This repository was archived by the owner on Apr 8, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.js
More file actions
276 lines (230 loc) · 7.28 KB
/
index.js
File metadata and controls
276 lines (230 loc) · 7.28 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
/*
Create loggers based on 'debug', with labels based on relative filepath
use as follows:
const lgr = require(THIS_MODULE)(__filename)
lgr.log('hi')
lgr.log.lazy('some preprocessed data', () => 'lazily evaluated data')
lgr.error('some error')
assuming that the file in which the logger is located at path `src/someFile.js`
in relation to CWD, executing it as follows:
```
env DEBUG='*' node src/someFile.js
```
should give the following output:
```
dvf:LOG:src/fileDebugTest.js hi +0ms
dvf:LOG:src/fileDebugTest.js some pre-processed lazily evaluated data +0ms
dvf:ERROR:src/fileDebugTest.js some error +0ms
```
The DEBUG env var con be used to control which loggers will produce output.
For example:
DEBUG='dvf:*'
will cause all logs which start with `dvf:` to be output to console
DEBUG='dvf:ERROR:*'
will result in only calls to `lgr.error` to be logged
DEBUG="dvf:*:$RELATIVE_FILE_PATH"
will show all types of logs but only from the file with the specified path
within the project
The lazy loggers can be used to log stuff which requires some pre-processing. If
any of the arguments passed to those loggers is a function, it will be called to
get the value to be logged, however this will only happen if given logger is
enabled. This way we can avoid paying for pre-processing if the value would not
have been logged anyway.
*/
const debug = require('debug')
const { stringify, stringifySimple } = require('./stringify')
// This is a string, or a regex, which will be matched against the __filename.
// Whatever it matches will be removed.
const defaultRoot = process.env.DVF_LOGGER_ROOT
// This is the directory from which node process was launched.
// We use it as default root since it gives relative paths which can be
// clicked on (in terminals such as iTerm) to open the file in an editor.
|| `${process.cwd()}/`
const PRETTY = Boolean(process.env.PRETTY)
const { DEPTH } = process.env
const EXTRA_PROPS = JSON.parse(process.env.EXTRA_PROPS || '{}')
const EXTRA_ERROR_PROPS = JSON.parse(process.env.EXTRA_ERROR_PROPS || '{}')
|| ({
'@type':
'type.googleapis.com/google.devtools.clouderrorreporting.v1beta1.ReportedErrorEvent',
})
const LEVELS = ['DEBUG', 'LOG', 'WARN', 'ERROR', 'EMERGENCY']
const simpleTypes = [
'bigint',
'boolean',
'number',
'string',
'symbol',
'undefined',
]
let globalCustomFormatters = {}
const expandThunks = array =>
array.map(elem => (typeof elem === 'function' ? elem() : elem))
const makeLazyLogger = strictLogger => (strictLogger.enabled
// call it with functions expanded to actual values
? (...args) => strictLogger.apply(strictLogger, expandThunks(args))
: () => {})
const parseArgs = (args, extraTypesForMessage) => {
let message = ''
const data = args
.map(arg => {
if (simpleTypes.includes(typeof arg)) {
message += `${stringifySimple(arg)}`
} else if (arg instanceof Error) {
if (!message) {
message = arg.message
}
return {
name: arg.name,
message: arg.message,
data: arg.data,
stack: arg.stack,
}
} else if (typeof arg === 'object') {
if (extraTypesForMessage && extraTypesForMessage.length) {
for (const extraType of extraTypesForMessage) {
if (arg instanceof extraType) {
message += ` ${stringify(arg, DEPTH)}`
}
}
return arg
}
return arg
}
return undefined
})
.filter(Boolean)
return { message, data }
}
const formatData = data => {
if (simpleTypes.includes(typeof data)) {
return `${stringifySimple(data)}`
}
if (typeof data === 'object') {
return data
}
}
const invalidInvocation = (args, extraTypesForMessage) => {
console.error(new Error('INVALID_LOG_INVOCATION'))
return parseArgs(args, extraTypesForMessage)
}
const findException = data => {
if (!data) return
const items = [data, data.error, data.err]
const error = items.find(item => item instanceof Error)
return error
}
const stringifyException = exception =>
`${exception.name} ${exception.message}\n${exception.stack}`
const parseArgsV2 = (args, extraTypesForMessage) => {
if (args.length === 1) {
if (typeof args[0] === 'string') {
return {
message: args[0],
}
}
if (args[0] instanceof Error) {
return {
message: stringifyException(args[0]),
error: args[0],
}
}
return invalidInvocation(args, extraTypesForMessage)
}
if (args.length > 2) {
return invalidInvocation(args, extraTypesForMessage)
}
// Standard log format, [message, data]
const [message, data] = args
const exception = findException(data)
const finalMessage = exception
? `${message} | ${stringifyException(exception)}`
: message
return {
message: finalMessage,
data: formatData(data, DEPTH),
error: exception,
}
}
/** @typedef {(message: string, data?: Object | Error) => void} LoggerFunction */
/** @typedef {(exception: Error) => void} ErrorLoggerFunction */
/**
* @param {string} severity
* @param {string} context
* @param {Object} extraTypesForMessage
* @returns {LoggerFunction | ErrorLoggerFunction}
*/
const makeStrictLogger = (
severity,
context,
extraTypesForMessage,
hasErrorProps,
) => {
const debugLogger = debug(`dvf:${severity}:${context}`)
const logger = (...args) => {
if (!logger.enabled) return
const { message, data, error } = parseArgsV2(args, extraTypesForMessage)
const extraProps = {
'logging.googleapis.com/sourceLocation': {
file: context,
},
...(error && hasErrorProps && EXTRA_ERROR_PROPS),
...EXTRA_PROPS,
}
const payload = {
severity,
timestamp: Date.now(),
context,
message,
...(data && { data }),
...(error && { error }),
...(!PRETTY && extraProps),
}
if (PRETTY) {
const format = `${
new Date(payload.timestamp).toISOString()
} | ${payload.severity} | ${payload.context} |`
console.log(format, payload.message, payload.data)
} else {
console.log(stringify(payload, DEPTH, globalCustomFormatters))
}
}
logger.enabled = debugLogger.enabled || false
return logger
}
module.exports = (
filename,
options = { root: defaultRoot, extraTypesForMessage: [] },
) => {
const { root = defaultRoot, extraTypesForMessage } = options
const relativeFilePath = filename.replace(new RegExp(`^${root}`), '')
const loggers = {
debug: makeStrictLogger(LEVELS[0], relativeFilePath, extraTypesForMessage),
log: makeStrictLogger(LEVELS[1], relativeFilePath, extraTypesForMessage),
warn: makeStrictLogger(LEVELS[2], relativeFilePath, extraTypesForMessage),
error: makeStrictLogger(
LEVELS[3],
relativeFilePath,
extraTypesForMessage,
true,
),
emergency: makeStrictLogger(
LEVELS[4],
relativeFilePath,
extraTypesForMessage,
true,
),
}
// Decorates each logger with .lazy prop, which contains the lazy version
// of the logger.
Object.values(loggers).forEach(logger => {
logger.lazy = makeLazyLogger(logger)
})
return loggers
}
/**
* @type {(globalFormatters: {[typeName: string]: (Object) => string}}
*/
module.exports.setGlobalCustomFormatters = globalFormatters => {
globalCustomFormatters = globalFormatters
}