简体   繁体   English

使用bunyan记录请求

[英]Log a request with bunyan

I building an app with node.js and express. 我用node.js构建应用程序并表达。 I have started using bunyan but I am having a hard time understanding hot to log requests. 我已经开始使用bunyan但是我很难理解要记录请求的热点。

Say that my router calls a function like this: 假设我的路由器调用了这样的函数:

function(request, someOtherStuff, done){\\do something}

where request is generated from a POST request, and has some stuff in request.body . request是从POST请求生成的,并且在request.body包含一些内容。

I would like to do the following: when an error occurs inside the function I would like to log the error, as well as the request (including the req.body ) from the user. 我想执行以下操作:当函数内部发生错误时,我想记录该错误以及用户的请求(包括req.body )。 Something like: 就像是:

if(err) {
  bunyan.error(err,request);
  done(err);
}

I know I can use serializers: {req: reqSerializer} in the bunyan configuration, but I could not find any examples where a request is actually logged. 我知道我可以在bunyan配置中使用serializers: {req: reqSerializer} ,但是我找不到实际记录请求的任何示例。

Any suggestion is highly appreciated . 任何建议都受到高度赞赏

The way I've implemented is to add a handler in app.js like this: 我实现的方法是在app.js中添加一个处理程序,如下所示:

app.use(function(req, res, next){
    log.info(reqSerializer(req));
    next();
});

The reqSerializer function then contains what you would like to return, eg 然后,reqSerializer函数包含您想要返回的内容,例如

function reqSerializer(req) {
   return {
        method: req.method,
        url: req.url,
        headers: req.headers,
        somethingCustom: ...,
    }
}

Also make sure the reqSerializer is included when you initialise the logger, eg 还要在初始化记录器时确保包括reqSerializer,例如

var log = bunyan.createLogger({
    name: 'myapp',
    serializers: {
        req: reqSerializer
    },
}

So all the serializer does is serialize the req object, you still need to actually pass it to the logger for it to be logged. 因此,序列化器所做的全部工作就是序列化req对象,您实际上仍然需要将其传递给记录器以进行记录。

What the serializer does is make sure that if you pass a field named "req" when writing a log record, it will be properly formatted. 串行器的作用是确保在写入日志记录时如果传递名为“ req”的字段,则该字段将被正确格式化。

So, once you have that serializer, you might log an error with a request simply by calling: 因此,一旦有了该序列化程序,就可以简单地通过调用以下命令记录错误:

logger.error({ req: request, err: err }, "Optionally, some message");

Where logger is the result of calling bunyan.createLogger with some parameters. 其中logger是使用某些参数调用bunyan.createLogger的结果。

You might also want to look into something like morgan that's specifically designed for logging requests, or perhaps bunyan-request if you're looking for something more structured. 您可能还需要研究专门为记录请求而设计的morgan之类的东西,或者,如果您正在寻找更结构化的东西,则可能要查找bunyan请求

(And by the way, I hope in your question when you wrote {req: reqSerializer} you meant {req: bunyan.stdSerializers.req} .) (顺便说一句,我希望在您写{req: reqSerializer}您的意思是{req: bunyan.stdSerializers.req} 。)

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM