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