Logs allow you to send info or errors during your program for debugging purposes. In practice, logging is often used in conjunction with something like Elastic Search to monitor and track down issues. In this article, we will learn how to use logs in Go.
Go provides us with a log
package. We can use this by importing the package.
import "log"
The basic usage is the Println
method which is similar to that in the fmt
package.
log.Println("info log")
The output
Service: 2021/11/29 08:18:42.304512 info log
We can also use the log.Fatalln
which will print then call the os.Exist(1)
.
log.Fatalln("Fatal log")
The output
Service: 2021/11/29 08:18:42.305032 Fatal log
exit status 1
And on more example, we can use log.Panicln
which will call panic after printing.
log.Panicln("Panic log")
The output
Service: 2021/11/29 08:19:25.671978 Panic log
panic: Panic log
goroutine 1 [running]:
log.Panicln({0xc000119f60, 0x49d1b4, 0x406e65})
C:/Program Files/Go/src/log/log.go:368 +0x65
main.main()
C:/Users/krh12/Documents/r-data-vis/GoLang/logs/main.go:11 +0xa5
exit status 2
The log package also has some configuration. For example, you often want to prefix your logs, usually when working with multiple services or layers. We can do this with the following:
log.SetPrefix("Service: ")
This will add the prefix when printing each log.
We can also SetFlags
to add other configuration. For example, we can modify the date display like so.
log.SetFlags(log.Ldate | log.Lmicroseconds)
You can find more flags here: https://pkg.go.dev/log#pkg-constants
You can run the full example code by copying the code below to a file called main.go
and run go run main.go
package main
import "log"
func main() {
log.SetPrefix("Service: ")
log.SetFlags(log.Ldate | log.Lmicroseconds)
log.Println("info log")
log.Fatalln("Fatal log")
log.Panicln("Panic log")
}