gitee.com/go-spring2/spring-base@v1.1.3/log/example/layout/main.go (about) 1 /* 2 * Copyright 2012-2019 the original author or authors. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * https://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package main 18 19 import ( 20 "bytes" 21 "context" 22 "fmt" 23 24 "gitee.com/go-spring2/spring-base/log" 25 "gitee.com/go-spring2/spring-base/util" 26 ) 27 28 func init() { 29 log.RegisterPlugin("ExampleLayout", log.PluginTypeLayout, (*ExampleLayout)(nil)) 30 } 31 32 type ExampleLayout struct{} 33 34 func (c *ExampleLayout) ToBytes(e *log.Event) ([]byte, error) { 35 buf := bytes.NewBuffer(nil) 36 prefix := fmt.Sprintf("[%s][%s:%d][%s] ", e.Level, e.File, e.Line, e.Time.Format("2006-01-02 15:04:05.000")) 37 buf.WriteString(prefix) 38 if ctx := e.Context; ctx != nil { 39 span := SpanFromContext(ctx) 40 if span != nil { 41 s := fmt.Sprintf("trace_id=%s||span_id=%s||", span.TraceID, span.SpanID) 42 buf.WriteString(s) 43 } 44 } 45 enc := log.NewFlatEncoder(buf, "||") 46 for _, f := range e.Fields { 47 err := enc.AppendKey(f.Key) 48 if err != nil { 49 return nil, err 50 } 51 err = f.Val.Encode(enc) 52 if err != nil { 53 return nil, err 54 } 55 } 56 buf.WriteString("\n") 57 return buf.Bytes(), nil 58 } 59 60 func main() { 61 62 config := ` 63 <?xml version="1.0" encoding="UTF-8"?> 64 <Configuration> 65 <Appenders> 66 <Console name="Console"> 67 <ExampleLayout/> 68 </Console> 69 </Appenders> 70 <Loggers> 71 <Root level="trace"> 72 <AppenderRef ref="Console"/> 73 </Root> 74 </Loggers> 75 </Configuration> 76 ` 77 78 err := log.RefreshBuffer(config, ".xml") 79 util.Panic(err).When(err != nil) 80 81 logger := log.GetLogger("xxx") 82 logger.Info("a", "=", "1") 83 logger.Infof("a=1") 84 logger.Infow(log.Int("a", 1)) 85 86 span := &Span{TraceID: "1111", SpanID: "2222"} 87 ctx := ContextWithSpan(context.Background(), span) 88 logger.WithContext(ctx).Info("a", "=", "1") 89 logger.WithContext(ctx).Infof("a=1") 90 logger.WithContext(ctx).Infow(log.Int("a", 1)) 91 } 92 93 ///////////////////////////// observability ///////////////////////////// 94 95 type Span struct { 96 TraceID string 97 SpanID string 98 } 99 100 type spanKeyType int 101 102 var spanKey spanKeyType 103 104 func SpanFromContext(ctx context.Context) *Span { 105 v := ctx.Value(spanKey) 106 if v == nil { 107 return nil 108 } 109 return v.(*Span) 110 } 111 112 func ContextWithSpan(ctx context.Context, span *Span) context.Context { 113 return context.WithValue(ctx, spanKey, span) 114 }