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

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

主站蜘蛛池模板: 湟中县| 双桥区| 拜泉县| 廊坊市| 金坛市| 弋阳县| 开平市| 聊城市| 民县| 长岛县| 平和县| 黑山县| 平乡县| 环江| 资源县| 临沂市| 昌都县| 武夷山市| 霍山县| 志丹县| 鸡东县| 左贡县| 新昌县| 南木林县| 七台河市| 大关县| 锦州市| 镇平县| 广安市| 饶河县| 宜良县| 绿春县| 汉沽区| 衡东县| 喜德县| 云南省| 镇坪县| 乌什县| 呼图壁县| 溆浦县| 东兴市|