node.js - 如何在 Winston 中为自定义日志格式添加额外参数?
问题描述
当您 console.log 时,您可以添加额外的参数:
console.log("The message", { foo: 123 });
这将打印消息以及第二个参数(和任何其他参数)的序列化版本。我使用 Winston 创建自定义日志格式,如下所示:
const winston = require('winston');
const logFormat = winston.format.printf(({ level, message, timestamp }) => {
return `${timestamp} ${level}: ${message}`;
});
const logger = winston.createLogger({
level: 'info',
format: winston.format.combine(winston.format.timestamp(), logFormat),
transports: [
new winston.transports.File({ filename: './logs/error.log', level: 'error' }),
new winston.transports.File({ filename: './logs/combined.log' })
]
});
这将在执行时忽略任何额外的参数logger.info("This gets in the logs", { this: "not" });
如何使用 Winston 实现与 console.log 类似的行为?
解决方案
您可以 JSON.stringify 整个事情并将其放入记录器或使用 + (执行连接)而不是 a , (不这样做)
logger.info("This gets in the logs"+ JSON.stringify({ this: "not" }));
希望这可以帮助
推荐阅读
- google-cloud-platform - Google Cloud Build - 查看日志权限
- android - 无法在单元测试中访问“Transformations.map”中的值
- java - 如何过滤多个字段的搜索查询?
- spring - Spring Integration JDBC 执行次数统计
- python-3.5 - ImportError 无法导入名称“dump_options_header”
- ruby - 在 Ruby on rails 中为 1 亿条记录生成 CSV/Excel 文件?
- bash - 从 XML 文档中获取信息并进行比较
- sql - 合并和删除重复条目
- c - 运动问题,跳过字段
- c++ - 用 cudaMemPrefetchAsync 替换 cudaMemcpy2D