packagemainimport ("log""errors""fmt")funcmain() {/* 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)}
packagemainimport ( log "github.com/Sirupsen/logrus""github.com/logmatic/logmatic-go")funcmain() {// 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-logyanrui$ gorunLogMatic.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-logyanrui$
packagemainimport ( log "github.com/sirupsen/logrus""gopkg.in/gemnasium/logrus-airbrake-hook.v2"// the package is named "aibrake" logrus_syslog "github.com/sirupsen/logrus/hooks/syslog""log/syslog")funcmain(){ hook, err := logrus_syslog.NewSyslogHook("udp", "59.37.0.1:514", syslog.LOG_INFO, "")if err !=nil { log.Error("Unable to connect to local syslog daemon") } else { log.AddHook(hook) }}
验证是否发送Syslog:
$ sudo tcpdump | grep 59.37.0.1tcpdump: data link type PKTAPtcpdump: verbose output suppressed, use -v or -vv for full protocol decodelistening on pktap, link-type PKTAP (Apple DLT_PKTAP), capture size 262144 bytes18:51:05.663612 IP 192.168.199.15.58819 > 59.37.0.1.syslog: SYSLOG kernel.info, length: 31418:51:05.663657 IP 192.168.199.15.58819 > 59.37.0.1.syslog: SYSLOG kernel.info, length: 314
funcmain() {// instantiate a new Logger with your Logmatic APIKey// 国内访问比较慢 log.AddHook(logmatic.NewLogmaticHook("p53uTkOhSEqI3-116DynkQ"))// ..........}