组件使用
默认以log4go使用介绍,logrus及zap请参考各自使用文档。
安装
go get -u github.com/tal-tech/loggerX
初始化
- xml
logger.InitLogger("conf/log.xml") //xml配置地址defer logger.Close()
- ini & yaml
logMap := confutil.GetConfStringMap("log") //通过配置文件转为map[string]stringconfig := logger.NewLogConfig()config.SetConfigMap(logMap)logger.InitLogWithConfig(config)defer logger.Close()
- 自定义初始化
config := logger.NewLogConfig()config.Level="WARNING" //更新其他配置logger.InitLogWithConfig(config)defer logger.Close()
日志方法
- 支持不同级别打印日志的方法:
logger.I(tag string, args interface{}, v ...interface{})logger.T(tag string, args interface{}, v ...interface{})logger.D(tag string, args interface{}, v ...interface{})logger.W(tag string, args interface{}, v ...interface{})logger.E(tag string, args interface{}, v ...interface{})logger.C(tag string, args interface{}, v ...interface{})logger.F(tag string, args interface{}, v ...interface{}) //级别同CRITICAL,但触发paniclogger.Ix(ctx context.Context, tag string, args interface{}, v ...interface{})logger.Tx(ctx context.Context, tag string, args interface{}, v ...interface{})logger.Dx(ctx context.Context, tag string, args interface{}, v ...interface{})logger.Wx(ctx context.Context, tag string, args interface{}, v ...interface{})logger.Ex(ctx context.Context, tag string, args interface{}, v ...interface{})
- 使用用例:
logger.I("TESTFUNCTAG","data save to mysql, uid:%d ,name:%s",100,"学生1")logger.Ix(ctx,"TESTFUNCTAG","data save to mysql, uid:%d ,name:%s",100,"学生1")logger.E("TESTFUNCTAG","get redis error:%v, uid:%d ,name:%s",err,100,"学生1")logger.Ex(ctx,"TESTFUNCTAG","get redis error:%v, uid:%d ,name:%s",err,100,"学生1")
链路追踪
//每次调用携带全局变量,支持log特殊需求,如链路追踪等//默认支持两个特性: 一次请求开始时写入ctx = context.WithValue(ctx, "logid", id) //id类型string,通过id区分一次完整请求的所有日志ctx = context.WithValue(ctx, "start", time.Now()) //每条日志会计算出相对接口开始时间耗时
//example目录日志支持接入网校链路追踪系统,使用参考example目录,普通链路和rpc链路
Error
//方法调用logger.NewError("error",SYSTEM_DEFAULT)//方法定义func NewError(err interface{}, ext ...XesError)//err传参支持string,error类型(会自动解析rpc server错误),表示错误根本原因//ext XesError,Xes错误码,对外输出错误信息,不传默认系统异常type XesError struct {Code intMsg string}
注意事项:
- logger库是并发不安全的,所以全局只能有一个实例。在写单元测时,有可能会多次初始化,此时一定要在包测试完之后进行logger.Close()操作。否则可能会出现如下错误
FileLogTraceWriter("/xxx/xxx.log"): Rotate: rename /xxx/xxx.log.1: no such file or dircotry\n
- logger库初始化的时候会先进行一次关闭操作,如果在init方法中使用的logger日志打印,数据写入channel,main函数初始化时进行关闭channel操作时会造成panic。
