-
Notifications
You must be signed in to change notification settings - Fork 0
/
logger.js
92 lines (74 loc) · 1.96 KB
/
logger.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
'use strict';
// Utility for JSON logging
// Helps to bundle all logs for the same request together
// in a single JSON object
const httpContext = require('express-http-context');
// Allow setting indention for JSON logs for readability when running locally
let INDENT = null;
if (process.env.IMGSRV_LOG_INDENT) {
INDENT = ' ';
}
const VERBOSE = process.env.IMGSRV_VERBOSE == '1';
const SOURCENAME = process.env.IMGSRV_SOURCENAME || 'imgsrv';
const getLog = function() {
let log = httpContext.get('log');
if (!log) {
log = {};
httpContext.set('log', log);
}
return log;
};
const print = function(obj) {
let data = JSON.stringify(obj, null, INDENT);
if (obj.errors) {
console.error(data);
} else if (VERBOSE) {
console.log(data);
}
};
module.exports = {
init: function(requestId, url) {
let log = getLog();
log.source = SOURCENAME || 'imgsrv';
log.requestID = requestId;
log.url = url;
log.timestamp = (new Date()).toUTCString();
},
write: function(key, value) {
let log = getLog();
if (typeof(key) == 'object') {
Object.assign(log, key);
} else {
log[key] = value;
}
},
warning: function(message) {
let log = getLog();
let warnings = log.warnings;
if (!warnings) {
log.warnings = warnings = [];
}
warnings.push(message);
},
error: function(ex) {
let log = getLog();
let errors = log.errors;
if (!errors) {
log.errors = errors = [];
}
errors.push({ 'message': ex.message, 'stack': ex.stack });
},
flush: function() {
let log = getLog();
print(log);
},
writeNoRequest: function(value) {
print(value);
},
requestId: function() {
let log = getLog();
return log.requestID;
},
verbose: VERBOSE,
sourceName: SOURCENAME
};