Golang Echo Code detailed log

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

One, the echo comes with the log library

1. Log structure

The log structure of the echo frame is echo. An attribute of the Echo struct

    type Echo struct {        ...        Logger Logger    }

and logger is an interface like this.

 type (//Logger defines the logging interface. Logger interface {Output () Io. Writer setoutput (w io. Writer) Prefix () string Setprefix (P string) level () log. LVL SetLevel (v log. LVL) Print (i ... interface{}) Printf (format string, args ... interface{}) PRINTJ (J Log. JSON) Debug (i ... interface{}) DEBUGF (format string, args ... interface{}) Debugj (J Log. JSON) Info (i ... interface{}) infof (format string, args ... interface{}) Infoj (J Log. JSON) Warn (i ... interface{}) WARNF (format string, args ... interface{}) Warnj (J Log. JSON) Error (i ... interface{}) Errorf (format string, args ... interface{}) Errorj (J Log. JSON) Fatal (i ... interface{}) Fatalj (J Log. JSON) fatalf (format string, args ... interface{}) Panic (I ... interface{}) PANICJ (J Log. JSON) PANICF (format string, args ... interface{})}) 

The general log also implements these methods, so we can replace this with our own log package. And the author is using github.com/labstack/gommon/log this package.

Here, you can customize the log level and the output location is at a glance.

2. The default log

In the Generate Echo. Echo instance, a default log is initialized.

// 初始化一个 Echo 实例func New() (e *Echo) {    e = &Echo{        ...        Logger:   log.New("echo"),    }    ...    e.Logger.SetLevel(log.ERROR) // 默认日志级别    ...    return}// log.New() 方法是这样的func New(prefix string) (l *Logger) {    l = &Logger{        level:    INFO,        prefix:   prefix,        template: l.newTemplate(defaultHeader),        color:    color.New(), // 这个是让不同级别的日志在控制台显示不用颜色的。        bufferPool: sync.Pool{            New: func() interface{} {                return bytes.NewBuffer(make([]byte, 256))            },        },    }    l.initLevels() // 同样是处理颜色    l.SetOutput(output()) // 默认是 os.Stdout    return}

Here the template is the object of the github.com/valyala/fasttemplate package, is a simple template engine, used to control the log output style.

The default style is this

    defaultHeader = `{"time":"${time_rfc3339_nano}","level":"${level}","prefix":"${prefix}",` +        `"file":"${short_file}","line":"${line}"}`

Many of the configurations here are similar to the official log configuration and also show the file name and line number. There are only two types of time formats that are supported by default

time_rfc3339 // "2006-01-02T15:04:05Z07:00"time_rfc3339_nano // "2006-01-02T15:04:05.999999999Z07:00"

If you need a deeper level of customization, you need to modify or replace the log package.

Second, log middleware

This is the way to register the log middleware, which is primarily used to print logs for HTTP requests.

// 使用默认的配置e.Use(middleware.Logger())// 自定义配置// 自定义配置只支持 Format 和 Output 两个属性e.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{  Format: "method=${method}, uri=${uri}, status=${status}\n",  Output os.Stdout,}))

The default configuration is this

    DefaultLoggerConfig = LoggerConfig{        ...        Format: `{"time":"${time_rfc3339_nano}","id":"${id}","remote_ip":"${remote_ip}","host":"${host}",` +            `"method":"${method}","uri":"${uri}","status":${status}, "latency":${latency},` +            `"latency_human":"${latency_human}","bytes_in":${bytes_in},` +            `"bytes_out":${bytes_out}}` + "\n",        Output:  os.Stdout,        colorer: color.New(),    }

The following fields are supported for custom configuration

- time_unix- time_unix_nano- time_rfc3339- time_rfc3339_nano// 时间上多了两个 unix 时间戳类型- id (Request ID)- remote_ip- uri- host- method- path- referer- user_agent- status// 常规的 http 请求内容- latency (In nanoseconds) - latency_human (Human readable)// 这个可以算作处理日志花的时间- bytes_in (Bytes received)- bytes_out (Bytes sent)// request 请求和 response 响应的大小- header:<NAME>- query:<NAME>- form:<NAME>- cookie:<NAME>// 这几个可以拿到具体内容,分别用下面的方法取得// tag 就是上面的字段// c.Request().Header.Get(tag[7:])// c.QueryParam(tag[6:])// c.FormValue(tag[5:])// c.Cookie(tag[7:]

The entire log middleware here https://github.com/labstack/echo/blob/master/middleware/logger.go , does not meet or can be re-implemented as needed.

Third, PostScript

Previously translated Echo's Chinese document http://go-echo.org, found that there are many areas of the document is not clear, the emergence of the side to see the code side to supplement the idea of using the document. It took a long time to finally get started, with the simplest log opening, followed by a succession of updates about other echo modules.

Original address: Laily.net

1231 Reads

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.