简体   繁体   English

如何在 winston 中设置自定义错误日志格式

[英]How do I set custom error log format in winston

winston default format for error log is too big it includes many thing like date,process,memoryUsage,os,trace etc. winston 错误日志的默认格式太大,它包含许多内容,如date,process,memoryUsage,os,trace等。
How do i remove unwanted things from log?如何从日志中删除不需要的东西?

logging.js日志记录.js

const express = require('express');
const winston = require('winston');

module.exports = function() {
  winston.handleExceptions(
    new winston.transports.File({ filename: 'uncaughtExceptions.log' }));

  process.on('unhandledRejection', (ex) => {
    throw ex;
  });

  winston.add(winston.transports.File, { filename: 'request.log' });

}

server.js服务器.js

const express = require('express');
const winston = require("winston");
const app = express();

//to Log errors
require('./startup/logging')();
//routes will contains all the routes list
require('./startup/routes')(app);

//PORT
const port = process.env.PORT || 3000;
app.listen(port,() => winston.info(`Listening on port ${port}....`));

routes.js路由.js

const express = require('express');
module.exports = function(app){
   app.get('/', async (req, res) => {
        res.json("testing"+a);
    });
});

Above route has error like undefined variable 'a' which I am able to log, but the file name and line number is wrong.上面的路线有像未定义变量 'a' 这样的错误,我可以记录,但文件名和行号是错误的。

uncaughtExceptions.log未捕获的异常.log

{"date":"Wed Oct 31 2018 16:45:33 GMT+0530 (India Standard Time)","process":{"pid":9680,"uid":null,"gid":null,"cwd":"D:\\nodejs\\synchronizer","execPath":"C:\\Program Files\\nodejs\\node.exe","version":"v8.11.2","argv":["C:\\Program Files\\nodejs\\node.exe","D:\\nodejs\\synchronizer\\server.js"],"memoryUsage":{"rss":40591360,"heapTotal":23990272,"heapUsed":19075672,"external":18278915}},"os":{"loadavg":[0,0,0],"uptime":3474.217938},"trace":[{"column":28,"file":"D:\\nodejs\\synchronizer\\startup\\routes.js","function":"app.get","line":52,"method":"get","native":false},{"column":5,"file":"D:\\nodejs\\synchronizer\\node_modules\\express\\lib\\router\\layer.js","function":"Layer.handle [as handle_request]","line":95,"method":"handle [as handle_request]","native":false},{"column":13,"file":"D:\\nodejs\\synchronizer\\node_modules\\express\\lib\\router\\route.js","function":"next","line":137,"method":null,"native":false},{"column":3,"file":"D:\\nodejs\\synchronizer\\node_modules\\express\\lib\\router\\route.js","function":"Route.dispatch","line":112,"method":"dispatch","native":false},{"column":5,"file":"D:\\nodejs\\synchronizer\\node_modules\\express\\lib\\router\\layer.js","function":"Layer.handle [as handle_request]","line":95,"method":"handle [as handle_request]","native":false},{"column":22,"file":"D:\\nodejs\\synchronizer\\node_modules\\express\\lib\\router\\index.js","function":null,"line":281,"method":null,"native":false},{"column":12,"file":"D:\\nodejs\\synchronizer\\node_modules\\express\\lib\\router\\index.js","function":"Function.process_params","line":335,"method":"process_params","native":false},{"column":10,"file":"D:\\nodejs\\synchronizer\\node_modules\\express\\lib\\router\\index.js","function":"next","line":275,"method":null,"native":false},{"column":5,"file":"D:\\nodejs\\synchronizer\\middlewares\\reqreslog.js","function":"module.exports","line":12,"method":"exports","native":false},{"column":5,"file":"D:\\nodejs\\synchronizer\\node_modules\\express\\lib\\router\\layer.js","function":"Layer.handle [as handle_request]","line":95,"method":"handle [as handle_request]","native":false}],"stack":["ReferenceError: a is not defined","    at app.get (D:\\nodejs\\synchronizer\\startup\\routes.js:52:28)","    at Layer.handle [as handle_request] (D:\\nodejs\\synchronizer\\node_modules\\express\\lib\\router\\layer.js:95:5)","    at next (D:\\nodejs\\synchronizer\\node_modules\\express\\lib\\router\\route.js:137:13)","    at Route.dispatch (D:\\nodejs\\synchronizer\\node_modules\\express\\lib\\router\\route.js:112:3)","    at Layer.handle [as handle_request] (D:\\nodejs\\synchronizer\\node_modules\\express\\lib\\router\\layer.js:95:5)","    at D:\\nodejs\\synchronizer\\node_modules\\express\\lib\\router\\index.js:281:22","    at Function.process_params (D:\\nodejs\\synchronizer\\node_modules\\express\\lib\\router\\index.js:335:12)","    at next (D:\\nodejs\\synchronizer\\node_modules\\express\\lib\\router\\index.js:275:10)","    at module.exports (D:\\nodejs\\synchronizer\\middlewares\\reqreslog.js:12:5)","    at Layer.handle [as handle_request] (D:\\nodejs\\synchronizer\\node_modules\\express\\lib\\router\\layer.js:95:5)"],"level":"error","message":"uncaughtException: a is not defined","timestamp":"2018-10-31T11:15:33.714Z"}

The question is how do I log user defined error log format like:问题是我如何记录用户定义的错误日志格式,例如:

timestamp:filename:errorlinenumber:errormessage:

Above log format is default which includes unnecessary stuff.上面的日志格式是默认的,其中包括不必要的东西。

You need to create a winston formatter and extract the relevant fields from the info object it provides.您需要创建一个 winston格式化程序并从它提供的info对象中提取相关字段。

Here is the solution:这是解决方案:

logger.js记录器.js

const express = require('express');
const { createLogger, format, transports } = require('winston');
const { combine, timestamp, label, printf } = format;

const myFormat = printf(info => {
  return (info.timestamp + " | " +
          info.trace[0].file + ":" + info.trace[0].line + " | " +
          info.message.split("\n")[0]);
});

module.exports = function() {
  const logger = createLogger({
    format: combine(timestamp(), myFormat)
  });

  logger.exceptions.handle(new transports.File({ filename: 'uncaughtExceptions.log' }));

  process.on('unhandledRejection', (reason, p) => {
    throw reason;
  });
}

Output:输出:

2018-11-01T13:42:54.927Z | /home/runner/routes.js:4 | uncaughtException: a is not defined

If you need other fields just console.log(info) in myFormat , then extract what you need.如果您只需要myFormat console.log(info)其他字段,请提取您需要的内容。 Cheers!干杯!

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

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