-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
53 lines (46 loc) · 1.37 KB
/
index.js
File metadata and controls
53 lines (46 loc) · 1.37 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
import {Context, ContextBuilder} from "js-context"
const loggerSym = Symbol("winston-logger")
/**
* adds winston log functions to context, adding context values to the log
* i.e. ctx.info("message goes here")
* @param {Context|ContextBuilder} ctx
* @param {Object} logger winston logger
*/
export function withLogger(ctx, logger) {
const builder = new ContextBuilder()
//add our logger
builder.with(loggerSym, logger)
//add the 'log' function
builder.withCtxFunction('log', (ctx, ...args) => {
const obj = buildCtxLogObject(ctx)
const logger = getLogger(ctx).child(obj)
logger.log(...args)
})
//add any custom levels/default levels
for(const level in logger.levels) {
builder.withCtxFunction(level, (ctx, ...args) => {
const obj = buildCtxLogObject(ctx)
const logger = getLogger(ctx).child(obj)
logger[level](...args)
})
}
return builder.build(ctx)
}
function buildCtxLogObject(ctx) {
const val = {}
for(const key in ctx) {
if(ctx[key] instanceof Context) {
val[key] = buildCtxLogObject(ctx[key])
} else {
val[key] = ctx[key]
}
}
return val
}
function getLogger(ctx) {
const logger = ctx[loggerSym]
if(!logger) {
throw new Error("Winston logger not defined on context")
}
return logger
}