Search code examples
javascriptnode.jswinston

Catch Error: getaddrinfo ENOTFOUND using winston


I've been using winston to push logs to logmatic for almost a year, and this week I had to turn it off because I get random connection errors which crash the production server. I turned it off as a temporal fix, but I would prefer something like a try/catch, which I tried but didn't work.

Here's my current code:

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

Solution

  • You could do

    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);
                }
            },
        });
    });
    

    just after initializing your logger while you're figuring out why you get connections error. At least, it should prevent crashes. It will basically intercepts each call to logger.info, logger.warn, logger.error and wrap them around a try catch.