Code coverage report for node/src/integrations/datadog-interceptor.ts

Statements: 20.83% (5 / 24)      Branches: 0% (0 / 27)      Functions: 0% (0 / 7)      Lines: 22.73% (5 / 22)      Ignored: none     

All files » node/src/integrations/ » datadog-interceptor.ts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 541 1   1                         1                       1                                                  
import {Interceptor, Tags, Message, LogLevel, Providers} from '@btilford/ts-base-core';
import {EventOptions, StatsD} from 'hot-shots';
 
import {internal, FilterLogMessage} from '@btilford/ts-base-core';
 
 
export type DatadogInterceptorOptions = {
  datadog?: StatsD;
  filter: FilterLogMessage;
  eventOptions: EventOptions;
  extractTitle: (context: Message) => string;
  extractText: (context: Message) => string | undefined;
  tags?: (context: Message) => Tags;
  onErr?: (err: Error) => void;
}
 
export const defaultDatadogInterceptorOptions: DatadogInterceptorOptions = {
  filter: context => context.level.gte(LogLevel.ALERT),
  eventOptions: {
    // eslint-disable-next-line @typescript-eslint/camelcase
    alert_type: 'error',
    priority: 'normal',
  },
  extractTitle: context => context.message,
  extractText: context => context.data?.args?.find(arg => arg instanceof Error)?.stack || undefined,
};
 
 
export function datadogInterceptor(options: DatadogInterceptorOptions = defaultDatadogInterceptorOptions): Interceptor {
  const log = internal.logger('DataDogInterceptor');
  return function forwardLogs(context: Message): void {
    const datadog = options.datadog || Providers.provide(StatsD);
    if (datadog) {
      if (options.filter(context)) {
        const tags = options.tags ? options.tags(context) : undefined;
        const title = options.extractTitle(context);
        const text = options.extractText(context);
        datadog.event(title, text, options.eventOptions, tags, (error: Error | undefined, bytes: any) => {
          if (error) {
            log.warn('Error forwarding event to Datadog! event:%o', context, error);
            if (options.onErr) {options.onErr(error);}
          }
          else {
            console.debug('Sent event to Datadog', bytes);
          }
        });
      }
    }
    else {
      log.warn('Unable to forward event to datadog! No StatsD provider available!');
    }
  }
}