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

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.

主站蜘蛛池模板: 金山区| 临漳县| 胶州市| 长丰县| 黄梅县| 杭锦后旗| 连州市| 道真| 仁怀市| 自治县| 汶川县| 五原县| 苍梧县| 沁水县| 迁安市| 霍州市| 天津市| 汕尾市| 苏尼特右旗| 万安县| 神木县| 南雄市| 利川市| 余干县| 长宁区| 察哈| 昌乐县| 萨嘎县| 平乐县| 台东市| 连云港市| 娱乐| 东明县| 班戈县| 阿拉尔市| 金寨县| 周宁县| 黔东| 旬邑县| 太谷县| 肥东县|