官术网_书友最值得收藏!

  • 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.

主站蜘蛛池模板: 曲靖市| 屏东县| 陇西县| 崇阳县| 江安县| 宜君县| 潍坊市| 玉溪市| 崇阳县| 崇仁县| 正安县| 舟曲县| 咸宁市| 城口县| 栾城县| 遂溪县| 蓬莱市| 阳新县| 弥勒县| 达日县| 白水县| 开封县| 当雄县| 阿城市| 红安县| 湘阴县| 扶沟县| 天柱县| 诸城市| 前郭尔| 缙云县| 怀宁县| 崇明县| 黄平县| 龙岩市| 任丘市| 讷河市| 安丘市| 平和县| 龙井市| 深圳市|