我如何在 Fastify 中使用自定义记录器?

How can i use custom logger in fastify?

我公司有一个自定义开发的记录器包,我们想将其用作 fastify 中的默认记录器。我试图通过下面的这个简单示例了解如何注册我的记录器,但 fastify 始终使用 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 还包含 errordebugfatalwarntracechild 函数,但函数体相同。

结果是:

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

whitch 是默认的 Pino 输出。

here所述,您的记录器

must have the following methods

所以这个例子有效:

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 您可以检查应用于您的参数的记录器验证

如果你需要 log4js, 这是一个支持 json 事件的自定义记录器。 你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 配置:

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;