Is it possible to log error messages using morgan?

Viewed 3935

I am logging request and responses using morgan and everything is working fine. I would like to know if there is any way in which I could log the error messages too? For ex: if a try catch block fails in my application, I am returning a 500 error and a custom message back to the user. But is there a way in which I could log the actual error.message?

Snippet from my app

 try {
     // Resend OTP
     let otp_server_response = await sms.resendOTP(mobile_number, resend_mode);

     if(otp_server_response.type === "success") {
         return res.status(200).json({ message: "OTP_RESENT" });
     } else {
         console.log(otp_server_response.message); // <= Log this message in morgan logs if request reaches here
         return res.status(400).json({ message: "OTP_RESENDING_FAILED" });
     }
 }
 catch (error) {
     console.log(error.message); // <= Log this message in morgan logs if request reaches here
     return res.status(500).json({ message: "SOME_ERROR_OCCURRED" });
 }

Snippet of my logger file

 const errorLogFormat    = ":requestId :status :res[content-length] :response-time ms";
 .
 .
 .
 // Log error responses (4xx and 5xx)
            morganLogger(
                errorLogFormat,
                {
                    skip: (req, res) => {
                        return res.statusCode < 400
                    },
                    stream: rfs(
                        "responses.log",
                        {
                            interval: "1d",
                            path: logDirectory
                        }
                    )
                }
            )
1 Answers

Don't think so. From my knowledge, this module doesn't contain actual errors. That being said, You could just save the error in your error handler with something like

req.error = err;

and then you can access req.error in your custom token.

Related