Go Log Library Guide

In Golang, the `log` package is a standard library used for recording information or errors during program execution. You can use the functions in the `log` package to print logs as shown below:

package main

import (
	"log"
)

func main() {
	// 打印普通信息
	log.Println("This is a log message")

	// 打印错误信息
	log.Fatalln("This is an error message")

	// 打印调试信息
	log.Printf("This is a debug message: %d", 10)

	// 设置日志前缀
	log.SetPrefix("PREFIX: ")

	// 打印日志
	log.Println("This is a log message with a prefix")
}

In the above code, we first import the log package. We can then use log.Println function to print regular information, log.Fatalln function to print error messages and terminate program execution, and log.Printf function to print formatted log information. We can also use log.SetPrefix function to set the prefix for the logs.

When you run the above code, you will see a similar output in the terminal.

This is a log message
This is an error message
This is a debug message: 10
PREFIX: This is a log message with a prefix

By default, the log package outputs log messages to standard error (stderr). You can also use the log.SetOutput function to redirect log messages to other places, such as a file.

bannerAds