許多軟件系統運行中需要日志文件。Go語言程序中,輸出日志需要使用包"log",編寫程序十分簡單。
像Java語言程序,輸出日志時,往往需要使用開源的軟件包來實現,編寫程序稍微復雜一些。
Go語言的包"log"中,提供了三類借口,分別是Print(一般的log,進程退出代碼為0即正常)、Panic(意外的log,進程退出代碼為2)和Fatal(致命的log,進程退出代碼為1)。
這里分別給出三個有個log的程序及其運行結果。
Go語言程序之一(Print):
// log project main.go
package mainimport ("log"
)func main() {no := []int{1, 2}log.Print("Print no ", no, "\n")log.Println("Println no", no)log.Printf("Printf no with item [%d,%d]\n", no[0], no[1])
}
程序運行結果(Print):
2017/08/11 12:43:38 Print no [1 2]
2017/08/11 12:43:38 Println no [1 2]
2017/08/11 12:43:38 Printf no with item [1,2]
成功: 進程退出代碼 0.
Go語言程序之二(Panic):
// log3 project main.go
package mainimport ("log"
)func main() {no := []int{1, 2}log.Panicln("Println no", no)
}
程序運行結果(Panic):
2017/08/11 12:40:07 Println no [1 2]
panic: Println no [1 2]goroutine 1 [running]:
log.Panicln(0xc42003ff50, 0x2, 0x2)/usr/local/go/src/log/log.go:344 +0xc0
main.main()/home/lin/go/src/log3/main.go:11 +0xe3
錯誤: 進程退出代碼 2.
Go語言程序之三(Fatal):
// log2 project main.go
package mainimport ("log"
)func main() {no := []int{1, 2}log.Fatalln("Println no", no)
}
程序運行結果(Fatal):
2017/08/11 12:37:38 Println no [1 2]
錯誤: 進程退出代碼 1.
程序說明:(略)