We can use the log4js library for logging errors. Log4js is a light-weight and flexible plugin. To install this plugin in our application, we will run the following command in the terminal:
1 |
npm install log4js |
After installation of this plugin, we will need to configure it. There are multiple ways to configure it as the plugin is very flexible. We will be configuring it in the logging.json. This plugin works with “Appenders”. Every appender is a destination for logging messages when an error occurs. I had set it up to print the error on the console, but now we will also send an email whenever an error occurs! We will also require an SMTP Appender to send emails. To install SMTP appender for log4js, we will run the following command in the terminal:
1 |
npm install @log4js-node/smtp |
Here are the configurations of this plugin in my logging.json :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
{ "appenders": { "email": { "type": "@log4js-node/smtp", "transport": { "plugin": "smtp", "options":{ "host": "smtp.sendgrid.net", "auth":{ "user":"USERNAME", "pass":"PASSWORD" }, "port": 465 } }, "recipients": "example@example.com", "sender": "no-reply@example.com", "sendInterval": 60, "subject":"Error" } }, "categories": { "default": { "appenders": [ "email" ], "level": "error" //change this according to your requirement } } } |
This configuration will send an email using the SMTP server, for every log event of level ERROR and above. Finally, when we want to use this plugin, we need to use the following code :
The following code will be defined at the beginning of the controller :
1 2 3 |
let log4js = require("log4js"); log4js.configure("config/logging.json"); let logger = log4js.getLogger(); |
The following code will be used to call the SMTP Appender:
1 |
logger.error("This send you an email!", err); |
Recent Comments