github.com/wangyougui/gf/v2@v2.6.5/os/glog/glog_logger_handler_json.go (about) 1 // Copyright GoFrame Author(https://goframe.org). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/wangyougui/gf. 6 7 package glog 8 9 import ( 10 "context" 11 12 "github.com/wangyougui/gf/v2/internal/json" 13 "github.com/wangyougui/gf/v2/util/gconv" 14 ) 15 16 // HandlerOutputJson is the structure outputting logging content as single json. 17 type HandlerOutputJson struct { 18 Time string `json:""` // Formatted time string, like "2016-01-09 12:00:00". 19 TraceId string `json:",omitempty"` // Trace id, only available if tracing is enabled. 20 CtxStr string `json:",omitempty"` // The retrieved context value string from context, only available if Config.CtxKeys configured. 21 Level string `json:""` // Formatted level string, like "DEBU", "ERRO", etc. Eg: ERRO 22 CallerPath string `json:",omitempty"` // The source file path and its line number that calls logging, only available if F_FILE_SHORT or F_FILE_LONG set. 23 CallerFunc string `json:",omitempty"` // The source function name that calls logging, only available if F_CALLER_FN set. 24 Prefix string `json:",omitempty"` // Custom prefix string for logging content. 25 Content string `json:""` // Content is the main logging content, containing error stack string produced by logger. 26 Stack string `json:",omitempty"` // Stack string produced by logger, only available if Config.StStatus configured. 27 } 28 29 // HandlerJson is a handler for output logging content as a single json string. 30 func HandlerJson(ctx context.Context, in *HandlerInput) { 31 output := HandlerOutputJson{ 32 Time: in.TimeFormat, 33 TraceId: in.TraceId, 34 CtxStr: in.CtxStr, 35 Level: in.LevelFormat, 36 CallerFunc: in.CallerFunc, 37 CallerPath: in.CallerPath, 38 Prefix: in.Prefix, 39 Content: in.Content, 40 Stack: in.Stack, 41 } 42 // Convert values string content. 43 var valueContent string 44 for _, v := range in.Values { 45 valueContent = gconv.String(v) 46 if len(valueContent) == 0 { 47 continue 48 } 49 if len(output.Content) > 0 { 50 if output.Content[len(output.Content)-1] == '\n' { 51 // Remove one blank line(\n\n). 52 if valueContent[0] == '\n' { 53 valueContent = valueContent[1:] 54 } 55 output.Content += valueContent 56 } else { 57 output.Content += " " + valueContent 58 } 59 } else { 60 output.Content += valueContent 61 } 62 } 63 // Output json content. 64 jsonBytes, err := json.Marshal(output) 65 if err != nil { 66 panic(err) 67 } 68 in.Buffer.Write(jsonBytes) 69 in.Buffer.Write([]byte("\n")) 70 in.Next(ctx) 71 }