- Go Systems Programming
- Mihalis Tsoukalos
- 343字
- 2021-07-02 18:08:01
About error logging
Go offers functions that can help you log your error messages in various ways. You already saw log.Fatal() in funErr.go, which is a somewhat cruel way to deal with simple errors. Put simply, you should have a very good reason to use log.Fatal() in your code. Generally speaking, log.Fatal() should be used instead of the os.Exit() function because it allows you to print an error message and exit your program using just one function call.
Go offers additional error logging functions in the log standard package that behave more gently depending on the situation, which includes log.Printf(), log.Print(), log.Println(), log.Fatalf(), log.Fatalln(), log.Panic(), log.Panicln(), and log.Panicf(). Please note that logging functions can be handy for debugging purposes so do not underestimate their power.
The logging.go program illustrates two of the mentioned logging functions using the following Go code:
package main import ( "log" ) func main() { x := 1 log.Printf("log.Print() function: %d", x) x = x + 1 log.Printf("log.Print() function: %d", x) x = x + 1 log.Panicf("log.Panicf() function: %d", x) x = x + 1 log.Printf("log.Print() function: %d", x) }
As you can see, logging.go does not need the fmt package because it has its own functions for printing the output. Executing logging.go will produce the following output:
$ go run logging.go 2017/03/10 16:51:56 log.Print() function: 1 2017/03/10 16:51:56 log.Print() function: 2 2017/03/10 16:51:56 log.Panicf() function: 3 panic: log.Panicf() function: 3 goroutine 1 [running]: log.Panicf(0x10b78d0, 0x19, 0xc42003df48, 0x1, 0x1) /usr/local/Cellar/go/1.8/libexec/src/log/log.go:329 +0xda main.main() /Users/mtsouk/ch3/code/logging.go:14 +0x1af exit status 2
Although the log.Printf() function works in the same way as fmt.Printf(), it automatically prints the date and time the log message was printed, just like the log.Fatal() function did in funErr.go. Additionally, the log.Panicf() function works in a similar way to log.Fatal()--they both terminate the current program. However, log.Panicf() prints some additional information, useful for debugging purposes.
Go also offers the log/syslog package that is a simple interface to the system log service running on your Unix machine. Chapter 7, Working with System Files, will talk more about the log/syslog package.
- 多媒體CAI課件設計與制作導論(第二版)
- FuelPHP Application Development Blueprints
- Java系統分析與架構設計
- Rust編程:入門、實戰與進階
- Java面向對象軟件開發
- Designing Hyper-V Solutions
- MATLAB實用教程
- 用Flutter極速構建原生應用
- C程序設計案例教程
- H5頁面設計:Mugeda版(微課版)
- Kotlin編程實戰:創建優雅、富于表現力和高性能的JVM與Android應用程序
- Create React App 2 Quick Start Guide
- Learning Hadoop 2
- Azure Serverless Computing Cookbook
- C++ Application Development with Code:Blocks