Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i use custom logger in fastify?

My company have a custom developed logger package, and we want to use that as default logger in fastify. I tried to understand how to register my logger with this simple example below, but fastify always use Pino.

index.js

const log = require("./Logger");
const fastify = require("fastify")({ logger: log });

fastify.get("/", (request, reply) => {
    request.log(
        "includes request information, but is the same logger instance as `log`"
    );
    reply.send({ hello: "world" });
});

fastify.listen(3000)

logger.js

function Logger(...args) {
    this.args = args;
}
Logger.prototype.info = function(msg) {
    console.log("myLogger", msg);
};

logger.js also contains error, debug, fatal, warn, trace, child functions but the functions body is same.

The result is:

{"level":30,"time":1553095994942,"msg":"Server listening at http://127.0.0.1:3000","pid":14543,"hostname":"VirtualBox","v":1}

whitch is the default Pino output.

like image 505
d-t Avatar asked Mar 20 '19 15:03

d-t


Video Answer


2 Answers

as explained here, your logger

must have the following methods

So this example works:

function Logger(...args) {
  this.args = args;
}
Logger.prototype.info = function (msg) { console.log("myLogger", msg); };
Logger.prototype.error = function (msg) { console.log("myLogger", msg); };
Logger.prototype.debug = function (msg) { console.log("myLogger", msg); };
Logger.prototype.fatal = function (msg) { console.log("myLogger", msg); };
Logger.prototype.warn = function (msg) { console.log("myLogger", msg); };
Logger.prototype.trace = function (msg) { console.log("myLogger", msg); };
Logger.prototype.child = function () { return new Logger() };


const myLogger = new Logger()
const app = require('fastify')({
  logger: myLogger
})

app.get("/", (request, reply) => {
  request.log.info('hi');
  reply.send({ hello: "world" });
});

app.listen(3000)

Here you can check the logger validation applied to your parameter

like image 80
Manuel Spigolon Avatar answered Sep 18 '22 14:09

Manuel Spigolon


in case you need log4js, this is a customized logger that supports json event. you c

import log4js from "log4js";

import {log4jsConfig} from "./log4js.config.js";

log4js.addLayout('json', function (config) {
    return function (logEvent) {
        logEvent.application = 'my-app';
        logEvent.processId = process.pid;
        if (process.env.IP) {
            logEvent.ip = process.env.IP;
        }
        if (process.env.ENV) {
            logEvent.ENV = process.env.ENV;
        }
        if (logEvent.data && logEvent.data.length > 0) {
            logEvent.message = logEvent.data[0];
            delete logEvent.data;
        }
        return JSON.stringify(logEvent);
    };
});
const log = log4js.getLogger('engine');

log4js.configure(log4jsConfig);

export class AndromedaLogger {
    logger;
    loggerOptions;

    constructor(args) {
        this.logger = log;
    }

    get Logger() {
        return this.logger;
    }

    static configGlobal(options) {
        this.loggerOptions = options;
    }

    info(message) {
        this.logger.info(message);
    }

    error(message, trace) {
        this.logger.error(`${message} -> (${trace || 'trace not provided !'})`);
    }

    warn(message) {
        this.logger.warn(message);
    }

    debug(message, context) {
        this.logger.debug(message);
    }

    trace(message, context) {
        this.logger.trace(message);
    }

    fatal(message, context) {
        this.logger.fatal(message);
    }

    child() {
        return new AndromedaLogger()
    };


}

log4js config:

const _log4jsConfig = {
  appenders: {},
  categories: {
    default: {
      appenders: [],
      level: 'trace',
    },
  },
};

_log4jsConfig.appenders.stdout = {
  type: 'stdout',
  layout: { type: 'colored' },
};

_log4jsConfig.appenders['file'] = {
  type: 'file',
  filename: 'logs/app.log',
  maxLogSize: 104857600,
  numBackups: 3,
};

_log4jsConfig.categories.default.appenders.push('stdout');
_log4jsConfig.categories.default.appenders.push('file');

export const log4jsConfig = _log4jsConfig;
like image 24
Ben Rhouma Zied Avatar answered Sep 19 '22 14:09

Ben Rhouma Zied