-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
71 lines (64 loc) · 1.94 KB
/
index.js
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
const { createLogger, format, transports } = require('winston');
const { combine } = format;
const LEVEL_TO_STACKDRIVER_NAME = {
emerg: 'EMERGENCY',
alert: 'ALERT',
crit: 'CRITICAL',
error: 'ERROR',
warn: 'WARNING',
notice: 'NOTICE',
info: 'INFO',
debug: 'DEBUG'
};
module.exports = {
/**
* Creates a new Winston logger that logs to stdout using JSON and maps log
* levels to Stackdriver severity levels.
* @return {winston.Logger} Winston logger instance
*/
createLogger: function() {
const log = createLogger({
transports: [
new transports.Console(),
],
format: combine(
format(info => {
info.severity = LEVEL_TO_STACKDRIVER_NAME[info.level];
delete info.level;
return info;
})(),
format.json()
)
});
return log;
},
/**
* Creates an Express middleware that creates a child logger for each
* request that includes the current trace.
* @param {winston.Logger} Winston logger instance
* @param {StackdriverTracer} Stackdriver tracer agent
* @return {function(req, res, next)} Express middleware function
*/
createExpressMiddleware: function(log, traceAgent) {
return function(req, res, next) {
req.log = log.child({
'logging.googleapis.com/trace': getCurrentTrace(traceAgent)
});
next();
};
}
};
function getCurrentTrace(agent) {
if (!agent || !agent.getCurrentContextId || !agent.getWriterProjectId) {
return null;
}
const traceId = agent.getCurrentContextId();
if (!traceId) {
return null;
}
const traceProjectId = agent.getWriterProjectId();
if (!traceProjectId) {
return null;
}
return `projects/${traceProjectId}/traces/${traceId}`;
}