all files / modules/middleware/ logger.js

83.33% Statements 15/18
57.14% Branches 8/14
75% Functions 3/4
83.33% Lines 15/18
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                                                                   
/* jshint -W058 */
const strftime = require("strftime").strftime;
const {isNil} = require("ramda");
 
function defaultMessageHandler(message) {
    if (typeof console !== "undefined" && console.log) {
        console.log(message);
    }
}
 
/**
 * A middleware that writes log entry data about the response to a given stream.
 * Log entries are formatted similarly to Apache httpd's Common Log Format
 * (see http://httpd.apache.org/docs/1.3/logs.html#common).
 */
function logger(app, messageHandler) {
    messageHandler = messageHandler || defaultMessageHandler;
 
    return function (conn) {
        const startTime = Date.now();
 
        return conn.call(app).then(function () {
            const elapsedTime = Date.now() - startTime;
            let contentLength = conn.response.headers["Content-Length"];
 
            Iif (isNil(contentLength)) {
                contentLength = "-";
            }
 
            let protocol = conn.protocol || "http:";
            protocol = protocol.substr(0, protocol.length - 1).toUpperCase();
 
      // 127.0.0.1 - frank [10/Oct/2000 13:55:36] "GET /apache_pb.gif HTTP/1.0" 200 2326 0.003
            messageHandler([
                conn.remoteHost || "-",
                "-", // RFC 1413 identity of the client
                conn.remoteUser || "-",
                `[${strftime("%d/%b/%Y %H:%M:%S", new Date)}]`,
                `"${conn.method} ${conn.basename}${conn.path} ${protocol}/${conn.version}"`,
                conn.status,
                contentLength,
                elapsedTime / 1000
            ].join(" "));
        });
    };
}
 
module.exports = logger;