- 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.
- 基于粒計算模型的圖像處理
- Web前端開發技術:HTML、CSS、JavaScript(第3版)
- Python數據分析入門與實戰
- Web Scraping with Python
- PaaS程序設計
- 深入淺出Spring Boot 2.x
- Hands-On Microservices with Kotlin
- Python算法詳解
- Python Data Structures and Algorithms
- Flowable流程引擎實戰
- Geospatial Development By Example with Python
- Python 3 Object:oriented Programming(Second Edition)
- Hacking Android
- 網頁設計與制作
- JSP應用與開發技術(第3版)