Skip to content

Commit 1098d02

Browse files
authored
chore: configurable log level for application (#12379)
1 parent a453038 commit 1098d02

File tree

2 files changed

+29
-6
lines changed

2 files changed

+29
-6
lines changed

.env.example

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,8 @@ MAIL_PROVIDER='debug'
192192
# LOGGING
193193
# Enable additional audit logs for select mutations
194194
AUDIT_LOGS='true'
195+
# highest log level, 'debug' | 'info' | 'warn' | 'error', defaults to 'info'
196+
# LOG_LEVEL='info'
195197

196198
#
197199
# DEVELOPER VARIABLES

packages/server/utils/Logger.ts

Lines changed: 27 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,21 @@ import tracer from 'dd-trace'
22
import formats from 'dd-trace/ext/formats'
33
import 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+
620
const 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+
5071
export 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

Comments
 (0)