golang中如何在不退出程序的情况下记录错误?

AVa*_*arf 2 logging go

我每 5 分钟运行一个任务,我想在不退出程序的情况下记录错误(如果遇到错误),但问题是log.Fatal()退出程序并将log.Panic()调用panic()它再次退出程序。

如何在不退出程序的情况下记录错误?

LFN*_*LFN 7

您可以使用不同的日志库(例如logrus)或修改标准日志库,如下所示:

日志包:

// Info writes logs in the color blue with "INFO: " as prefix
var Info = log.New(os.Stdout, "\u001b[34mINFO: \u001B[0m", log.LstdFlags|log.Lshortfile)

// Warning writes logs in the color yellow with "WARNING: " as prefix
var Warning = log.New(os.Stdout, "\u001b[33mWARNING: \u001B[0m", log.LstdFlags|log.Lshortfile)

// Error writes logs in the color red with "ERROR: " as prefix
var Error = log.New(os.Stdout, "\u001b[31mERROR: \u001b[0m", log.LstdFlags|log.Lshortfile)

// Debug writes logs in the color cyan with "DEBUG: " as prefix
var Debug = log.New(os.Stdout, "\u001b[36mDEBUG: \u001B[0m", log.LstdFlags|log.Lshortfile)
Run Code Online (Sandbox Code Playgroud)

与用法:

Error.Println("this is an error")
Run Code Online (Sandbox Code Playgroud)

结果是:

在此输入图像描述