wzp
2021-05-13 7d694a9113118daec5be7ac224dab46a3b20f106
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
// Copyright 2012 Mark Cavage, Inc.  All rights reserved.
 
'use strict';
 
var assert = require('assert-plus');
 
var shallowCopy = require('./utils/shallowCopy');
 
///--- API
 
/**
 * Sets up a child [bunyan](https://github.com/trentm/node-bunyan) logger with
 * the current request id filled in, along with any other parameters you define.
 *
 * You can pass in no options to this, in which case only the request id will be
 * appended, and no serializers appended (this is also the most performant); the
 * logger created at server creation time will be used as the parent logger.
 * This logger can be used normally, with [req.log](#request-api).
 *
 * This plugin does _not_ log each individual request. Use the Audit Logging
 * plugin or a custom middleware for that use.
 *
 * @public
 * @function requestLogger
 * @param    {Object}   [options] - an options object
 * @param    {Array}    [options.headers] - A list of headers to transfer from
 *                                  the request to top level props on the log.
 * @returns  {Function} Handler
 * @example
 * server.use(restify.plugins.requestLogger({
 *     properties: {
 *         foo: 'bar'
 *     },
 *     serializers: {...}
 * }));
 */
function requestLogger(options) {
    assert.optionalObject(options);
    var opts = options || {};
 
    var props;
 
    if (opts.properties) {
        props = shallowCopy(opts.properties);
    } else {
        props = {};
    }
 
    if (opts.serializers) {
        props.serializers = opts.serializers;
    }
 
    var headersToCopy = opts.headers || [];
 
    return function bunyan(req, res, next) {
        if (!req.log && !opts.log) {
            next();
            return;
        }
 
        var log = req.log || opts.log;
 
        props.req_id = req.getId();
        headersToCopy.forEach(function forEach(k) {
            if (req.headers[k]) {
                props[k] = req.headers[k];
            }
        });
        req.log = log.child(props, props.serializers ? false : true);
 
        if (props.req_id) {
            delete props.req_id;
        }
 
        next();
    };
}
 
///--- Exports
 
module.exports = requestLogger;