package main
import (
"log"
"errors"
"fmt"
)
func main() {
/* local variable definition */
...
/* function for division which return an error if divide by 0 */
ret,err = div(a, b)
if err != nil {
log.Fatal(err)
}
fmt.Println(ret)
}
YRMacBook-Pro:go-log yanrui$ more test.log
2017/05/24 21:46:25 ==========works==============
二、格式化
推荐日志工具库:logrus
$ go get github.com/Sirupsen/logrus
1、JSON format
package main
import (
log "github.com/Sirupsen/logrus"
"github.com/logmatic/logmatic-go"
)
func main() {
// use JSONFormatter
log.SetFormatter(&logmatic.JSONFormatter{})
// log an event as usual with logrus
log.WithFields(log.Fields{"string": "foo", "int": 1, "float": 1.1 }).Info("My first ssl event from golang")
}
日志输出样式:
{
"@marker":["sourcecode","golang"],
"date":"2017-05-24T15:27:40+08:00",
"float":1.1,"int":1,"level":"info",
"message":"My first ssl event from golang",
"string":"foo"
}
三、附加上下文
通过logrus库可以加入一些上下文信息,例如:主机名称,程序名称或者会话参数等。
contextLogger := log.WithFields(log.Fields{
"common": "XXX common content XXX",
"other": "YYY special context YYY",
})
contextLogger.Info("AAAAAAAAAAAA")
contextLogger.Info("BBBBBBBBBBBB")
日志输出样式:
YRMacBook-Pro:go-log yanrui$ go run LogMatic.go
{"@marker":["sourcecode","golang"],"common":"XXX common content XXX","date":"2017-05-24T17:00:08+08:00","level":"info","message":"AAAAAAAAAAAA","other":"YYY special context YYY"}
{"@marker":["sourcecode","golang"],"common":"XXX common content XXX","date":"2017-05-24T17:00:08+08:00","level":"info","message":"BBBBBBBBBBBB","other":"YYY special context YYY"}
YRMacBook-Pro:go-log yanrui$
func main() {
// instantiate a new Logger with your Logmatic APIKey
// 国内访问比较慢
log.AddHook(logmatic.NewLogmaticHook("p53uTkOhSEqI3-116DynkQ"))
// ..........
}