forked from stoshiya/express-fluent-logger
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
92 lines (82 loc) · 2.66 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
"use strict"
const logger = require("fluent-logger")
const debug = require("debug")("fluentd-logger-middleware")
/**
* Create a fluentd logger middleware.
*
* @public
* @param {Object}
* @return {Function}
*/
exports = module.exports = function fluentdLoggerMiddleware(options) {
const defaultOptions = {
source: "Access",
level: "info",
mode: "development",
tag: "debug",
label: "server",
configure: { host: "127.0.0.1", port: 24224, timeout: 3.0 },
responseHeaders: [],
}
options = Object.assign(defaultOptions, options)
logger.configure(options.tag, options.configure)
logger.on("error", debug)
return function(req, res, next) {
var start = new Date()
function emitHandler() {
res.removeListener("finish", emitHandler)
res.removeListener("close", emitHandler)
var record = {
timestamp: start.getTime(),
"remote-address": req.ip,
method: req.method,
url:
req.protocol + "://" + req.get("host") + req.originalUrl
? req.originalUrl
: req.url,
"http-version": req.httpVersion,
status: res.statusCode,
"content-length": res.get("content-length"),
referrer: req.get("referrer") || req.get("referer") || "",
"response-time": new Date() - start,
}
/**
* Request Headers
*/
Object.keys(req.headers)
.filter(key => {
return (
key !== "host" &&
key !== "connection" &&
key !== "referrer" &&
key !== "referer"
)
})
.forEach(key => {
key = key.toLowerCase()
record[key] = req.get(key)
})
/**
* Response Headers
*/
options.responseHeaders
.filter(key => {
return res.get(key)
})
.forEach(key => {
key = key.toLowerCase()
record[key.toLowerCase()] = res.get(key)
})
logger.emit(options.label, {
source: options.source,
level: options.level,
mode: options.mode,
record,
})
}
res.on("finish", emitHandler)
res.on("close", emitHandler)
req.logger = logger
next()
}
}