Go語言中日誌處理,log包的使用
阿新 • • 發佈:2018-05-06
Go語言日誌 Go語言log golang日誌處理 Golang提供了原生日誌庫“log”,使用簡單方便,本文以代碼為例進行說明介紹。
package main import ( "os" "log" "fmt" ) func main() { // 打開日誌文件 // 第二個參數為打開文件的模式,可選如下: /* O_RDONLY // 只讀模式打開文件 O_WRONLY // 只寫模式打開文件 O_RDWR // 讀寫模式打開文件 O_APPEND // 寫操作時將數據附加到文件尾部 O_CREATE // 如果不存在將創建一個新文件 O_EXCL // 和O_CREATE配合使用,文件必須不存在 O_SYNC // 打開文件用於同步I/O O_TRUNC // 如果可能,打開時清空文件 */ // 第三個參數為文件權限,請參考linux文件權限,664在這裏為八進制,代表:rw-rw-r-- logFile, err := os.OpenFile("e:/go.log", os.O_WRONLY | os.O_CREATE | os.O_APPEND, 0644) if err != nil { log.Fatal(err) } // 第一個參數為輸出io,可以是文件也可以是實現了該接口的對象,此處為日誌文件;第二個參數為自定義前綴;第三個參數為輸出日誌的格式選項,可多選組合 // 第三個參數可選如下: /* Ldate = 1 // 日期:2009/01/23 Ltime = 2 // 時間:01:23:23 Lmicroseconds = 4 // 微秒分辨率:01:23:23.123123(用於增強Ltime位) Llongfile = 8 // 文件全路徑名+行號: /a/b/c/d.go:23 Lshortfile = 16 // 文件無路徑名+行號:d.go:23(會覆蓋掉Llongfile) LstdFlags = Ldate | Ltime // 標準logger的初始值 */ debugLog := log.New(logFile, "[debug]", log.Ldate|log.Ltime|log.Llongfile) // 日誌輸出 debugLog.Print("日誌測試Print輸出,處理同fmt.Print") debugLog.Println("日誌測試Println輸出,處理同fmt.Println") debugLog.Printf("日誌測試%s輸出,處理同fmt.Printf", "Printf") // 日誌輸出,同時直接終止程序,後續的操作都不會執行 debugLog.Fatal("日誌測試Fatal輸出,處理等價於:debugLog.Print()後,再執行os.Exit(1)") debugLog.Fatalln("日誌測試Fatalln輸出,處理等價於:debugLog.Println()後,再執行os.Exit(1)") debugLog.Fatalf("日誌測試%s輸出,處理等價於:debugLog.Print()後,再執行os.Exit(1)", "Fatalf") // 日誌輸出,同時拋出異常,可用recover捕捉 defer func() { if r := recover(); r != nil { fmt.Println("===========", r) } }() debugLog.Panic("日誌測試Panic輸出,處理等價於:debugLog.Print()後,再執行Panic()") debugLog.Panicln("日誌測試Panicln輸出,處理等價於:debugLog.Println()後,再執行Panic()") debugLog.Panicf("日誌測試%s輸出,處理等價於:debugLog.Printf()後,再執行Panic()", "Panicf") fmt.Println("前綴為:", debugLog.Prefix()) // 前綴為: [debug] fmt.Println("輸出選項為:", debugLog.Flags()) // 輸出選項為: 11 // 設置前綴 debugLog.SetPrefix("[info]") // 設置輸出選項 debugLog.SetFlags(log.LstdFlags) fmt.Println("前綴為:", debugLog.Prefix()) // 前綴為: [info] fmt.Println("輸出選項為:", debugLog.Flags()) // 輸出選項為: 3 }
說明:以上代碼執行時要分段註釋後執行,否則執行到:
debugLog.Fatal("日誌測試Fatal輸出,處理等價於:debugLog.Print()後,再執行os.Exit(1)")
便會終止
Go語言中日誌處理,log包的使用