AVarf
AVarf

Reputation: 5149

How to log error without exit the program in golang?

I am running a task every 5 minutes and I want to log the error (if it faced the error) without exiting the program but the problem is log.Fatal() is exiting the program and log.Panic() will call panic() which again exits the program.

How can I log the error without exiting the program?

Upvotes: 2

Views: 10393

Answers (1)

LFN
LFN

Reputation: 336

You can use a different logging library like logrus or modify your standard log library like this:

log package:

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

with usage:

Error.Println("this is an error")

and the result would be:

enter image description here

Upvotes: 9

Related Questions