Go:glog
目录:
glog基本用法
package main
import (
"flag"
"github.com/golang/glog"
)
func main() {
flag.Parse()
defer glog.Flush()
glog.Info("This is a Info log")
glog.Warning("This is a Warning log")
glog.Error("This is a Error log")
glog.V(1).Infoln("level 1")
glog.V(2).Infoln("level 2")
}
这里log产生后会暂存在内存的buffer,只有调用glog.Flush()才会写入文件,glog的package的init函数启动了一个flushDaemon的goroutine来定时Flush,时间为30s,在程序退出之前需要defer来方式这种问题的发生
直接通过指定日志路径的方式运行
go run main.go -log_dir="./"
会生成不同级别的日志文件
lrwxr-xr-x 1 mrwhy staff 52 4 10 23:42 main.ERROR -> main.whydomain.mrwhy.log.ERROR.20210410-234226.86055
lrwxr-xr-x 1 mrwhy staff 51 4 10 23:42 main.INFO -> main.whydomain.mrwhy.log.INFO.20210410-234226.86055
lrwxr-xr-x 1 mrwhy staff 54 4 10 23:42 main.WARNING -> main.whydomain.mrwhy.log.WARNING.20210410-234226.86055
-rw-r--r-- 1 mrwhy staff 271 4 10 23:41 main.go
-rw-r--r-- 1 mrwhy staff 250 4 10 23:42 main.whydomain.mrwhy.log.ERROR.20210410-234226.86055
-rw-r--r-- 1 mrwhy staff 375 4 10 23:42 main.whydomain.mrwhy.log.INFO.20210410-234226.86055
-rw-r--r-- 1 mrwhy staff 314 4 10 23:42 main.whydomain.mrwhy.log.WARNING.20210410-234226.86055
Info日志内容
Log file created at: 2021/04/10 23:42:26
Running on machine: whydomain
Binary: Built with gc go1.13.15 for darwin/amd64
Log line format: [IWEF]mmdd hh:mm:ss.uuuuuu threadid file:line] msg
I0410 23:42:26.076030 86055 main.go:11] This is a Info log
W0410 23:42:26.076561 86055 main.go:12] This is a Warning log
E0410 23:42:26.076832 86055 main.go:13] This is a Error log
可以看到是没有level1和level2的输出的,需要在启动的时候通过-v来指定,小于这个级别的才会进行输出,默认为0
相当于
if glog.V(1) {
Info()
}
执行
go run main.go -log_dir="./" -v=1
就看到只有level1的日志输出了
启动参数
-alsologtostderr
log to standard error as well as files
-log_backtrace_at value
when logging hits line file:N, emit a stack trace
-log_dir string
If non-empty, write log files in this directory
-logtostderr
log to standard error instead of files
-stderrthreshold value
logs at or above this threshold go to stderr
-v value
log level for V logs
-vmodule value
comma-separated list of pattern=N settings for file-filtered logging
常用的还有
- alsologtostderr:日志写入文件的同时,输出到stderr
- vmodule:可以为不同文件的日志打印配置不同的-v值
log_backtrace_at
:运行到指定位置打印堆栈信息
alsologtostderr
同级添加go文件
package main
import "github.com/golang/glog"
func bar() {
glog.V(1).Info("level 1 in bar")
glog.V(2).Info("level 2 in bar")
}
main.go引用bar方法
package main
import (
"flag"
"github.com/golang/glog"
)
func main() {
flag.Parse()
defer glog.Flush()
glog.Info("This is a Info log")
glog.Warning("This is a Warning log")
glog.Error("This is a Error log")
glog.V(1).Infoln("level 1")
glog.V(2).Infoln("level 2")
bar()
}
执行
go run ./ -log_dir="./" -v 1 -vmodule=bar=2
只有vmoudule大于v才生效
I0411 00:09:13.347980 88302 main.go:16] level 1
I0411 00:09:13.347995 88302 bar.go:6] level 1 in bar
I0411 00:09:13.348000 88302 bar.go:7] level 2 in bar