Junior — Middle
Can you explain the principles and methods of logging in the Go language?
sobes.tech AI
Answer from AI
In the Go language, the log package from the standard library is commonly used for logging. The main principles and methods:
- Ease of use: the
logpackage provides functions likePrint,Printf,Println,Fatal,Panicfor outputting messages. - Output customization: you can set the output format, such as adding timestamps, line numbers, etc.
- Creating custom loggers with
log.New()to write logs to different files or streams.
Example of simple logging:
import (
"log"
"os"
)
func main() {
file, err := os.OpenFile("app.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err != nil {
log.Fatal(err)
}
logger := log.New(file, "INFO: ", log.Ldate|log.Ltime|log.Lshortfile)
logger.Println("Application started")
}
For more complex logging, third-party libraries like zap or logrus are often used, which support log levels, formatting, and asynchronous writing.