2017-09-22 71 views
0

我一直在使用winston將日誌推送到logmatic近一年,本週我不得不關閉它,因爲我得到了隨機連接錯誤,導致生產服務器崩潰。我把它作爲一個臨時解決方案來關閉,但我更喜歡像try/catch這樣的東西,我嘗試過但沒有成功。捕獲錯誤:getaddrinfo ENOTFOUND使用winston

這裏是我當前的代碼:

const Winston = require('winston') 
require('winston-logstash') 

const transports = [] 
transports.push(new Winston.transports.Console({ 
    level: 'debug', 
    colorize: true, 
    prettyPrint: true 
})) 

try { 
    transports.push(new (Winston.transports.Logstash)({ 
    level: 'info', 
    port: 10514, 
    host: 'api.logmatic.asdsadio', 
    meta: { logmaticKey: 'Xen03ppdS_Cm24hxbz1_kg' }, 
    node_name: 'api' 
    })) 

    const logger = new (Winston.Logger)({ 
    transports: transports 
    }) 
} 
catch (err) { 
    console.log(err) 
} 

module.exports = logger 
+0

爲什麼你需要嘗試/趕上,如果你關掉它? – alexmac

+0

而try/catch應該設置爲不傳輸初始化,而是設置爲每個調用'logger。 ()調用。但它沒有意義。 – alexmac

+0

@alexmac,所以我可以安全地打開它,我共享的代碼正在使用該服務。這是我的本地環境,在生產中它已關閉 –

回答

1

只是初始化你的記錄,當你弄清楚爲什麼你的連接錯誤後,你可以做

const methods = ['info', 'warn', 'error']; 
methods.forEach(method => { 
    logger[method] = new Proxy(logger[method], { 
     apply: function(target, thisArg, args) { 
      try { 
       target.call(logger, ...args); 
      } catch(error) { 
       console.error(error); 
      } 
     }, 
    }); 
}); 

。至少,它應該防止崩潰。它會基本攔截每個電話logger.info,logger.warn,logger.error並將它們包裹在try catch上。

+0

我認爲它的工作原理,因爲沒有更多的崩潰。謝謝! –