@@ -2,7 +2,21 @@ import tracer from 'dd-trace'
22import formats from 'dd-trace/ext/formats'
33import util from 'util'
44
5- type LogLevel = 'error' | 'warn' | 'info' | 'debug'
5+ const Levels = {
6+ error : 1 ,
7+ warn : 2 ,
8+ info : 3 ,
9+ debug : 4
10+ } as const
11+ type LogLevel = keyof typeof Levels
12+
13+ const LOG_LEVEL = Levels [ ( process . env . LOG_LEVEL || 'info' ) as LogLevel ]
14+ if ( ! LOG_LEVEL ) {
15+ throw new Error (
16+ `Invalid LOG_LEVEL: ${ process . env . LOG_LEVEL } , allowed values are: ${ Object . keys ( Levels ) . join ( ', ' ) } `
17+ )
18+ }
19+
620const LogFun = {
721 error : console . error ,
822 warn : console . warn ,
@@ -47,10 +61,17 @@ function trace(level: LogLevel, message: any, ...optionalParameters: any[]) {
4761 LogFun [ level ] ( JSON . stringify ( record ) )
4862}
4963
64+ const bindIfEnabled = ( level : LogLevel ) => {
65+ if ( Levels [ level ] <= LOG_LEVEL ) {
66+ return trace . bind ( null , level )
67+ }
68+ return ( ) => { }
69+ }
70+
5071export const Logger = {
51- log : trace . bind ( null , 'info' ) ,
52- error : trace . bind ( null , 'error' ) ,
53- warn : trace . bind ( null , 'warn' ) ,
54- info : trace . bind ( null , 'info' ) ,
55- debug : trace . bind ( null , 'debug' )
72+ log : bindIfEnabled ( 'info' ) ,
73+ error : bindIfEnabled ( 'error' ) ,
74+ warn : bindIfEnabled ( 'warn' ) ,
75+ info : bindIfEnabled ( 'info' ) ,
76+ debug : bindIfEnabled ( 'debug' )
5677}
0 commit comments