All files / middlewares logger.js

100% Statements 24/24
100% Branches 8/8
100% Functions 2/2
100% Lines 24/24
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          1x 1x   1x   1x 8x 8x 8x 8x   8x 1x     8x 9x 9x 9x 9x   9x 9x     1x 1x 1x     9x                     9x 1x     9x        
/**
 * Middleware to print logs
 **/
'use strict';
 
const assert    = require('assert');
const bytes     = require('bytes');
 
const LarkLog   = require('lark-log');
 
module.exports = (app) => {
    assert(app.config.has('log'), 'No log config found!');
    const config = app.config.get('log');
    const logger = new LarkLog(config);
    app.logger = logger;
 
    if (app.config.has('autoloader') && global.$) {
        global.$.logger = logger;
    }
 
    return async (ctx, next) => {
        const now = Date.now();
        ctx.logger = logger;
        ctx.log = logger;
        let error = null;
 
        try {
            await next();
        }
        catch (e) {
            logger.error(e.stack);
            error = e;
            throw e;
        }
        finally {
            const message = {
                method: ctx.method.toUpperCase(),
                url: ctx.url,
                header: ctx.headers,
                ip: ctx.ip,
                ips: ctx.ips,
                cost: `${Date.now() - now}ms`,
                status: ctx.status,
                length: bytes(Buffer.byteLength(JSON.stringify(ctx.body || ''), 'utf-8')),
            };
 
            if (error instanceof Error) {
                message.error = error.message;
            }
 
            logger.access(JSON.stringify(message));
        }
    };
};