package main import ( "log" ) func main() { log.Print("Hello, world!") }
2022/01/01 00:00:00 Hello, world!
package main import ( "log" "os" ) func main() { file, err := os.Create("logfile.txt") if err != nil { log.Fatal("Failed to create log file:", err) } defer file.Close() log.SetOutput(file) log.SetFlags(log.LstdFlags | log.Lshortfile) err = doSomething() if err != nil { log.Printf("Error: %s", err) } } func doSomething() error { return fmt.Errorf("Something went wrong") }
2022/01/01 00:00:00 main.doSomething:/path/to/file/main.go:20: Error: Something went wrongIn this example, we create a file to write the logs to and set it as the output for the Logger using `log.SetOutput(file)`. We also set some flags to include the date and time of each log message and a short file name and line number where the log message occurred. Finally, we log an error message with a stack trace using `log.Printf`. Overall, the log package is a powerful and easy-to-use tool for logging messages in Go programs.