我能够将每个请求和错误消息记录到单独的日志文件(request.log和uncaughtExceptions.log)中,但想要将这两个文件合并为一个仅称为logs.log的文件,例如
var logmsg = {
'Request IP',
'Method':req.method,
'URL':req.originalUrl,
'statusCode':res.statusCode,
'headers':req.headers,
'Time':new Date(),
'ErrorMessage':'Error Message if any with file name with line number and proper error message'
};
工作代码:
const express = require('express');
const winston = require('winston');
require('express-async-errors');
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' });
}
我尝试过的事情:
logging.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: 'logs.log' }));
process.on('unhandledRejection', (reason, p) => {
throw p;
});
}
它显示奇怪的错误消息,我不知道如何解决。
错误消息:
server.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
const express = require('express');
const reqres = require('../middlewares/reqreslog');
module.exports = function(app){
//Every Request Response Logging Middleware
app.use(reqres);
app.get('/', async (req, res) => {
res.json("testing"+a);
});
});
reqreslog.js
var winston = require('winston');
module.exports = function(req, res, next) {
var logmsg = {
'Request IP':req.ip,
'Method':req.method,
'URL':req.originalUrl,
'statusCode':res.statusCode,
'headers':req.headers,
'Time':new Date(),
'ErrorMessage':'Display Error If Any for this request'
};
winston.log('info', logmsg);
next();
}
答案 0 :(得分:1)
Winston日志记录基于日志级别info,debug,error etc.
进行工作。如果要将所有内容记录到同一日志文件中,则必须设置级别info
。
const logger = winston.createLogger({
levels: winston.config.syslog.levels,
transports: [
new winston.transports.File({
filename: 'combined.log',
level: 'info'
})
]
});
process.on('unhandledRejection', (reason, p) => {
logger.error('exception occur');
throw p;
});
详细了解winstonjs中的日志级别-https://github.com/winstonjs/winston#using-logging-levels