import * as shimmer from "shimmer" ; import { inspect } from "util" ; import { getLogLevel , LogLevel , setLogLevel } from "../utils/log" ; import { TraceContextService } from "./trace-context-service" ; type LogMethod = "log" | "info" | "debug" | "error" | "warn" | "trace" ; param contextService export function patchConsole ( cnsle , contextService ) { patchMethod ( cnsle , "log" , contextService ) ; patchMethod ( cnsle , "info" , contextService ) ; patchMethod ( cnsle , "debug" , contextService ) ; patchMethod ( cnsle , "error" , contextService ) ; patchMethod ( cnsle , "warn" , contextService ) ; patchMethod ( cnsle , "trace" , contextService ) ; } /**
 * Removes log patching to add DataDog's trace context.
 */ export function unpatchConsole ( cnsle ) { unpatchMethod ( cnsle , "log" ) ; unpatchMethod ( cnsle , "info" ) ; unpatchMethod ( cnsle , "debug" ) ; unpatchMethod ( cnsle , "error" ) ; unpatchMethod ( cnsle , "warn" ) ; unpatchMethod ( cnsle , "trace" ) ; } function patchMethod ( mod , method , contextService ) { if ( mod [ method ] . __wrapped !== undefined ) { return ; } shimmer . wrap ( mod , method , ( original ) => { let isLogging = false ; return function emitWithContext ( this , message ? , ... optionalParams ) { if ( isLogging ) { return original . apply ( this as any , arguments as any ) ; } isLogging = true ; let prefix = "" ; const oldLogLevel = getLogLevel ( ) ; setLogLevel ( LogLevel . NONE ) ; try { const context = contextService . currentTraceContext ; if ( context !== undefined ) { const { traceID , parentID } = context ; prefix = `[dd.trace_id=${ traceID } dd.span_id=${ parentID }]` ; if ( arguments . length === 0 ) { arguments . length = 1 ; arguments [ 0 ] = prefix ; } else { let logContent = arguments [ 0 ] ; if ( typeof logContent !== "string" ) { logContent = inspect ( logContent ) ; } arguments [ 0 ] = `${ prefix } ${ logContent }` ; } } } catch ( error ) { } setLogLevel ( oldLogLevel ) ; isLogging = false ; return original . apply ( this as any , arguments as any ) ; } ; } ) ; } function unpatchMethod ( mod , method ) { if ( mod [ method ] . __wrapped !== undefined ) { shimmer . unwrap ( mod , method ) ; } }