我有一個需要日志檔案的專案,這就是我想使用winston 的原因。但是在它的運行時它可能會在某個時候崩潰,所以我做了一些測驗:
const winston = require('winston');
const logger = winston.createLogger({
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: 'combined.log' })
]
});
let i=100000;
while(i-->0){
logger.info('Hello world');
}
throw new Error('Error');
這基本上只是列印 hello world 100000 次而不是錯誤。我遇到的問題是,combined.log 僅在程式沒有崩潰時才被寫入(大概在最后)。那么為什么winston 只在運行完成后才寫入實際日志。即使可能有例外,我怎樣才能讓它寫入檔案?
編輯:
有趣的是,如果您在錯誤之間添加 1 秒的延遲,它會起作用
const winston = require('winston');
const fsp = require('fs').promises;
let a=async ()=>{
try{
await fsp.unlink('combined.log');
}catch(e){
}
const logger = winston.createLogger({
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: 'combined.log' })
]
});
let i=100000;
while(i-->0){
logger.info('Hello world');
}
//wait 1 seconds
await new Promise((resolve)=>setTimeout(resolve,1000));
// await new Promise((resolve,reject)=>{resolve()});
throw new Error('Error');
}
a()
uj5u.com熱心網友回復:
利用handleExceptions: true
const winston = require('winston');
const logger = winston.createLogger({
transports: [
new winston.transports.Console({handleExceptions: true}),
new winston.transports.File({ filename: 'combined.log',handleExceptions: true})
]
});
let i=100000;
while(i-->0){
logger.info('Hello world');
}
throw new Error('Error');
雖然,真的,你應該總是捕捉任何例外等
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/530994.html
標籤:节点.js温斯顿
