-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
51 lines (51 loc) · 1.87 KB
/
index.js
File metadata and controls
51 lines (51 loc) · 1.87 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
"use strict";
const {onFinished} = require("on-finished");
const {MongoClient} = require('mongodb');
/**
*
* koa2 request/response logger function
* @param {Object} options object containing the parameters
* @param {String} options.url mongodb connection string
* @param {String} options.db mongodb log database name
* @param {String} options.collection mongodb log collection name
*/
module.exports = function(options) {
const url = options.url || 'mongodb://localhost:27017/';
const db = options.db || 'logs';
const collection = options.collection || 'koalogs';
return async function logger(ctx,next) {
let err;
try {
await next();
} catch (e) {
err = e;
} finally {
onFinished(ctx.response,async () => {
const logObj = {
url: ctx.request.href,
method: ctx.request.method,
status: ctx.status,
request: ctx.request.body,
response: ctx.response.body,
user_agent: ctx.header['user-agent'],
event_time: new Date()
};
if (typeof ctx.header['remoteip'] != undefined) {
logObj['remote_addr'] = ctx.header['remoteip'];
} else if (ctx.get('X-Forwarded-For') != '') {
let forwardedIpsStr = ctx.get('X-Forwarded-For');
let forwardedIp = forwardedIpsStr.split(',')[0];
logObj['remote_addr'] = forwardedIp;
}
const client = new MongoClient(url);
await client.connect();
const dbo = client.db(db);
await dbo.collection(collection).insertOne(logObj);
await client.close();
});
}
if (err) {
throw err;
}
}
};