Search code examples
node.jssendgridlog4js-node

How to use non SMTP transport in log4js smtp appender?


If you read the log4js documentation for SMTP appender, you'll see example for SMTP transport, which even does not work well with latest nodemailer (I'm using nodemailer 1.3.0 at the time of writting).

Docs show this bad config as an example:

{ "appenders": [
    {
        "type": "smtp",
        "recipients": "[email protected]",
        "sendInterval": 60,
        "transport": "SMTP",
        "SMTP": {
            "host": "smtp.gmail.com",
            "secureConnection": true,
            "port": 465,
            "auth": {
                "user": "[email protected]",
                "pass": "bar_foo"
            }
        }
    }
] }

How to change config to use transport other than SMTP? What I want is to configure log4js to work with SendGrid.


Solution

  • After a couple of hours of trial and error, I found out the solution. Here is the example log4js configuration with console and smtp appenders:

    sendgridTransport = require('nodemailer-sendgrid-transport');
    
    log4js.configure({
        appenders: [{
            type: 'console'
        }, {
            type: 'logLevelFilter',
            level: 'ERROR',
            appender: {
                type: 'smtp',
                recipients: '[email protected]',
                sender: '[email protected]',
                sendInterval: 60,
                transport: sendgridTransport({
                    auth: {
                        api_user: config.smtpUsername,
                        api_key: config.smtpPassword
                    }
                })
            }
        }]
    });
    

    You can use any other transport in the similar way. Supporter transports are all the ones supported by nodemailer (for example: AWS SES, SMTP, ...). See the documentation for transport you want to use to learn how to instantiate it.