k88074
k88074

Reputation: 2164

Log a request with bunyan

I building an app with node.js and express. I have started using bunyan but I am having a hard time understanding hot to log requests.

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.

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. 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.

Any suggestion is highly appreciated.

Upvotes: 2

Views: 6013

Answers (2)

Tomty
Tomty

Reputation: 2022

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.

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.

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.

(And by the way, I hope in your question when you wrote {req: reqSerializer} you meant {req: bunyan.stdSerializers.req}.)

Upvotes: 3

onux
onux

Reputation: 61

The way I've implemented is to add a handler in app.js like this:

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

The reqSerializer function then contains what you would like to return, e.g.

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, e.g

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.

Upvotes: 6

Related Questions