【发布时间】:2019-11-12 18:02:47
【问题描述】:
我尝试将信息消息和错误消息存储在 winston 记录器文件中,它成功运行。但我希望将可自定义的错误存储在 winston 记录器文件中。如何解决它
winston.js
var myFormat = winston.format.combine(winston.format.timestamp({format:'YYYY-MM-DD HH:mm:ss.SSS'}),
winston.format.json())
const logger = winston.createLogger({
level: 'info',
format: myFormat,
defaultMeta: { service: 'user-service' },
transports: [
//
// - Write to all logs with level `info` and below to `combined.log`
// - Write all logs error (and below) to `error.log`.
//
new winston.transports.Console(),
new winston.transports.File({ filename: 'error.log', level: 'error' }),
new winston.transports.File({ filename: 'combined.log' })
],
exceptionHandlers: [
new winston.transports.Console(),
new winston.transports.File({ filename: './exceptions.log', timestamp: true, maxsize: 1000000 })
],
});
//
// If we're not in production then log to the `console` with the format:
// `${info.level}: ${info.message} JSON.stringify({ ...rest }) `
//
if (process.env.NODE_ENV !== 'production') {
logger.add(new winston.transports.Console({
format: winston.format.simple()
}));
}
module.exports = logger;
authentication.js
const authMiddleware = function (userPermissionLevels) {
return (request, response, next) => {
const token = request.header('x-auth-token');
if (!token) return response.status(401).send("no token provided");
const decoded = jwt.verify(token, config.get('jwtPrivateKey'));
// Check for permissions
if (!userPermissionLevels.includes(decoded.userPermissionLevels)) return response.status(403).send("Access denied.");
request.user = decoded;
next();
}
}
I want to store "no token provided" and access deined error in winston logger file.How to acheive it.
【问题讨论】: