1. 程式人生 > >Golang學習筆記--log包

Golang學習筆記--log包

一、快速使用
Golang的log包短小精悍,可以非常輕鬆的實現日誌列印轉存功能。不用多說,log支援併發操作(即協程安全-相對於JAVA中的執行緒安全而言),其結構定義如下:


type Loggerstruct{
	mu     sync.Mutex// ensures atomic writes; protects the following fields
	prefix string// prefix to write at beginning of each line //  日誌行字首
	flag   int// properties // 日誌列印格式標誌,用於指定每行日誌的列印格式out    io
.Writer// destination for output // 用於指定日誌輸出位置,理論上可以是任務地方,只要實現了io.Writer介面就行 buf []byte// for accumulating text to write // 日誌內容}

log包定義了一些日誌格式標誌:

// These flags define which text to prefix to each log entry generated by the Logger.const(// Bits or'ed together to control what's printed. There is no control over the
// order they appear (the order listed here) or the format they present (as// described in the comments). A colon appears after these items:// 2009/01/23 01:23:23.123123 /a/b/c/d.go:23: messageLdate=1<< iota // the date: 2009/01/23Ltime// the time: 01:23:23Lmicroseconds// microsecond resolution: 01:23:23.123123. assumes Ltime.
Llongfile// full file name and line number: /a/b/c/d.go:23Lshortfile// final file name element and line number: d.go:23. overrides LlongfileLstdFlags=Ldate|Ltime// initial values for the standard logger)

上述這些標誌可以在建立Logger物件時指定(通過下面的New函式建立),也可以通過Logger.setFlat()方法動態指定。

Logger物件通過函式New建立

// New creates a new Logger.   The out variable sets the// destination to which log data will be written.// The prefix appears at the beginning of each generated log line.// The flag argument defines the logging properties.
func New(out io.Writer, prefix string, flag int)*Logger{return&Logger{out:out, prefix: prefix, flag: flag}}

log包已預設提供了一個日誌物件,並封裝了包級別的常用函式,該物件將日誌資訊輸出到標準輸出裝置中(開箱即用)。

var std =New(os.Stderr,"",LstdFlags)// 日誌中只使用的flag為LstdFlags,即只輸出日期

如果只是想輸出到終端而不儲存到檔案等其它地方時,可以直接通過log.Xxxx()方式直接呼叫,因為這些包級別的函式只是對std物件相關方法的簡單封裝,如println函式定義如下:

// Println calls Output to print to the standard logger.// Arguments are handled in the manner of fmt.Println.
func Println(v ...interface{}){
	std.Output(2, fmt.Sprintln(v...))}

二、Logger物件方法使用說明
Logger物件提供瞭如下幾個方法:

func (l *Logger)Output(calldepth int, s string) error ;// 真正負責日誌列印的方法,其它級別的列印方法都將會呼叫它// Println calls l.Output to print to the logger.// Arguments are handled in the manner of fmt.Println.
func (l *Logger)Println(v ...interface{}){// 一般資訊列印方法,相當於JAVA中log的info級別
        l.Output(2, fmt.Sprintln(v...))}// Panicln is equivalent to l.Println() followed by a call to panic().  
func (l *Logger)Panicln(v ...interface{}){// 業務異常時使用的方法,該方法會丟擲異常,呼叫方可以用recover捕獲,相當於JAVA的ERROR級別(JAVA不會自動拋異常)
	s := fmt.Sprintln(v...)
	l.Output(2, s)
	panic(s)// 通過panic丟擲異常,只有上層業務沒捕獲異常時,程式才會異常中止並退出,}// Fatalln is equivalent to l.Println() followed by a call to os.Exit(1).
func (l *Logger)Fatalln(v ...interface{}){ 
	l.Output(2, fmt.Sprintln(v...))
	os.Exit(1)// 呼叫該方法會中止應用程式並直接退出}

三、使用示例

package test

import("fmt""log""os""testing")

func TestLog(t *testing.T){
	fmt.Println("begin TestLog ...")
	file, err := os.Create("test.log")if err !=nil{
		log.Fatalln("fail to create test.log file!")}
	logger := log.New(file,"", log.LstdFlags|log.Llongfile)
	log.Println("1.Println log with log.LstdFlags ...")
	logger.Println("1.Println log with log.LstdFlags ...")

	logger.SetFlags(log.LstdFlags)

	log.Println("2.Println log without log.LstdFlags ...")
	logger.Println("2.Println log without log.LstdFlags ...")//log.Panicln("3.std Panicln log without log.LstdFlags ...")//fmt.Println("3 Will this statement be execute ?")//logger.Panicln("3.Panicln log without log.LstdFlags ...")

	log.Println("4.Println log without log.LstdFlags ...")
	logger.Println("4.Println log without log.LstdFlags ...")

	log.Fatal("5.std Fatal log without log.LstdFlags ...")
	fmt.Println("5 Will this statement be execute ?")
	logger.Fatal("5.Fatal log without log.LstdFlags ...")}