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:

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:

Here are the configurations of this plugin in my logging.json :

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 :

The following code will be used to call the SMTP Appender: