node.js - 元在 Winston-mongodb 中为空
问题描述
我正在使用 winston-mongodb 模块来记录请求响应。
记录器服务.ts
const options = {
console: {
db: DB_URL,
level: 'info',
format: format.combine(format.timestamp(), format.json()),
collection: 'logs',
},
error: {
db: DB_URL,
level: 'error',
format: format.combine(format.timestamp(), format.json()),
collection: 'logs',
}
};
const logger = createLogger({
transports: [
new MongoDB(options.console),
new MongoDB(options.error)
],
});
服务器.ts
server.listen(port, () => {
logger.info({message:`Server is up and running on port ${port}`, meta: {
myProp: 'foo'
}});
);
结果:
{
"_id" : ObjectId("5ed8bd2c726d273004b082ca"),
"timestamp" : ISODate("2020-06-04T09:21:48.835Z"),
"level" : "info",
"message" : "Server is up and running on port 4000 HI",
**"meta" : null**
}
我正在尝试将元数据添加到记录器。但它在结果中添加了 null 。
解决方案
要获取存储在元中的 err 对象(及其所有 javascript 属性),您需要指定:
format.metadata()
在 createLogger 调用中。
这是一个工作示例代码:
// Declare winston
const winston = require("winston");
// Import all needed using Object Destructuring
const { createLogger, format, transports } = require("winston");
const { combine, timestamp, printf } = format;
// Export the module
module.exports = function (err, req, res, next) {
const logger = createLogger({
level: "error",
format: combine(
format.errors({ stack: true }), // log the full stack
timestamp(), // get the time stamp part of the full log message
printf(({ level, message, timestamp, stack }) => {
// formating the log outcome to show/store
return `${timestamp} ${level}: ${message} - ${stack}`;
}),
format.metadata() // >>>> ADD THIS LINE TO STORE the ERR OBJECT IN META field
),
transports: [
new transports.Console(), // show the full stack error on the console
new winston.transports.File({
// log full stack error on the file
filename: "logfile.log",
format: format.combine(
format.colorize({
all: false,
})
),
}),
new winston.transports.MongoDB({
db: "mongodb://localhost/logdb",
// collection: "log",
level: "error",
storeHost: true,
capped: true,
// metaKey: 'meta'
}),
],
});
logger.log({
level: "error",
message: err,
});
// Response sent to client but nothing related to winston
res.status(500).json(err.message);
};
推荐阅读
- c# - 如果我在实体框架代码优先方法中从静态方法保存数据,为什么记录没有保存在数据库中?
- java - 删除下游 ChangeLog 对象 KafkaStreams
- c++ - DLLImport C++ To .NET - char*(指向字符串的指针)
- julia - 如何在 MacOS 上为 Julia 测试做 PackageSpec()?
- python-3.x - Python - 如果打印特定单词,我如何附加数据?
- conemu - cd 回到 Cmder 中的先前位置
- excel - 允许基于数据验证的非空白单元格
- python-3.x - tkinter 根据其他输入更改 optionsMenu
- python - pip install from repo programmatically results in error "No such file or directory"
- c - 读取字节之间的位