簡體   English   中英

如何將我的消息錯誤保存在日志文件中? 它在應該寫入錯誤一時寫入成功消息

[英]How can I save my message errors in a log file? it writes the success message when it should write the error one

我需要創建一個 .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));
}

這是我的溫斯頓配置:

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 中運行 function,因此當它失敗(進入 catch)時,它會顯示logger.error(new Error(error)); 但它似乎沒有進入捕獲。

當我進行插入並且一切正常時,在我的example.log文件中,它應該寫成:

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

確實如此,但是當我故意在我的代碼中編寫錯誤以檢查它是否也適用於消息錯誤時,它不起作用,它仍然會寫入成功消息。

我已經在這里搜索了一些問題,例如這個問題,但在我看來,它不適合我的錯誤。

它應該寫在我的example.log時間戳和消息錯誤中,但它沒有。

這是寫消息錯誤的正確方法嗎?

編輯:我搜索並觀看了這個問題,這可能是因為 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)
}

嘗試運行此代碼..

 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 和 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();

如果您對此示例有疑問,請嘗試確定您的代碼是否拋出任何錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM