microsoft / applicationinsights-node.js Goto Github PK
View Code? Open in Web Editor NEWMicrosoft Application Insights SDK for Node.js
License: MIT License
Microsoft Application Insights SDK for Node.js
License: MIT License
Hi,
I am using the library in my client side node.js project and I need to track the pageview data. However, I found this function is not implemented in the latest version('0.15.11') yet.
Wondering if there is a plan to implement this function? Is there a workaround for the current version?
Hi,
Thanks for this module. Can I please request a TypeScript definition file that is added to the DefinitelyTyped library?
https://github.com/borisyankov/DefinitelyTyped
Thanks.
This used to work in 0.10 (and I think 0.11), but in 0.12 the process exits before the post request is able to transmit data (https://github.com/Microsoft/AppInsights-node.js/blob/master/applicationInsights.ts#L138-L147).
I don't think there's a good way to fix this, the Error
should be re-thrown immediately after it is tracked to avoid letting the app continue in an unstable state. It might work to do a synchronous file stream write before re-throwing the error, then reading the data from disk when the app starts.
I'm leaving it as-is since people might be using it in older versions of node without issue, but it would be good to find a better long-term solution.
It appears that the trackEvent
function (as well as others) are not sending the session cookies to App Insights with the event.
Ex. I have a App Insights configured on the browser of a webpage served up by node. The client side script creates the ai_session and ai_user cookies. When I post that form, I get those cookies back in the form post on the server, but the event tracking isn't identifying those cookies automatically like when I use the C# package for App Insights.
Is there another way to send the App Insights cookies through the trackEvent
function so that I can tie my end user's page view and server telemetry together? Should it be set as metadata?
I have a Node app running on my localhost, and I'm receiving the following error when I invoke my trackEvent method. Not sure if there's a limitation with using app insight via browserify, as Im able to write logs to my instance when I run the same code below in my server.js script.
Fetch API cannot load http://dc.services.visualstudio.com/v2/track. Request header field content-encoding is not allowed by Access-Control-Allow-Headers in preflight response.
index.debug.js:1245 ApplicationInsights:Sender [TypeError: Failed to fetch
at TypeError (native)]0: TypeError: Failed to fetch
at TypeError (native)length: 1__proto__: Array[0]
Here's my code.
import appInsights from 'applicationinsights';
import env_properties from '../../config';
setupLogging(){
appInsights.setup(env_properties.APPINSIGHTS_INSTRUMENTATIONKEY).start();
appInsights.client.trackEvent("login", {message: "Logging worked"});
},
Here's the outputted request header from verbose logging
headers: Object
Content-Encoding: "gzip"
Content-Length: 473
Content-Type: "application/x-json-stream"
https://github.com/Microsoft/ApplicationInsights-node.js/blob/master/Library/Client.ts#L88
/**
* Log an exception you have caught.
* @param exception An Error from a catch clause, or the string error message.
* @param properties map[string, string] - additional data used to filter events and metrics in the portal. Defaults to empty.
* @param measurements map[string, number] - metrics associated with this event, displayed in Metrics Explorer on the portal. Defaults to empty.
*/
public trackException(exception:Error, properties?:{ [key: string]: string; }) {
if(!Util.isError(exception)) {
exception = new Error(<any>exception);
}
var data = ExceptionTracking.getExceptionData(exception, true, properties)
this.track(data);
}
https://github.com/Microsoft/AppInsights-node.js/blob/master/applicationInsights.ts#L247-L253
This needs to be updated to remove the port number when the x-forwarded-for header is read. The back-end rejects the whole payload if this is included in the IP address field.
Unlike the .NET (or browser JavaScript) library, this library does not allow you to pass in additional properties to the .trackMetric function.
You can do it for the other types of telemetry like events and dependencies, but not metrics.
ContractsModule.Contracts.MetricData object has a spot for properties, so doesn't seem like it would break the model.
JSSDK sets ai_user cookie which should be associated with the request. NodeSDK does parse ai_session cookie but doesn't look at ai_user.
I think we should be able to add meta data to the metrics we track similar to the C# library.
This could be something I'm doing wrong, but the following results in a request and a trace being logged in Application Insights - but for neither of those to be related to the other (not showing in 'Related Items').
appInsights.trackRequest(req, res);
appInsights.trackTrace(JSON.stringify(trace));
Here do not set any device type as we do in .NET. It will assume PC
than
If an application immediately shuts down after logging an event, for example, it can happen that the events are dropped and never written to disk for later submission. It seems that there is a sync implementation of it, but it is not exposed in the API.
If it were, we could always call that method when listening on process exit: process.on('exit'...
Run the code below and the app won't exit after console.log()
var appInsights = require("applicationinsights");
var c = appInsights.getClient("key");
c.trackEvent('some event', {'version': 'foo'});
console.log('All done');
When there is no data to send Client.sendPendingData doesn't call callback which is passed as a paramerter. In that case it is impossible to determine whether we complete work with Application Insights Client or not.
Consider to use https://github.com/broofa/node-uuid instead of Util.NewGuid() function.
The CPU metrics being sent by the node sdk are being rejected by the app insights endpoint.
If you enable verbose logging you can see this response from the endpoint:
WaWorkerHost.exe Information: 0 : ApplicationInsights:Sender [ '{"itemsRecieved":58,"itemsAccepted":42,"errors":[{"index":0,"statusCode":400,"message":"Metric at index[0] '% cpu[0] user' name contains invalid character '['"},{"index":1,"statusCode":400,"message":"Metric at index[0] '% cpu[1] user' name contains invalid character '['"},{"index":2,"statusCode":400,"message":"Metric at index[0] '% cpu[2] user' name contains invalid character '['"},{"index":3,"statusCode":400,"message":"Metric at index[0] '% cpu[3] user' name contains invalid character '['"},{"index":4,"statusCode":400,"message":"Metric at index[0] '% cpu[4] user' name contains invalid character '['"},{"index":5,"statusCode":400,"message":"Metric at index[0] '% cpu[5] user' name contains invalid character '['"},{"index":6,"statusCode":400,"message":"Metric at index[0] '% cpu[6] user' name contains invalid character '['"},{"index":7,"statusCode":400,"message":"Metric at index[0] '% cpu[7] user' name contains invalid character '['"},{"index":29,"statusCode":400,"message":"Metric at index[0] '% cpu[0] user' name contains invalid character '['"},{"index":30,"statusCode":400,"message":"Metric at index[0] '% cpu[1] user' name contains invalid character '['"},{"index":31,"statusCode":400,"message":"Metric at index[0] '% cpu[2] user' name contains invalid character '['"},{"index":32,"statusCode":400,"message":"Metric at index[0] '% cpu[3] user' name contains invalid character '['"},{"index":33,"statusCode":400,"message":"Metric at index[0] '% cpu[4] user' name contains invalid character '['"},{"index":34,"statusCode":400,"message":"Metric at index[0] '% cpu[5] user' name contains invalid character '['"},{"index":35,"statusCode":400,"message":"Metric at index[0] '% cpu[6] user' name contains invalid character '['"},{"index":36,"statusCode":400,"message":"Metric at index[0] '% cpu[7] user' name contains invalid character '['"}]}' ]
Hi,
I've added a tag to my client context for setting my custom device id. It works well on traces, but I don't see the device id as a grouping criteria in metrics. Is it supported and correctly sent in metrics?
Thanks!
A majority of the unit tests are not enabled. This should be corrected.
See also:
https://github.com/Microsoft/AppInsights-node.js/blob/master/Tests/UnitTests.ts
Currently, the project source control contains TypeScript definitions of third-party components. TSD provides better mechanism to get TypeScript definitions (similar to NPM).
Hi,
I'm working on a transport for Winston logger and I'd like to map Winston log levels to AI's trace levels. I've seen an enumeration of supported levels in the "Contracts" module, but I am not sure on how to extract those values for using in my code. What's the suggested way?
Thanks!
This should be available by 4/10. This will most likely break the following: https://github.com/Microsoft/AppInsights-node.js/blob/master/applicationInsights.ts#L62-L69
The contains a few fixes to JS in addition to supporting the latest bond schemas https://github.com/Microsoft/bond.
When encountering exceptions in VS Code we take measures remove any PII, esp. from stack traces. However, Client#trackException counters that effort by throwing new errors in case it doesn't understand the given one and thereby leaking stack traces that include PII.
I just realized the require("os");
module provides a way to track cpu/memory/network.
https://nodejs.org/api/os.html
The application insights user interface now supports custom metrics so the idea here is to collect custom metrics to capture system performance. This will be exposed similar to appInsights.trackAllHttpServerRequets
, maybe appInsights.trackSystemMetrics()
and it will capture aggregate metrics at a configurable interval.
For some reason I can't get trackMetric to work.
My code is something like
var appInsights = require("applicationinsights");
appInsights.setup("<id>").start();
appInsights.client.trackEvent("Hello World");
appInsights.client.trackMetric("RegisteredPushChannels", Math.random * 1000);
The event Hello World shows up but I cannot find anywhere RegisteredPushChannels in the Metrics Explorer.
Any ideas?
Best regards
Ferdinand
This field is used to determine the source of data if there are processing errors in the backend services.
Please support envirnment variable based config like Azure Storage.
After running npm install applicationinsights, I get the following error:
var ai = require('applicationinsights')
>node test.js
module.js:338
throw err;
^
Error: Cannot find module 'applicationinsights'
at Function.Module._resolveFilename (module.js:336:15)
at Function.Module._load (module.js:278:25)
at Module.require (module.js:365:17)
at require (module.js:384:17)
at Object.<anonymous> (C:\cb\td\win8\temp\test.js:1:72)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:501:10)
When having both JSSDK and NodeJS SDK the latter takes session id from cookies and sets it to requests. The logic parses the cookie incorrectly - it should take only the 1st part of cookie (before first occurrence of "|").
Currently, clients share a sequence number counter:
class Client {
private static _sequencePrefix =
Util.int32ArrayToBase64([
Util.random32(),
Util.random32(),
Util.random32(),
Util.random32()]) +
":";
private static _sequenceNumber = 0;
//...
}
The sequence number should be unique for each client.
Hi! I'm having trouble getting any data to show up. No data is coming across when it is run from Azure or OSX. I'm using Node.js 0.12.0 on Azure and 0.12.1 on OS X. I double checked that APPINSIGHTS_INSTRUMENTATION_KEY
was set to the correct key both places. Any ideas. Here is the code:
https://github.com/ctaggart/SourceLink-Proxy/blob/appinsights/server.ts#L7-L11
Log request url pathname as ai.operation.name
for each request
The TravisCI badge on the home page points to the fork I created a few weeks ago. It would be better to enable TravisCI for the main repo and update the badge to point to that.
I've noticed this odd (probably wrong) behavior associated to the AutoCollection of Exceptions. In a brief: if "enableOfflineMode" if off, unhandled exceptions are not sent and pile up on disk.
Details follow:
If AutoCollection is enabled, all uncaught exceptions are trapped by "uncaughtException" event on the process. This causes the exception data to be sent to "handleCrash" method on Channel object with "isNodeCrashing" set to true. "handleCrash" sends the exception data to "saveOnCrash" and this method does not check if "_enableOfflineMode" is true. It just stores on disk.
If "_enableOfflineMode" if false, 2 (bad) things happen: Files are stored on disk even if this functionality is off. It may still make sense, since it's the only way to make unhandled exception collection work. But since "_enableOfflineMode" is false, files stored on disk are never sent.
So, ultimately:
Maybe it would be better to:
What do you think?
In our node server we collect various properties about the request throughout processing and place them in a context object. Whenever we log any app insights telemetry we add this context to the custom property bag. The only type for which this doesn't work is requests.
For requests tracking, we want to do something like this:
var context;
// process the request and add items to logging context throughout the pipeline
response.on('finish', function() {
appInsights.client.trackrequest(request, response, context);
});
Unfortunately this doesn't work because in the trackRequest implementation it actually listens for the response.on('finish') event which has already fired at this point. Here's the relevant snippet from the trackRequest method in the sdk:
if (response && response.once) {
response.once("finish", function () { return processRequest(); });
}
Additionally we want to set the operationId, userId, and operationParentId to our own custom values so we can correlate the request telemetry with other telemetry from inside and outside this application:
appInsights.client.context.tags[appInsights.client.context.keys.operationId] = loggingContext.requestId;
appInsights.client.context.tags[appInsights.client.context.keys.userId] = loggingContext.userId;
appInsights.client.context.tags[appInsights.client.context.keys.operationParentId] = loggingContext.clientRequestId;
But this doesn't work because the request is actually logged asynchronously and this context could have been reset by another request at that point.
I'm open to suggestions on how to implement this either in our client, or in the SDK itself. I think we basically need a trackRequest method that is synchronous.
Missing required field specification: The field 'iKey' is required but not present on source
As per subject, the public "dispose()" method in the main ApplicationInsights class calls "dispose()" on each internal static instances of console, exceptions, performance and requests. But in the implementation of those methods, not all resources are released. As an example:
https://github.com/Microsoft/ApplicationInsights-node.js/blob/master/AutoCollection/Exceptions.ts
class AutoCollectExceptions {
...
public enable(isEnabled: boolean) {
if(isEnabled) {
...
process.on("uncaughtException", this._exceptionListenerHandle);
}
} else {
...
process.removeListener("uncaughtException", this._exceptionListenerHandle);
...
}
}
}
public dispose() {
AutoCollectExceptions.INSTANCE = null;
// <<<<---- What about calling "this.enable(false)" here?
this._isInitialized = false;
}
Same goes for performance.
In my tests I use the "dispose()" method to reset AI's SDK to a pristine state. This is required because AI creates a global singleton and even reloading it with another require(), the same instance is returned due to node's module caching.
After some tests, node complains about an handler leek because handlers are added on each test.
My suggestion is to call "enable(false)" in the dispose call if you agree. I can make a PR for this if you like.
Currently all instances of this module share the same cache directory. This is a problem if several applications depend on it and run simultaneously.
cc @seanmcbreen
It would be nice if Device Id could identify instances of the application running from the same device. "node" is not unique enough to group events coming from multiple instances running on different devices.
The node sdk used to report a session object that contains an Id. It's not the case any more. Is this by design?
The sender should emit more detail when the appInsights.config.enableDebug
flag is set true
. At a minimum the response should be emitted to console: https://github.com/Microsoft/AppInsights-node.js/blob/master/Sender.ts#L55
Some modules (example) subclass Error
. When obj
is an instance of such, Util.isError(...)
returns false
.
// "[object Object]" !== "[object Error]"
return Object.prototype.toString.call(obj) === "[object Error]";
This issue causes the "Exception type" and "Failed method" properties in Azure Portal's Application Insights blade to display the error type and method name from this line in the Application Insights SDK for Node.js:
Error at Client.trackException
...instead of from the original error. Example:
OriginalErrorTypeName at originalFunctionName
I believe the implementation of Util.isError(...)
should be:
return obj instanceof Error;
Rejected by the backend (requirements recently changed, no method is required and must not be empty).
See related issue in JS SDK repo - microsoft/ApplicationInsights-JS#155
Update samples:
appInsights.getClient();
requires instrumentation keyappInsights.client
insteadThis will enable callers to wait for all data to finish sending
Is it possibile to enable sampling?
Please change configuration setting to APPINSIGHTS_INSTRUMENTATIONKEY. This is a setting name that will be set by Azure Web Sites automatically when you enabling Application Insights for it and it is aligned with azure web sites extensions and SDK for ASP.NET 5 configuration
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.