简体   繁体   English

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

[英]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.我的公司有一个定制开发的记录器包,我们想在 fastify 中使用它作为默认记录器。 I tried to understand how to register my logger with this simple example below, but fastify always use Pino.我试图通过下面这个简单的例子来了解如何注册我的记录器,但是 fastify 总是使用 Pino。

index.js索引.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记录器.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. logger.js还包含errordebugfatalwarntracechild函数,但函数体是相同的。

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. whiitch 是默认的 Pino 输出。

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

in case you need log4js, this is a customized logger that supports json event.如果您需要 log4js,这是一个支持 json 事件的自定义记录器。 you c你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: 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在其他类中使用 fastify 请求记录器而无需将其作为参数传递? - How can I use fastify request logger in other classes without having to pass it as a parameter? 我如何使用 pino 作为记录器? - How I can use pino as a logger? 我如何使用 fastify/static 和基于 header 的自定义路由来提供相同的路由? - How can I serve the same route with fastify/static and a custom route based on header? 如何在 Fastify 中使用 Jest 和 Supertest? - How to use Jest and Supertest with Fastify? 如何在 fastify 中使用 node-sspi - how to use node-sspi with fastify 如何使用 fastify 发送多个 URL 参数? - How to use fastify to send multiple URL parameters? 如何访问从客户端 JS 获取的文本响应以进行快速化? - How can I access the text response of a fetch from client JS to fastify? 如何将多部分文件流从 fastify-multipart 转发到第三部分 api? - How can I forward a mulitpart file stream from fastify-multipart to a 3rd part api? 我该如何解决这个错误'无法读取未定义的属性(读取'符号')'在fastify上 - How can i solve this error 'Cannot read properties of undefined (reading 'sign')' on fastify Fastify - 自定义错误处理程序中的 i18next - Fastify - i18next in custom error handler
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM