![](/img/trans.png)
[英]How to get the OriginURL using morgan and winston.js format in nodejs?
[英]Customize messages format using winston.js and node.js
我在我的 nodejs 項目中使用 winston.js,我正在尋找的是,將兩個不同的自定義消息輸出到不同類型的傳輸(控制台、文件)中。 控制台模式:
return `${timestamp} [${label}] ${level}: ${message}
文件模式(在文件中我只想顯示消息和級別):
return ` ${level} : ${message}
這是我的代碼:
const { createLogger, format, transports } = require('winston');
const { combine, timestamp, label, printf } = format;
const myFormat = printf(({ level, message, label, timestamp }) => {
return `${timestamp} [${label}] ${level}: ${message}`;
}
});
const logger = createLogger({
format: combine(
label({ label: 'hello |' }),
timestamp(),
myFormat
),
transports: [new transports.Console(),
new transports.File({
filename: api.log,
level: 'info'
})
]
});
logger.stream = {
write: function(message, encoding) {
logger.info(message);
},
};
module.exports = logger;
使用此代碼,我有相同的輸出,請問有什么幫助嗎?
從 Winston.js ver3 on Transport 接受格式
為了對不同的輸出使用不同的日志格式,您需要創建不同的 Format 對象並將它們傳遞給您的 Transport 構造函數。
所以在你的情況下:
${timestamp} [${label}] ${level}: ${message}
創建了 myFormat 而不是將它傳遞給createLogger
您需要將它傳遞給Console
構造函數。${level} : ${message}
創建另一種Format
${level} : ${message}
Format
傳遞給File
傳輸構造函數的format
屬性您可以在 winston.js 項目源中看到將不同格式傳遞給控制台的示例: https : //github.com/winstonjs/winston/blob/master/examples/quick-start.js
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.