microsoft / ApplicationInsights-node.js

Microsoft Application Insights SDK for Node.js
MIT License
325 stars 140 forks source link

Is there a way to see if applicationinsights has been initialised #1064

Open grug opened 1 year ago

grug commented 1 year ago

Hi there,

Is there a way to see if applicationinsights has been initalised? For instance, I have the following code:

    import * as appInsights from 'applicationinsights';

    appInsights.setup(applicationInsightsConnectionString);

    appInsights.start();

Later on in my code, I want to check to see if appInsights.start() has been called so I know that I should either call functions like trackException or trackTrace or warn the user that they haven't initialised things.

I had a look through the docs and it doesn't seem like there's a flag or way to determine this. Is my understanding correct and I'll have to track this myself?

hectorhdzg commented 1 year ago

@grug We use internal properties to track this so initialization works correctly and to prevent multiple starts, but we don't expose them, can you elaborate on your scenario?, setup should prepare everything for manual tracking, like track APIs that you mention, start will do auto instrumentation stuff, maybe you can check for appInsights.defaultClient to exist and should be enough.

grug commented 1 year ago

We have a logging service which is a thin wrapper over appInsights which looks something like this:

import * as appInsights from 'applicationinsights';
import { SeverityLevel } from 'applicationinsights/out/Declarations/Contracts';

interface LogServiceInitConfig {
  applicationInsightsConnectionString: string;
}

class LogService {
  public static init({
    sampleRate,
  }: LogServiceInitConfig) {
    appInsights.setup(applicationInsightsConnectionString);

    // some unimportant code omitted here...

    appInsights.start();
  }

  public static logError(
    exception: Error,
    properties: Record<string, unknown> = {},
    severity: SeverityLevel = SeverityLevel.Error
  ) {
    console.error(exception);
    appInsights.defaultClient?.trackException({
      severity,
      properties,
      exception,
    });
  }

  public static logEvent(
    message: string,
    properties: Record<string, unknown> = {},
    severity: SeverityLevel = SeverityLevel.Information
  ) {
    console.log(message);
    appInsights.defaultClient?.trackTrace({ message, severity, properties });
  }
}

export { LogService };
export type { LogServiceInitConfig };

Basically I'd like to warn the user that appInsights hasn't been set up properly if they haven't called init(). I can track this myself with a flag but was wondering if there was something that the library itself provided.

grug commented 1 year ago

You're right, though, checking for defaultClient existing would do the job :)