[Logger] Use Logger to send error on email

I would like to add winston-nodemailer as driver so that every error generated by the application is sent by email.

Others logging levels goes to file. How can I do that?

Thank

1 Like

I think Adonis has everything you need!

  1. Setup a global error handler with:

adonis make:exception Handler

This should create a file app/Exceptions/Handler.js

'use strict'

const BaseExceptionHandler = use('BaseExceptionHandler')

/**
 * This class handles all exceptions thrown during
 * the HTTP request lifecycle.
 *
 * @class ExceptionHandler
 */
class ExceptionHandler extends BaseExceptionHandler {
  /**
   * Handle exception thrown during the HTTP lifecycle
   *
   * @method handle
   *
   * @param  {Object} error
   * @param  {Object} options.request
   * @param  {Object} options.response
   *
   * @return {void}
   */
  async handle (error, { request, response }) {
    response.status(error.status).send(error.message)
  }

  /**
   * Report exception for logging or debugging.
   *
   * @method report
   *
   * @param  {Object} error
   * @param  {Object} options.request
   *
   * @return {void}
   */
  async report (error, { request }) {
    console.log(error)
    
    // Add your code to send email here.

  }
}

module.exports = ExceptionHandler

  1. Under async report(), call your code to send an email!

I really like Adonis Mail module that can be setup (see https://adonisjs.com/docs/4.1/mail)

Then send your email as simple as this (once you’ve configured Mail of course)

      await Mail.send('emails.error', { error }, message => {
        message
          .to('admin@myapp.com')
          .from('errors@myapp.com')
          .subject('Generic Application Error')
      })

This will use the templateresources/view/emails/error.edge (which you need to create first:

<h1>Generic Error</h1>

<p>

Your app just encounter the following error:

{{ error }}

</p>
<br>

<p>
    Sincerely,<br>
    Your App

</p>

Side note, if you started your Adonis project as API only, you will need to add the view provider to render your emails if you use Adonis Mail. Add these to your start/app.js

  '@adonisjs/framework/providers/ViewProvider',
  '@adonisjs/mail/providers/MailProvider',

You could totally use Winston node-mailer, but it might be easier to use the tools Adonis already gives you instead of trying to write a custom transport for Logger (which is based on Winston)

Hope this helps!

-Ryan

4 Likes

Hi, sorry for the delay in responding which was very thorough, thank you.