简单的Go日志框架

网友投稿 1076 2022-10-19

简单的Go日志框架

简单的Go日志框架

通用日志框架

本log只是一个框架,并不处理log实际的输出 具体的输出实现由dirver完成(driver是实现log.FormatWriter的对象)

获取

go get -u github.com/afocus/log

基本使用

import ( "github.com/afocus/log" "github.com/afocus/log/driver/console")func main(){ // 创建一个向控制台输出的log对象 g := log.New(log.DEBUG,console.New()) g.Info("hello,world") g.Error("error message")}

输出到多个输出源

import ( "github.com/afocus/log" "github.com/afocus/log/driver/console" "github.com/afocus/log/driver/file")func main(){ // 同时输出到文件和控制台 g := log.New(log.DEBUG,console.New(), file.New(&file.Option{...})) g.Info("hello,world") g.Error("error message")}

高级(带有关联关系的日志)

Ctx(id string) 用于创建一个关联日志组

包含的方法 Tag 用于设置标签 支持链式调用

import ( "github.com/afocus/log" "github.com/afocus/log/driver/console")func main(){ // 创建一个向控制台输出的log对象 g := log.New(log.DEBUG,console.New()) // 创建一个日志组并关联一个id gx := g.Ctx("000000001").Tag("login") gx.Info("user:xxx,pwd:xxx") gx.Error("pwd is error") // 添加标签 gx.Tag("newtag").Warn("dang") // 添加附加字段信息 gx.Fields(map[string]interface{}{"name":"afocus"}) // 用完需要释放 gx.Free()}

输出级别

分为6级,只有当日志级别大于等于设置的级别才会输出

定义

Level说明
DEBUG指明细致的事件信息,对调试应用最有用
INFO指明描述信息,从粗粒度上描述了应用运行过程
WARN指明潜在的有害状况
ERROR指明错误事件,但应用可能还能继续运行
FATAL指明非常严重的错误事件,可能会导致应用终止执行 (自带调用堆栈信息)
OFF最高级别,用于关闭日志

输出方法

Debug(v ...interface{})Info(v ...interface{})Warn(v ...interface{})Error(v ...interface{})Fatal(v ...interface{})Debugf(s string, v ...interface{})Infof(s string, v ...interface{})Warnf(s string, v ...interface{})Errorf(s string, v ...interface{})Fatalf(s string, v ...interface{})

Driver

格式化输出接口

// Formater 格式化日志事件到字符串type Formater interface { Format(*Event) []byte}// FormatWriter 格式化输入// 用于定制日志输出内容的样式type FormatWriter interface { io.Writer Formater}

实现自己的日志driver 将日志格式输出为json并通过tcp持续发送

type MyDriver struct{ c net.Conn}func (*MyDriver) Format(ev *log.Event)[]byte{ b,_:=json.Marshal(ev) return b}func (d *MyDriver) Write(d []byte) int,error{ return d.c.Write(d)}func main(){ conn,err:=net.Dial("tcp","....") myd:=&MyDriver{c:conn} // 启用 g:=log.New(log.DEBUG, myd) ...}

目前已实现的driver

控制台 带颜色的控制台输出(windows暂时无色)文件 支持文件分割网络 目前仅实现了通过http发送日志的功能并且高度自定义

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:App模块化及工程扩展
下一篇:Android中获取网络图片的方法(如果手机缓存里面有就从缓存获取)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~