Code Monkey home page Code Monkey logo

applicationinsights-node.js's Issues

support TrackPageView()?

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?

Unhandled exception tracking doesn't work in node 0.12

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.

Insights cookies not sent with tracking functions

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?

Unable to properly setup App Insight logging to Azure Portal

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"

Documentation says that the trackException method takes a third parameter named measurements, but it is not actually defined in the method definition

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);
    }

trackMetric does not support setting custom properties

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.

Requests and Traces aren't related in Application Insights

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));

Provide a sync flush call

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'...

App hangs after trackEvent is called

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'); 

Auto collected CPU metric is rejected by app insights endpoint

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 '['"}]}' ]

Device.Id in metrics

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!

How to get severity level values

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!

Collect system metrics

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.

trackMetric not working

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

Cannot find module applicationinsights

After running npm install applicationinsights, I get the following error:

  • test.js
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)

Clients should not share a sequence number.

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.

Update TravisCI badge

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.

Exceptions are stored on disk even if offline mode is off and are never sent

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:

  1. Files will pile up forever on disk
  2. Unhandled Exceptions will not be sent

Maybe it would be better to:

  1. Not store exceptions to disk, since they will not be sent. It may happen that on first run offline mode is off, then switched on later. But its an odd scenario. If this is not the case, Exception files will be piled up forever.
  2. Try to send exceptions (only) on next start even if offline mode is off.

What do you think?

Cannot track request with custom properties determined during request processing

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.

Dispose not removing timers and exception handlers

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.

Device Id is always node

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.

Exception type and failed method incorrect for objects that are instances of Error subclass

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;

Sampling

Is it possibile to enable sampling?

Operation name missing in portal when calling trackDependency

I'm calling trackDependency to track calls to Azure Storage and although I'm passing an operation name as the second parameter it's not appearing in the portal:

metricsClient.trackDependency(blobService.host.primaryHost, 'listBlobsSegmented', (new Date().getTime() - started), !err);

screen shot 2015-11-30 at 1 05 18 pm

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.