How can i use custom logger in fastify?

0

Issue

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.

Solution

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

Answered By – Manuel Spigolon

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More