相关定义
可以看到第二个参数为日志处理的日志信息,并且为指针类型,意味着在Handler
中可以修改该参数的任意属性信息,并且修改后的内容将会传递给下一个Handler
。
// HandlerInput is the input parameter struct for logging Handler.
type HandlerInput struct {
Logger *Logger // Logger.
Ctx context.Context // Context.
Buffer *bytes.Buffer // Buffer for logging content outputs.
Time time.Time // Logging time, which is the time that logging triggers.
TimeFormat string // Formatted time string, like "2016-01-09 12:00:00".
Color int // Using color, like COLOR_RED, COLOR_BLUE, etc.
Level int // Using level, like LEVEL_INFO, LEVEL_ERRO, etc.
LevelFormat string // Formatted level string, like "DEBU", "ERRO", etc.
CallerFunc string // The source function name that calls logging.
CallerPath string // The source file path and its line number that calls logging.
CtxStr string // The retrieved context value string from context.
Prefix string // Custom prefix string for logging content.
Content string // Content is the main logging content that passed by you.
IsAsync bool // IsAsync marks it is in asynchronous logging.
handlerIndex int // Middleware handling index for internal usage.
}
使用示例
我们来看两个示例便于更快速了解Handler
的使用。
package main
import (
"context"
"encoding/json"
"os"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/text/gstr"
)
// JsonOutputsForLogger is for JSON marshaling in sequence.
type JsonOutputsForLogger struct {
Time string `json:"time"`
Level string `json:"level"`
Content string `json:"content"`
}
// LoggingJsonHandler is a example handler for logging JSON format content.
var LoggingJsonHandler glog.Handler = func(ctx context.Context, in *glog.HandlerInput) {
jsonForLogger := JsonOutputsForLogger{
Time: in.TimeFormat,
Level: gstr.Trim(in.LevelFormat, "[]"),
Content: gstr.Trim(in.Content),
}
jsonBytes, err := json.Marshal(jsonForLogger)
if err != nil {
_, _ = os.Stderr.WriteString(err.Error())
return
}
in.Buffer.Write(jsonBytes)
in.Buffer.WriteString("\n")
in.Next()
}
func main() {
g.Log().SetHandlers(LoggingJsonHandler)
ctx := context.TODO()
g.Log().Debug(ctx, "Debugging...")
g.Log().Warning(ctx, "It is warning info")
}
可以看到,我们可以在Handler
中通过属性操作来控制输出的日志内容。如果在所有的前置中间件Handler
处理后Buffer
内容为空,那么继续Next
执行后将会执行日志中间件默认的Handler
逻辑。执行本示例的代码后,终端输出:
package main
import (
"context"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/glog"
gelf "github.com/robertkowalski/graylog-golang"
)
var grayLogClient = gelf.New(gelf.Config{
GraylogPort: 80,
GraylogHostname: "graylog-host.com",
Connection: "wan",
MaxChunkSizeWan: 42,
MaxChunkSizeLan: 1337,
})
// LoggingGrayLogHandler is an example handler for logging content to remote GrayLog service.
var LoggingGrayLogHandler glog.Handler = func(ctx context.Context, in *glog.HandlerInput) {
in.Next()
grayLogClient.Log(in.Buffer.String())
}
func main() {
g.Log().SetHandlers(LoggingGrayLogHandler)
ctx := context.TODO()
g.Log().Debug(ctx, "Debugging...")
g.Log().Warning(ctx, "It is warning info")
g.Log().Error(ctx, "Error occurs, please have a check")
glog.Print(ctx, "test log")