简体   繁体   中英

Node.js server outgoing http request logging format

I have nodejs server, and need to implement logging of outgoing requests.

Let's say I use node-request

const np = require('request-promise');
const logger = require('./winston-logger');

np.get('https://swapi.co/api/planets').
  .then(res => {
    logger.info( ??? )
  })
  .catch(err => {
    logger.error(err);
  })

My question what should I put in logger.info? Requested url, headers, response body? Is there popular and established by most devs format?

I was looking into this and didn't find sufficient solution. There is apache log format. But is that what is the best for nodejs apps? For example there is no time-response for request, what could be useful to log. And how it well working with winston logger? Also, I think this format should be well recognizable for logs parsers

Any thoughts how you approach logging for nodejs?

I tried to give you an answer with some dummy piece of code. I specifically used Winston for an application logging purpose.

In Winston, you may also define custom log parameters as well as json format or plain text format. Definitely, in the sample code, I did not use request or request-promise module but it well enough to get an idea that how Winston configure and used in an application.

package.json

{
  "name": "winston",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {
    "express": "4.16.2",
    "http": "0.0.0",
    "nodemon": "1.15.1",
    "winston": "2.4.0"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

logger.js

var winston = require('winston');
var logger = new (winston.Logger)({
  transports: [
    new winston.transports.File({
      filename: __dirname + '/logger.log',
      json: false,
      timestamp: function () {
        return new Date()
      },
      handleExceptions: true,
      humanReadableUnhandledException: true,
    })
  ],
  exceptionHandlers: [
    new winston.transports.File({ filename: __dirname + '/exceptions.log', json: false })
  ],
  exitOnError: false
});
module.exports = logger;
module.exports.stream = {
  write: function (message, encoding) {
    logger.info(message);
  }
};

index.js

const express = require('express');
const app = express();
const logger = require("./logger");

app.listen(3000, () => {
  logger.log("info", 'Example app listening on port 3000!');
  const data = require("./data")(app);
});

data.js

const logger = require("./logger"); logger.log("info", 'executes data.js');

module.exports = ((app) => {

    app.get('/', (req, res) => {
        logger.log("info", "Default route executes");
        res.send("hello world from data file");
    });

    app.get('/hello', (req, res) => {
        logger.log("info", "hello route executes");
        res.send("hello route executes");
    });

    app.use(function (err, req, res, next) {
        logger.log("info", "error routing called");
        logger.log("error", err);
        if (err.name === 'UnauthorizedError') {
            res.status(401).json({ status: 0, code: 401, type: "unauthorised", message: err.name + ": " + err.message });
        } else {
            res.status(404).json({ status: 0, code: 404, type: "ENOENT", message: "file not found" });
        }
    });
    return app;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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