node.js - 是否可以使用 Morgan 记录错误消息?

标签 node.js express logging morgan

我正在使用 morgan 记录请求和响应,一切正常。我想知道是否有任何方法可以记录错误消息?例如:如果我的应用程序中的 try catch block 失败,我将向用户返回 500 错误和自定义消息。但是有没有一种方法可以记录实际的 error.message

我的应用程序的片段

 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" });
 }

我的记录器文件的片段

 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
                        }
                    )
                }
            )

最佳答案

不这么认为。据我所知,该模块不包含实际错误。话虽如此,您可以使用类似

的内容将错误保存在错误处理程序中
req.error = err;

然后您可以在自定义 token 中访问 req.error。

关于node.js - 是否可以使用 Morgan 记录错误消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58544361/

相关文章:

node.js - Puppeteer 未在 Mac 10.14 中启动 Chromium

javascript - 如何附加json字段的nodejs Sequelize 模型列表

node.js - 如何在 NodeJS 中创建具有唯一 id 的路由

python - 每个应用程序实例的单独记录器名称

c++ - 控制台/文件记录器库 C++

javascript - Node.js API 设计和路由处理

node.js - 手动添加文件到package.json?

node.js - spotify-web-api- Node : authorizationCodeGrant() give a 400 - Bad Request

javascript - 每次在 server.js 上听到路径时都会执行express app.use

Bash - 比较 2 个文本文件并找到缺失的行