【问题标题】:How can I save my message errors in a log file? it writes the success message when it should write the error one如何将我的消息错误保存在日志文件中?它在应该写入错误一时写入成功消息
【发布时间】:2022-02-04 01:54:55
【问题描述】:

我需要创建一个 .log 文件,每次我运行我的代码时,它都会保存我的信息,显示它是否成功运行或是否有错误。 我编写了一个代码,以便每次代码正确运行时它都可以正常运行,我现在遇到的问题是,如果我有错误并且它没有运行,它会在同样的方式,它应该在什么时候显示错误消息。

这是我的代码:

// inserts data to a DB
function insertOffice(index) {
    ...
}

// Loops the function in order to make an insert each 0.5 seconds
function myLoop() {
    setTimeout(function () {
        let response = insertOffice(i);
        console.log('Running...');
        i++;
        if (i < offices.length) {
            myLoop();
        }
    }, 500)
}

// Runs the looper.
try {
    myLoop();
    logger.info('Success');
} catch (error) {
    console.log(error);
    logger.error(new Error(error));
}

这是我的 Winston 配置:

import *  as  winston from 'winston';
import { format, createLogger, transports } from "winston";
const { timestamp, combine, printf } = format;

const logFormat = printf(({ message, timestamp, stack }) => {
    return `${timestamp} : ${stack || message}`;
});

export const logger = createLogger({
    format: combine(
        format.colorize(),
        timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
        format.errors({ stack: true }),
        logFormat
    ),
    'transports': [
        new winston.transports.File({
            filename: 'logs/example.log'
        })
    ]
});

如您所见,计划是在 try catch 中运行该函数,因此当它失败(进入 catch)时,它会向我显示 logger.error(new Error(error));,但它似乎没有进入 catch。

当我进行插入并且一切正常时,在我的 example.log 文件中,它应该写成:

2022-02-03 08:25:18 : Success

确实如此,但是当我故意在代码中编写错误以检查它是否也适用于消息错误时,它不起作用,它仍然写入成功消息。

我已经在这里搜索了一些问题,例如 one,但在我看来,这不适合我的错误。

应该写在我的example.log时间戳和报错信息,但是没有。

消息错误的写法正确吗?

编辑: 我搜索并观看了这个question,这可能是因为 settimeout 导致了错误,但我仍然得到相同的结果,写的是成功消息而不是错误消息。

我注意到这可能是 try catch 的问题,但我找不到解决方案。

编辑:我添加了 Mojtaba 告诉我的内容,这样看:

function myLoop() {
    setTimeout(function () {
        try {
            let response = insertOffice(i);
            i++;
            if (i < offices.length) {
                myLoop();
            }
            //throw Error('unexpected Error');
            console.log('success');
        } catch (error) {
            console.log('failed');
        }
    }, 500)
}

【问题讨论】:

    标签: javascript node.js winston


    【解决方案1】:

    尝试运行这段代码..

    function myLoop() {
        setTimeout(function () {
           throw Error('unexpected Error')
        }, 500)
    }
    
    // Runs the looper.
    try {
        myLoop();
        console.log('success')
    } catch (error) {
        console.log('does it reach here??');
    }

    在此示例中:您看到setTimeout() 中发生错误时,它不会被您的 try and catch 语句捕获。

    您可以尝试使用以下代码结构:

    function myLoop() {
      setTimeout(function() {
        try {
          throw Error('unexpected Error')
          console.log('success')
        } catch (error) {
          console.log('does it reach here??');
        }
    
      }, 500)
    }
    
    // Runs the looper.
    
    myLoop();

    如果您对此示例有疑问,请尝试确定您的代码是否抛出任何错误。

    【讨论】:

    • 我只需在throw Error('unexpected Error') 上方添加我的let response = insertOffice(i); ... 就可以了,谢谢你的伙伴:)
    • 我用了你的第二个例子
    • @MartínJF Coo​​l Good For You :)) 祝你好运
    • 大声笑,我发现这是因为throw Error('unexpected Error') 对吧?当我评论该行时,我遇到了同样的问题,显示成功消息,知道为什么吗?
    • @MartínJF 如果您的代码没有抛出任何错误,则无法使用 try 和 catch 捕获。祝你好运
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-20
    • 1970-01-01
    相关资源
    最近更新 更多