在go语言中,自身已经集成了一定log模块,开发者可以使用go语言自身的log包(import “log”)。也有不少对自身log的开源封装。对于一些简单的开发,自身的log模块就已经足够应付。但是对一些大型,复杂的开发,log需要分门别类的输出,或者通过网络进行输出,自身log模块将难以应对。
当前也有一些比较重量级的log模块,比如logrus,可以实现比较复杂的功能。这里介绍一个轻量级的log模块——log4go. 源于Google的一项log工程,官方已经停止维护更新,这里对他进行了重构,使用起来也特别简单,就像自身的log模块一样。
2. 特点 日志输出到终端 日志输出到文件,支持按大小和时间切片 日志输出到网络 日志异步输出 支持Json文件配置 日志分类不同类别的日志,输出到不同的printer中. 兼容老的日志方式 使用方式
首先,下载源码.
go get github.com/jeanphorn/log4go
导入进工程:
import log "github.com/jeanphorn/log4go"
源代码也可以直接从github仓库下载使用。
使用示例这里使用Json配置文件,配置文件是可选的,如果不配置,默认输出到终端。
{ "console": { "enable": true,// wether output the log "level": "FINE" // log level: FINE,DEBUG,TRACE,INFO,WARNING,ERROR,CRITICAL },"files": [{ "enable": true,"level": "DEBUG","filename":"./test.log","category": "Test",// different category log to different files "pattern": "[%D %T] [%C] [%L] (%s) %M" // log output formmat },{ "enable": false,"filename":"rotate_test.log","category": "TestRotate","pattern": "[%D %T] [%C] [%L] (%s) %M","rotate": true,// wether rotate the log "maxsize": "500M","maxlines": "10K","daily": true }],"sockets": [{ "enable": false,"category": "TestSocket","addr": "127.0.0.1:12124","protocol":"udp" }] }
Code example:
package mainimport ( log "github.com/jeanphorn/log4go")func main() { // load config file,it's optional // or log.LoadConfiguration("./example.Json","Json") // config file Could be Json or xml log.LoadConfiguration("./example.Json") log.LOGGER("Test").Info("category Test info test ...") log.LOGGER("Test").Info("category Test info test message: %s","new test msg") log.LOGGER("Test").DeBUG("category Test deBUG test ...") // Other category not exist,test log.LOGGER("Other").DeBUG("category Other deBUG test ...") // socket log test log.LOGGER("TestSocket").DeBUG("category TestSocket deBUG test ...") // original log4go test log.Info("nomal info test ...") log.DeBUG("nomal deBUG test ...") log.Close()}
输出样式:
4. 感谢[2017/11/15 14:35:11 CST] [Test] [INFO] (main.main:15) category Test info test …
[2017/11/15 14:35:11 CST] [Test] [INFO] (main.main:16) category Test info test message: new test msg
[2017/11/15 14:35:11 CST] [Test] [DEBG] (main.main:17) category Test deBUG test …
[2017/11/15 14:35:11 CST] [DEFAulT] [INFO] (main.main:26) nomal info test …
[2017/11/15 14:35:11 CST] [DEFAulT] [DEBG] (main.main:27) nomal deBUG test …
Thanks alecthomas for provIDing the original resource.
总结以上是内存溢出为你收集整理的golang log模块之log4go使用介绍全部内容,希望文章能够帮你解决golang log模块之log4go使用介绍所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)