diff --git a/.github/workflows/pr-check.yml b/.github/workflows/pr-check.yml index e0609d9..c5a8059 100644 --- a/.github/workflows/pr-check.yml +++ b/.github/workflows/pr-check.yml @@ -11,9 +11,6 @@ jobs: - name: Check License Header uses: apache/skywalking-eyes/header@501a28d2fb4a9b962661987e50cf0219631b32ff - - name: typos-action - uses: crate-ci/typos@master - resolve-modules: name: resolve module runs-on: ubuntu-latest @@ -35,7 +32,7 @@ jobs: steps: - uses: actions/setup-go@v4 with: - go-version: "1.21.1" + go-version: "1.21" cache: false - uses: actions/checkout@v4 - name: Lint diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 386fd89..94b52e2 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -12,7 +12,7 @@ jobs: - name: Set up Go uses: actions/setup-go@v4 with: - go-version: 1.21.1 + go-version: 1.21 - uses: actions/cache@v3 with: diff --git a/accesslog/accesslog.go b/accesslog/accesslog.go index ee42929..eceb5aa 100644 --- a/accesslog/accesslog.go +++ b/accesslog/accesslog.go @@ -43,158 +43,15 @@ package accesslog import ( "context" - "fmt" - "os" - "strconv" - "strings" - "sync" - "sync/atomic" - "time" + "github.com/cloudwego-contrib/cwgo-pkg/log/accesslog" "github.com/cloudwego/hertz/pkg/app" - "github.com/cloudwego/hertz/pkg/common/bytebufferpool" ) -var defaultFormat = " %s | %3d | %7v | %-7s | %-s " - func New(opts ...Option) app.HandlerFunc { - return new(context.Background(), opts...) + return accesslog.New(opts...) } func NewWithContext(ctx context.Context, opts ...Option) app.HandlerFunc { - return new(ctx, opts...) -} - -func new(ctx context.Context, opts ...Option) app.HandlerFunc { - cfg := newOptions(opts...) - // Check if format contains latency - cfg.enableLatency = strings.Contains(cfg.format, "${latency}") - - // Create correct time format - var timestamp atomic.Value - timestamp.Store(time.Now().In(cfg.timeZoneLocation).Format(cfg.timeFormat)) - - // Update date/time every 500 milliseconds in a separate go routine - if strings.Contains(cfg.format, "${time}") { - go func() { - for { - select { - case <-time.After(cfg.timeInterval): - case <-ctx.Done(): - return - } - timestamp.Store(time.Now().In(cfg.timeZoneLocation).Format(cfg.timeFormat)) - } - }() - } - - // Set PID once and add tag - pid := strconv.Itoa(os.Getpid()) - - dataPool := sync.Pool{ - New: func() interface{} { - return &Data{} - }, - } - - // instead of analyzing the template inside(handler) each time, this is done once before - // and we create several slices of the same length with the functions to be executed and fixed parts. - tmplChain, logFunChain, err := buildLogFuncChain(cfg, Tags) - if err != nil { - panic(err) - } - - return func(ctx context.Context, c *app.RequestContext) { - var start, stop time.Time - - // Logger data - data := dataPool.Get().(*Data) //nolint:forcetypeassert,errcheck // We store nothing else in the pool - // no need for a reset, as long as we always override everything - data.Pid = pid - data.Timestamp = timestamp - // put data back in the pool - defer dataPool.Put(data) - - // Set latency start time - if cfg.enableLatency { - data.Start = time.Now() - } - - c.Next(ctx) - - if !cfg.logConditionFunc(ctx, c) { - return - } - - if cfg.enableLatency { - data.Stop = time.Now() - } - - // Get new buffer - buf := bytebufferpool.Get() - defer bytebufferpool.Put(buf) - - if cfg.format == defaultTagFormat { - // format log to buffer - _, _ = buf.WriteString(fmt.Sprintf(defaultFormat, - timestamp, - c.Response.StatusCode(), - stop.Sub(start), - c.Method(), - c.Path(), - )) - - cfg.logFunc(ctx, buf.String()) - return - } - - // Loop over template parts execute dynamic parts and add fixed parts to the buffer - for i, logFunc := range logFunChain { - if logFunc == nil { - _, _ = buf.Write(tmplChain[i]) //nolint:errcheck // This will never fail - } else if tmplChain[i] == nil { - _, err = logFunc(buf, c, data, "") - } else { - _, err = logFunc(buf, c, data, unsafeString(tmplChain[i])) - } - if err != nil { - break - } - } - - // Also write errors to the buffer - if err != nil { - _, _ = buf.WriteString(err.Error()) - } - - cfg.logFunc(ctx, buf.String()) - } -} - -func appendInt(output Buffer, v int) (int, error) { - old := output.Len() - output.Set(appendUint(output.Bytes(), v)) - return output.Len() - old, nil -} - -func appendUint(dst []byte, n int) []byte { - if n < 0 { - panic("BUG: int must be positive") - } - - var b [20]byte - buf := b[:] - i := len(buf) - var q int - for n >= 10 { - i-- - q = n / 10 - buf[i] = '0' + byte(n-q*10) - n = q - } - i-- - buf[i] = '0' + byte(n) - - dst = append(dst, buf[i:]...) - return dst + return accesslog.NewWithContext(ctx, opts...) } diff --git a/accesslog/go.mod b/accesslog/go.mod index 69381c1..2240091 100644 --- a/accesslog/go.mod +++ b/accesslog/go.mod @@ -1,5 +1,31 @@ module github.com/hertz-contrib/logger/accesslog -go 1.16 +go 1.21 -require github.com/cloudwego/hertz v0.7.2 +require ( + github.com/cloudwego-contrib/cwgo-pkg/log/accesslog v0.0.0-00010101000000-000000000000 + github.com/cloudwego/hertz v0.7.2 +) + +require ( + github.com/bytedance/go-tagexpr/v2 v2.9.2 // indirect + github.com/bytedance/gopkg v0.0.0-20220413063733-65bf48ffb3a7 // indirect + github.com/bytedance/sonic v1.8.1 // indirect + github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect + github.com/cloudwego/netpoll v0.5.0 // indirect + github.com/fsnotify/fsnotify v1.5.4 // indirect + github.com/golang/protobuf v1.5.0 // indirect + github.com/henrylee2cn/ameda v1.4.10 // indirect + github.com/henrylee2cn/goutil v0.0.0-20210127050712-89660552f6f8 // indirect + github.com/klauspost/cpuid/v2 v2.0.9 // indirect + github.com/nyaruka/phonenumbers v1.0.55 // indirect + github.com/tidwall/gjson v1.14.4 // indirect + github.com/tidwall/match v1.1.1 // indirect + github.com/tidwall/pretty v1.2.0 // indirect + github.com/twitchyliquid64/golang-asm v0.15.1 // indirect + golang.org/x/arch v0.0.0-20210923205945-b76863e36670 // indirect + golang.org/x/sys v0.0.0-20220412211240-33da011f77ad // indirect + google.golang.org/protobuf v1.27.1 // indirect +) + +replace github.com/cloudwego-contrib/cwgo-pkg/log/accesslog => github.com/smx-Morgan/cwgo-pkg/log/accesslog v0.0.0-20241019002536-84cf43046703 diff --git a/accesslog/go.sum b/accesslog/go.sum index a40fbf6..e19e9e2 100644 --- a/accesslog/go.sum +++ b/accesslog/go.sum @@ -43,6 +43,8 @@ github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d h1:zE9ykE github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= github.com/smartystreets/goconvey v1.6.4 h1:fv0U8FUIMPNf1L9lnHLvLhgicrIVChEkdzIKYqbNC9s= github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= +github.com/smx-Morgan/cwgo-pkg/log/accesslog v0.0.0-20241019002536-84cf43046703 h1:OGsj2gJNg/Xi+zIWAQT5ywPjoOiCby4hRAkTtttfAso= +github.com/smx-Morgan/cwgo-pkg/log/accesslog v0.0.0-20241019002536-84cf43046703/go.mod h1:k8o+J4eSyMBm9UFYdULTyN2RKlKh5/I8VN8NDHujnq0= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= diff --git a/accesslog/option.go b/accesslog/option.go index ee6f870..d1b42bd 100644 --- a/accesslog/option.go +++ b/accesslog/option.go @@ -45,106 +45,41 @@ import ( "context" "time" - "github.com/cloudwego/hertz/pkg/app" + "github.com/cloudwego-contrib/cwgo-pkg/log/accesslog" - "github.com/cloudwego/hertz/pkg/common/hlog" + "github.com/cloudwego/hertz/pkg/app" ) type ( - logConditionFunc func(ctx context.Context, c *app.RequestContext) bool - - // options defines the config for middleware. - options struct { - // format defines the logging tags - // - // Optional. Default: [${time}] ${status} - ${latency} ${method} ${path}\n - format string - - // timeFormat defines timestamp format https://programming.guide/go/format-parse-string-time-date-example.html - // - // Optional. Default: 15:04:05 - timeFormat string - - // timeInterval is the delay before the timestamp is updated - // - // Optional. Default: 500 * time.Millisecond - timeInterval time.Duration - - // logFunc custom define log function - // - // Optional. Default: hlog.CtxInfof - logFunc func(ctx context.Context, format string, v ...interface{}) - - // timeZoneLocation can be specified time zone - // - // Optional. Default: time.Local - timeZoneLocation *time.Location - enableLatency bool - logConditionFunc logConditionFunc - } - - Option func(o *options) + Option = accesslog.Option ) -var defaultTagFormat = "[${time}] ${status} - ${latency} ${method} ${path}" - -func newOptions(opts ...Option) *options { - cfg := &options{ - format: defaultTagFormat, - timeFormat: "15:04:05", - timeZoneLocation: time.Local, - timeInterval: 500 * time.Millisecond, - logFunc: hlog.CtxInfof, - logConditionFunc: func(ctx context.Context, c *app.RequestContext) bool { - return true - }, - } - - for _, opt := range opts { - opt(cfg) - } - - return cfg -} - // WithFormat set log format func WithFormat(s string) Option { - return func(o *options) { - o.format = s - } + return accesslog.WithFormat(s) } // WithTimeFormat set log time format func WithTimeFormat(s string) Option { - return func(o *options) { - o.timeFormat = s - } + return accesslog.WithTimeFormat(s) } // WithTimeInterval set timestamp refresh interval func WithTimeInterval(t time.Duration) Option { - return func(o *options) { - o.timeInterval = t - } + return accesslog.WithTimeInterval(t) } // WithAccessLogFunc set print log function func WithAccessLogFunc(f func(ctx context.Context, format string, v ...interface{})) Option { - return func(o *options) { - o.logFunc = f - } + return accesslog.WithAccessLogFunc(f) } // WithTimeZoneLocation set timestamp zone func WithTimeZoneLocation(loc *time.Location) Option { - return func(o *options) { - o.timeZoneLocation = loc - } + return accesslog.WithTimeZoneLocation(loc) } // WithLogConditionFunc set logConditionFunc -func WithLogConditionFunc(f logConditionFunc) Option { - return func(o *options) { - o.logConditionFunc = f - } +func WithLogConditionFunc(f func(ctx context.Context, c *app.RequestContext) bool) Option { + return accesslog.WithLogConditionFunc(f) } diff --git a/accesslog/option_test.go b/accesslog/option_test.go deleted file mode 100644 index 0acba98..0000000 --- a/accesslog/option_test.go +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright 2022 CloudWeGo Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * MIT License - * - * Copyright (c) 2019-present Fenny and Contributors - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE.E SOFTWARE. - * - * This file may have been modified by CloudWeGo authors. All CloudWeGo - * Modifications are Copyright 2022 CloudWeGo Authors. - */ - -package accesslog - -import ( - "fmt" - "testing" - "time" - - "github.com/cloudwego/hertz/pkg/common/hlog" - "github.com/cloudwego/hertz/pkg/common/test/assert" -) - -func TestDefaultOption(t *testing.T) { - opts := newOptions() - assert.DeepEqual(t, defaultTagFormat, opts.format) - assert.DeepEqual(t, "15:04:05", opts.timeFormat) - assert.DeepEqual(t, time.Local, opts.timeZoneLocation) - assert.DeepEqual(t, 500*time.Millisecond, opts.timeInterval) - assert.DeepEqual(t, fmt.Sprintf("%p", hlog.CtxInfof), fmt.Sprintf("%p", opts.logFunc)) -} - -func TestOption(t *testing.T) { - opts := newOptions( - WithFormat("[${time}] ${status} - ${latency} ${method} ${path} ${referer}"), - WithTimeFormat(time.UnixDate), - WithTimeInterval(100*time.Millisecond), - WithAccessLogFunc(hlog.CtxDebugf), - ) - assert.DeepEqual(t, "[${time}] ${status} - ${latency} ${method} ${path} ${referer}", opts.format) - assert.DeepEqual(t, time.UnixDate, opts.timeFormat) - assert.DeepEqual(t, 100*time.Millisecond, opts.timeInterval) - assert.DeepEqual(t, fmt.Sprintf("%p", hlog.CtxDebugf), fmt.Sprintf("%p", opts.logFunc)) - assert.DeepEqual(t, false, opts.enableLatency) -} diff --git a/accesslog/tags.go b/accesslog/tags.go index 45219b3..3cccfb7 100644 --- a/accesslog/tags.go +++ b/accesslog/tags.go @@ -42,134 +42,38 @@ package accesslog import ( - "fmt" - "strings" - "sync/atomic" - "time" - - "github.com/cloudwego/hertz/pkg/app" + "github.com/cloudwego-contrib/cwgo-pkg/log/accesslog" ) const ( - TagPid = "pid" - TagTime = "time" - TagReferer = "referer" - TagProtocol = "protocol" - TagPort = "port" - TagIP = "ip" - TagIPs = "ips" - TagHost = "host" - TagClientIP = "clientIP" - TagMethod = "method" - TagPath = "path" - TagURL = "url" - TagUA = "ua" - TagLatency = "latency" - TagStatus = "status" - TagResBody = "resBody" - TagReqHeaders = "reqHeaders" - TagResHeaders = "resHeaders" - TagQueryStringParams = "queryParams" - TagBody = "body" - TagBytesSent = "bytesSent" - TagBytesReceived = "bytesReceived" - TagRoute = "route" + TagPid = accesslog.TagPid + TagTime = accesslog.TagTime + TagReferer = accesslog.TagReferer + TagProtocol = accesslog.TagProtocol + TagPort = accesslog.TagPort + TagIP = accesslog.TagIP + TagIPs = accesslog.TagIPs + TagHost = accesslog.TagHost + TagClientIP = accesslog.TagClientIP + TagMethod = accesslog.TagMethod + TagPath = accesslog.TagPath + TagURL = accesslog.TagURL + TagUA = accesslog.TagUA + TagLatency = accesslog.TagLatency + TagStatus = accesslog.TagStatus + TagResBody = accesslog.TagResBody + TagReqHeaders = accesslog.TagReqHeaders + TagResHeaders = accesslog.TagResHeaders + TagQueryStringParams = accesslog.TagQueryStringParams + TagBody = accesslog.TagBody + TagBytesSent = accesslog.TagBytesSent + TagBytesReceived = accesslog.TagBytesReceived + TagRoute = accesslog.TagRoute ) -type LogFunc func(output Buffer, c *app.RequestContext, data *Data, extraParam string) (int, error) +type LogFunc = accesslog.LogFunc // Data is a struct to define some variables to use in custom logger function. -type Data struct { - Pid string - Start time.Time - Stop time.Time - Timestamp atomic.Value -} +type Data = accesslog.Data -var Tags = map[string]LogFunc{ - TagReferer: func(output Buffer, c *app.RequestContext, data *Data, extraParam string) (int, error) { - return output.WriteString(c.Request.Header.Get("Referer")) - }, - TagProtocol: func(output Buffer, c *app.RequestContext, data *Data, extraParam string) (int, error) { - return output.WriteString(string(c.Request.URI().Scheme())) - }, - TagPort: func(output Buffer, c *app.RequestContext, data *Data, extraParam string) (int, error) { - host := string(c.Request.URI().Host()) - split := strings.Split(host, ":") - return output.WriteString(split[1]) - }, - TagIP: func(output Buffer, c *app.RequestContext, data *Data, extraParam string) (int, error) { - host := string(c.Request.URI().Host()) - split := strings.Split(host, ":") - return output.WriteString(split[0]) - }, - TagIPs: func(output Buffer, c *app.RequestContext, data *Data, extraParam string) (int, error) { - return output.WriteString(c.Request.Header.Get("X-Forwarded-For")) - }, - TagResBody: func(output Buffer, c *app.RequestContext, data *Data, extraParam string) (int, error) { - return output.WriteString(string(c.Response.Body())) - }, - TagHost: func(output Buffer, c *app.RequestContext, data *Data, extraParam string) (int, error) { - return output.WriteString(string(c.Request.URI().Host())) - }, - TagClientIP: func(output Buffer, c *app.RequestContext, data *Data, extraParam string) (int, error) { - return output.WriteString(c.ClientIP()) - }, - TagPath: func(output Buffer, c *app.RequestContext, data *Data, extraParam string) (int, error) { - return output.WriteString(string(c.Request.Path())) - }, - TagURL: func(output Buffer, c *app.RequestContext, data *Data, extraParam string) (int, error) { - return output.WriteString(string(c.Request.Header.RequestURI())) - }, - TagUA: func(output Buffer, c *app.RequestContext, data *Data, extraParam string) (int, error) { - return output.WriteString(c.Request.Header.Get("User-Agent")) - }, - TagBody: func(output Buffer, c *app.RequestContext, data *Data, extraParam string) (int, error) { - return output.Write(c.Request.Body()) - }, - TagBytesSent: func(output Buffer, c *app.RequestContext, data *Data, extraParam string) (int, error) { - if c.Response.Header.ContentLength() < 0 { - return appendInt(output, 0) - } - return appendInt(output, len(c.Response.Body())) - }, - TagBytesReceived: func(output Buffer, c *app.RequestContext, data *Data, extraParam string) (int, error) { - return appendInt(output, len(c.Request.Body())) - }, - TagRoute: func(output Buffer, c *app.RequestContext, data *Data, extraParam string) (int, error) { - return output.WriteString(string(c.Path())) - }, - TagStatus: func(output Buffer, c *app.RequestContext, data *Data, extraParam string) (int, error) { - return appendInt(output, c.Response.StatusCode()) - }, - TagReqHeaders: func(output Buffer, c *app.RequestContext, data *Data, extraParam string) (int, error) { - reqHeaders := make([]string, 0) - c.Request.Header.VisitAll(func(k, v []byte) { - reqHeaders = append(reqHeaders, string(k)+"="+string(v)) - }) - return output.Write([]byte(strings.Join(reqHeaders, "&"))) - }, - TagResHeaders: func(output Buffer, c *app.RequestContext, data *Data, extraParam string) (int, error) { - resHeaders := make([]string, 0) - c.Response.Header.VisitAll(func(k, v []byte) { - resHeaders = append(resHeaders, string(k)+"="+string(v)) - }) - return output.Write([]byte(strings.Join(resHeaders, "&"))) - }, - TagQueryStringParams: func(output Buffer, c *app.RequestContext, data *Data, extraParam string) (int, error) { - return output.WriteString(c.Request.URI().QueryArgs().String()) - }, - TagMethod: func(output Buffer, c *app.RequestContext, data *Data, extraParam string) (int, error) { - return output.WriteString(string(c.Method())) - }, - TagLatency: func(output Buffer, c *app.RequestContext, data *Data, extraParam string) (int, error) { - latency := data.Stop.Sub(data.Start) - return output.WriteString(fmt.Sprintf("%13v", latency)) - }, - TagPid: func(output Buffer, c *app.RequestContext, data *Data, extraParam string) (int, error) { - return output.WriteString(data.Pid) - }, - TagTime: func(output Buffer, c *app.RequestContext, data *Data, extraParam string) (int, error) { - return output.WriteString(data.Timestamp.Load().(string)) - }, -} +var Tags = accesslog.Tags diff --git a/accesslog/tmpl_chain.go b/accesslog/tmpl_chain.go index a2e2dc6..05942b2 100644 --- a/accesslog/tmpl_chain.go +++ b/accesslog/tmpl_chain.go @@ -42,106 +42,7 @@ package accesslog import ( - "bytes" - "errors" - "io" - "reflect" - "unsafe" + "github.com/cloudwego-contrib/cwgo-pkg/log/accesslog" ) -const ( - startTag = "${" - endTag = "}" - paramSeparator = ":" -) - -type Buffer interface { - Len() int - ReadFrom(r io.Reader) (int64, error) - WriteTo(w io.Writer) (int64, error) - Bytes() []byte - Write(p []byte) (int, error) - WriteByte(c byte) error - WriteString(s string) (int, error) - Set(p []byte) - SetString(s string) - String() string -} - -// buildLogFuncChain analyzes the template and creates slices with the functions for execution and -// slices with the fixed parts of the template and the parameters -// -// fixParts contains the fixed parts of the template or parameters if a function is stored in the funcChain at this position -// funcChain contains for the parts which exist the functions for the dynamic parts -// funcChain and fixParts always have the same length and contain nil for the parts where no data is required in the chain, -// if a function exists for the part, a parameter for it can also exist in the fixParts slice -func buildLogFuncChain(cfg *options, tagFunctions map[string]LogFunc) ([][]byte, []LogFunc, error) { - // process flow is copied from the fasttemplate flow https://github.com/valyala/fasttemplate/blob/2a2d1afadadf9715bfa19683cdaeac8347e5d9f9/template.go#L23-L62 - templateB := unsafeBytes(cfg.format) - startTagB := unsafeBytes(startTag) - endTagB := unsafeBytes(endTag) - paramSeparatorB := unsafeBytes(paramSeparator) - - var fixParts [][]byte - var funcChain []LogFunc - - for { - currentPos := bytes.Index(templateB, startTagB) - if currentPos < 0 { - // no starting tag found in the existing template part - break - } - // add fixed part - funcChain = append(funcChain, nil) - fixParts = append(fixParts, templateB[:currentPos]) - - templateB = templateB[currentPos+len(startTagB):] - currentPos = bytes.Index(templateB, endTagB) - if currentPos < 0 { - // cannot find end tag - just write it to the output. - funcChain = append(funcChain, nil) - fixParts = append(fixParts, startTagB) - break - } - // ## function block ## - // first check for tags with parameters - if index := bytes.Index(templateB[:currentPos], paramSeparatorB); index != -1 { - logFunc, ok := tagFunctions[unsafeString(templateB[:index+1])] - if !ok { - return nil, nil, errors.New("No parameter found in \"" + unsafeString(templateB[:currentPos]) + "\"") - } - funcChain = append(funcChain, logFunc) - // add param to the fixParts - fixParts = append(fixParts, templateB[index+1:currentPos]) - } else if logFunc, ok := tagFunctions[unsafeString(templateB[:currentPos])]; ok { - // add functions without parameter - funcChain = append(funcChain, logFunc) - fixParts = append(fixParts, nil) - } - // ## function block end ## - - // reduce the template string - templateB = templateB[currentPos+len(endTagB):] - } - // set the rest - funcChain = append(funcChain, nil) - fixParts = append(fixParts, templateB) - - return fixParts, funcChain, nil -} - -const MaxStringLen = 0x7fff0000 // Maximum string length for UnsafeBytes. (decimal: 2147418112) - -func unsafeBytes(s string) []byte { - if s == "" { - return nil - } - - return (*[MaxStringLen]byte)(unsafe.Pointer( - (*reflect.StringHeader)(unsafe.Pointer(&s)).Data), - )[:len(s):len(s)] -} - -func unsafeString(b []byte) string { - return *(*string)(unsafe.Pointer(&b)) -} +type Buffer = accesslog.Buffer diff --git a/logrus/go.mod b/logrus/go.mod index ccc84f7..e5e522f 100644 --- a/logrus/go.mod +++ b/logrus/go.mod @@ -1,10 +1,13 @@ module github.com/hertz-contrib/logger/logrus -go 1.17 +go 1.21 + +toolchain go1.21.12 require ( - github.com/cloudwego/hertz v0.4.0 - github.com/sirupsen/logrus v1.9.0 + github.com/cloudwego-contrib/cwgo-pkg/log/logging/logrus v0.0.0-20241014044734-80a98dbe0b6a + github.com/cloudwego/hertz v0.9.2 + github.com/sirupsen/logrus v1.9.2 ) -require golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8 // indirect +require golang.org/x/sys v0.21.0 // indirect diff --git a/logrus/go.sum b/logrus/go.sum index 0eb274a..b61d7e2 100644 --- a/logrus/go.sum +++ b/logrus/go.sum @@ -1,47 +1,71 @@ github.com/bytedance/go-tagexpr/v2 v2.9.2/go.mod h1:5qsx05dYOiUXOUgnQ7w3Oz8BYs2qtM/bJokdLb79wRM= github.com/bytedance/gopkg v0.0.0-20220413063733-65bf48ffb3a7/go.mod h1:2ZlV9BaUH4+NXIBF0aMdKKAnHTzqH+iMU4KUjAbL23Q= +github.com/bytedance/mockey v1.2.1/go.mod h1:+Jm/fzWZAuhEDrPXVjDf/jLM2BlLXJkwk94zf2JZ3X4= github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM= +github.com/bytedance/sonic v1.8.1/go.mod h1:i736AoUSYt75HyZLoJW9ERYxcy6eaN6h4BZXU064P/U= github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY= -github.com/cloudwego/hertz v0.4.0 h1:qigNIzhOpydsEgenCCHoLObQgkumg7aPR7MvvkbeVuo= -github.com/cloudwego/hertz v0.4.0/go.mod h1:QSD2254yaf43BIy4isrlfKR42R3uFAT+6G5CpeROOJs= -github.com/cloudwego/netpoll v0.2.6/go.mod h1:1T2WVuQ+MQw6h6DpE45MohSvDTKdy2DlzCx2KsnPI4E= +github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk= +github.com/cloudwego-contrib/cwgo-pkg/log/logging/logrus v0.0.0-20241014044734-80a98dbe0b6a h1:kpu/RTVoMi2VloWZPo1SDpY/DedkGfMvLmiaMt40RUI= +github.com/cloudwego-contrib/cwgo-pkg/log/logging/logrus v0.0.0-20241014044734-80a98dbe0b6a/go.mod h1:PCebhPHtSuvo3D7bligLXjdsbYZLsKqNicdd9bl033w= +github.com/cloudwego/hertz v0.9.2 h1:VbqddZ5RuvcgxzfxvXcmTiRisGYoo0+WnHGeDJKhjqI= +github.com/cloudwego/hertz v0.9.2/go.mod h1:cs8dH6unM4oaJ5k9m6pqbgLBPqakGWMG0+cthsxitsg= +github.com/cloudwego/netpoll v0.6.0/go.mod h1:xVefXptcyheopwNDZjDPcfU6kIjZXZ4nY550k1yH9eQ= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/fsnotify/fsnotify v1.5.4/go.mod h1:OVB6XrOHzAwXMpEM7uPOzcehqUV2UqJxmVXmkdnm1bU= github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/henrylee2cn/ameda v1.4.8/go.mod h1:liZulR8DgHxdK+MEwvZIylGnmcjzQ6N6f2PlWe7nEO4= github.com/henrylee2cn/ameda v1.4.10/go.mod h1:liZulR8DgHxdK+MEwvZIylGnmcjzQ6N6f2PlWe7nEO4= github.com/henrylee2cn/goutil v0.0.0-20210127050712-89660552f6f8/go.mod h1:Nhe/DM3671a5udlv2AdV2ni/MZzgfv2qrPL5nIi3EGQ= +github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= github.com/nyaruka/phonenumbers v1.0.55/go.mod h1:sDaTZ/KPX5f8qyV9qN+hIm+4ZBARJrupC6LuhshJq1U= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/sirupsen/logrus v1.9.0 h1:trlNQbNUG3OdDrDil03MCb1H2o9nJ1x4/5LYw7byDE0= -github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= +github.com/sirupsen/logrus v1.9.2 h1:oxx1eChJGI6Uks2ZC4W1zpLlVgqB8ner4EuQwV4Ik1Y= +github.com/sirupsen/logrus v1.9.2/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= +github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= +github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= -github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= +github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/tidwall/gjson v1.9.3/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= -github.com/tidwall/gjson v1.13.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= +github.com/tidwall/gjson v1.14.4/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM= github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= +golang.org/x/arch v0.0.0-20201008161808-52c3e6f60cff/go.mod h1:flIaEI6LNU6xOCD5PaJvn9wGP0agmIOqjrtsKGRguv4= golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20220110181412-a018aaa089fe/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8 h1:0A+M6Uqn+Eje4kHMK80dtF3JCXC4ykBgQG4Fe06QRhQ= golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.21.0 h1:rF+pYz3DAGSQAxAu1CbC7catZg4ebC4UIeIhKxBZvws= +golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4= diff --git a/logrus/logger.go b/logrus/logger.go index 18431ee..af57a8c 100644 --- a/logrus/logger.go +++ b/logrus/logger.go @@ -42,148 +42,16 @@ package logrus import ( - "context" - "io" - + "github.com/cloudwego-contrib/cwgo-pkg/log/logging/logrus" "github.com/cloudwego/hertz/pkg/common/hlog" - "github.com/sirupsen/logrus" ) var _ hlog.FullLogger = (*Logger)(nil) // Logger logrus impl -type Logger struct { - l *logrus.Logger -} +type Logger = logrus.Logger // NewLogger create a logger func NewLogger(opts ...Option) *Logger { - cfg := defaultConfig() - - // apply options - for _, opt := range opts { - opt.apply(cfg) - } - - // attach hook - for _, hook := range cfg.hooks { - cfg.logger.AddHook(hook) - } - - return &Logger{ - l: cfg.logger, - } -} - -func (l *Logger) Logger() *logrus.Logger { - return l.l -} - -func (l *Logger) Trace(v ...interface{}) { - l.l.Trace(v...) -} - -func (l *Logger) Debug(v ...interface{}) { - l.l.Debug(v...) -} - -func (l *Logger) Info(v ...interface{}) { - l.l.Info(v...) -} - -func (l *Logger) Notice(v ...interface{}) { - l.l.Warn(v...) -} - -func (l *Logger) Warn(v ...interface{}) { - l.l.Warn(v...) -} - -func (l *Logger) Error(v ...interface{}) { - l.l.Error(v...) -} - -func (l *Logger) Fatal(v ...interface{}) { - l.l.Fatal(v...) -} - -func (l *Logger) Tracef(format string, v ...interface{}) { - l.l.Tracef(format, v...) -} - -func (l *Logger) Debugf(format string, v ...interface{}) { - l.l.Debugf(format, v...) -} - -func (l *Logger) Infof(format string, v ...interface{}) { - l.l.Infof(format, v...) -} - -func (l *Logger) Noticef(format string, v ...interface{}) { - l.l.Warnf(format, v...) -} - -func (l *Logger) Warnf(format string, v ...interface{}) { - l.l.Warnf(format, v...) -} - -func (l *Logger) Errorf(format string, v ...interface{}) { - l.l.Errorf(format, v...) -} - -func (l *Logger) Fatalf(format string, v ...interface{}) { - l.l.Fatalf(format, v...) -} - -func (l *Logger) CtxTracef(ctx context.Context, format string, v ...interface{}) { - l.l.WithContext(ctx).Tracef(format, v...) -} - -func (l *Logger) CtxDebugf(ctx context.Context, format string, v ...interface{}) { - l.l.WithContext(ctx).Debugf(format, v...) -} - -func (l *Logger) CtxInfof(ctx context.Context, format string, v ...interface{}) { - l.l.WithContext(ctx).Infof(format, v...) -} - -func (l *Logger) CtxNoticef(ctx context.Context, format string, v ...interface{}) { - l.l.WithContext(ctx).Warnf(format, v...) -} - -func (l *Logger) CtxWarnf(ctx context.Context, format string, v ...interface{}) { - l.l.WithContext(ctx).Warnf(format, v...) -} - -func (l *Logger) CtxErrorf(ctx context.Context, format string, v ...interface{}) { - l.l.WithContext(ctx).Errorf(format, v...) -} - -func (l *Logger) CtxFatalf(ctx context.Context, format string, v ...interface{}) { - l.l.WithContext(ctx).Fatalf(format, v...) -} - -func (l *Logger) SetLevel(level hlog.Level) { - var lv logrus.Level - switch level { - case hlog.LevelTrace: - lv = logrus.TraceLevel - case hlog.LevelDebug: - lv = logrus.DebugLevel - case hlog.LevelInfo: - lv = logrus.InfoLevel - case hlog.LevelWarn, hlog.LevelNotice: - lv = logrus.WarnLevel - case hlog.LevelError: - lv = logrus.ErrorLevel - case hlog.LevelFatal: - lv = logrus.FatalLevel - default: - lv = logrus.WarnLevel - } - l.l.SetLevel(lv) -} - -func (l *Logger) SetOutput(writer io.Writer) { - l.l.SetOutput(writer) + return logrus.NewLogger(opts...) } diff --git a/logrus/option.go b/logrus/option.go index 3308a83..7ea5b8f 100644 --- a/logrus/option.go +++ b/logrus/option.go @@ -42,47 +42,19 @@ package logrus import ( + cwlogrus "github.com/cloudwego-contrib/cwgo-pkg/log/logging/logrus" "github.com/sirupsen/logrus" ) // Option logger options -type Option interface { - apply(cfg *config) -} - -type option func(cfg *config) - -func (fn option) apply(cfg *config) { - fn(cfg) -} - -type config struct { - logger *logrus.Logger - hooks []logrus.Hook -} - -func defaultConfig() *config { - // new logger - logger := logrus.New() - // default json format - logger.SetFormatter(new(logrus.JSONFormatter)) - - return &config{ - logger: logger, - hooks: []logrus.Hook{}, - } -} +type Option = cwlogrus.Option // WithLogger configures logger func WithLogger(logger *logrus.Logger) Option { - return option(func(cfg *config) { - cfg.logger = logger - }) + return cwlogrus.WithLogger(logger) } // WithHook configures logrus hook func WithHook(hook logrus.Hook) Option { - return option(func(cfg *config) { - cfg.hooks = append(cfg.hooks, hook) - }) + return cwlogrus.WithHook(hook) } diff --git a/slog/go.mod b/slog/go.mod index edf7f86..45c9c5b 100644 --- a/slog/go.mod +++ b/slog/go.mod @@ -3,12 +3,14 @@ module github.com/hertz-contrib/logger/slog go 1.21.1 require ( - github.com/cloudwego/hertz v0.6.8 - github.com/stretchr/testify v1.8.4 + github.com/cloudwego-contrib/cwgo-pkg/log/logging/slog v0.0.0-20241014044734-80a98dbe0b6a + github.com/cloudwego/hertz v0.9.2 + github.com/stretchr/testify v1.9.0 ) require ( - github.com/davecgh/go-spew v1.1.1 // indirect + github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect + github.com/kr/text v0.2.0 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/slog/go.sum b/slog/go.sum index 8c47a1b..e82acb8 100644 --- a/slog/go.sum +++ b/slog/go.sum @@ -5,12 +5,16 @@ github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1 github.com/bytedance/sonic v1.8.1/go.mod h1:i736AoUSYt75HyZLoJW9ERYxcy6eaN6h4BZXU064P/U= github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY= github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk= -github.com/cloudwego/hertz v0.6.8 h1:nuUp2YuD3DJ4jjL9gP2IJRb84aSigbEUumuwQt0mjfc= -github.com/cloudwego/hertz v0.6.8/go.mod h1:KhztQcZtMQ46gOjZcmCy557AKD29cbumGEV0BzwevwA= -github.com/cloudwego/netpoll v0.3.2/go.mod h1:xVefXptcyheopwNDZjDPcfU6kIjZXZ4nY550k1yH9eQ= +github.com/cloudwego-contrib/cwgo-pkg/log/logging/slog v0.0.0-20241014044734-80a98dbe0b6a h1:PVc/pLMk1UYdfzxazNDAWWZe8k3mZlAVcKkTuUarVgk= +github.com/cloudwego-contrib/cwgo-pkg/log/logging/slog v0.0.0-20241014044734-80a98dbe0b6a/go.mod h1:BPZTpDxdnXH2ibM2/Ym7E8RHr1u9Vj5vW3Chm4cUpjI= +github.com/cloudwego/hertz v0.9.2 h1:VbqddZ5RuvcgxzfxvXcmTiRisGYoo0+WnHGeDJKhjqI= +github.com/cloudwego/hertz v0.9.2/go.mod h1:cs8dH6unM4oaJ5k9m6pqbgLBPqakGWMG0+cthsxitsg= +github.com/cloudwego/netpoll v0.6.0/go.mod h1:xVefXptcyheopwNDZjDPcfU6kIjZXZ4nY550k1yH9eQ= +github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/fsnotify/fsnotify v1.5.4/go.mod h1:OVB6XrOHzAwXMpEM7uPOzcehqUV2UqJxmVXmkdnm1bU= github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= @@ -21,9 +25,15 @@ github.com/henrylee2cn/ameda v1.4.10/go.mod h1:liZulR8DgHxdK+MEwvZIylGnmcjzQ6N6f github.com/henrylee2cn/goutil v0.0.0-20210127050712-89660552f6f8/go.mod h1:Nhe/DM3671a5udlv2AdV2ni/MZzgfv2qrPL5nIi3EGQ= github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/nyaruka/phonenumbers v1.0.55/go.mod h1:sDaTZ/KPX5f8qyV9qN+hIm+4ZBARJrupC6LuhshJq1U= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= +github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= @@ -35,10 +45,10 @@ github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= -github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= -github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= +github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/tidwall/gjson v1.9.3/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= -github.com/tidwall/gjson v1.13.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= +github.com/tidwall/gjson v1.14.4/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM= github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= @@ -55,8 +65,9 @@ golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3 golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= diff --git a/slog/logger.go b/slog/logger.go index be3c6f8..46cda8e 100644 --- a/slog/logger.go +++ b/slog/logger.go @@ -15,11 +15,9 @@ package slog import ( - "context" - "fmt" - "io" "log/slog" + cwslog "github.com/cloudwego-contrib/cwgo-pkg/log/logging/slog" "github.com/cloudwego/hertz/pkg/common/hlog" ) @@ -32,180 +30,10 @@ const ( var _ hlog.FullLogger = (*Logger)(nil) func NewLogger(opts ...Option) *Logger { - config := defaultConfig() - - // apply options - for _, opt := range opts { - opt.apply(config) - } - - if !config.withLevel && config.withHandlerOptions && config.handlerOptions.Level != nil { - lvl := &slog.LevelVar{} - lvl.Set(config.handlerOptions.Level.Level()) - config.level = lvl - } - config.handlerOptions.Level = config.level - - var replaceAttrDefined bool - if config.handlerOptions.ReplaceAttr == nil { - replaceAttrDefined = false - } else { - replaceAttrDefined = true - } - - replaceFun := config.handlerOptions.ReplaceAttr - - replaceAttr := func(groups []string, a slog.Attr) slog.Attr { - if a.Key == slog.LevelKey { - level := a.Value.Any().(slog.Level) - switch level { - case LevelTrace: - a.Value = slog.StringValue("Trace") - case slog.LevelDebug: - a.Value = slog.StringValue("Debug") - case slog.LevelInfo: - a.Value = slog.StringValue("Info") - case LevelNotice: - a.Value = slog.StringValue("Notice") - case slog.LevelWarn: - a.Value = slog.StringValue("Warn") - case slog.LevelError: - a.Value = slog.StringValue("Error") - case LevelFatal: - a.Value = slog.StringValue("Fatal") - default: - a.Value = slog.StringValue("Warn") - } - } - if replaceAttrDefined { - return replaceFun(groups, a) - } else { - return a - } - } - config.handlerOptions.ReplaceAttr = replaceAttr - - return &Logger{ - l: slog.New(slog.NewJSONHandler(config.output, config.handlerOptions)), - cfg: config, - } -} - -// Logger slog impl -type Logger struct { - l *slog.Logger - cfg *config -} - -func (l *Logger) Logger() *slog.Logger { - return l.l -} - -func (l *Logger) log(level hlog.Level, v ...any) { - lvl := hLevelToSLevel(level) - l.l.Log(context.TODO(), lvl, fmt.Sprint(v...)) -} - -func (l *Logger) logf(level hlog.Level, format string, kvs ...any) { - lvl := hLevelToSLevel(level) - l.l.Log(context.TODO(), lvl, fmt.Sprintf(format, kvs...)) -} - -func (l *Logger) ctxLogf(level hlog.Level, ctx context.Context, format string, v ...any) { - lvl := hLevelToSLevel(level) - l.l.Log(ctx, lvl, fmt.Sprintf(format, v...)) -} - -func (l *Logger) Trace(v ...any) { - l.log(hlog.LevelTrace, v...) -} - -func (l *Logger) Debug(v ...any) { - l.log(hlog.LevelDebug, v...) -} - -func (l *Logger) Info(v ...any) { - l.log(hlog.LevelInfo, v...) -} - -func (l *Logger) Notice(v ...any) { - l.log(hlog.LevelNotice, v...) -} - -func (l *Logger) Warn(v ...any) { - l.log(hlog.LevelWarn, v...) -} - -func (l *Logger) Error(v ...any) { - l.log(hlog.LevelError, v...) -} - -func (l *Logger) Fatal(v ...any) { - l.log(hlog.LevelFatal, v...) -} - -func (l *Logger) Tracef(format string, v ...any) { - l.logf(hlog.LevelTrace, format, v...) -} - -func (l *Logger) Debugf(format string, v ...any) { - l.logf(hlog.LevelDebug, format, v...) -} - -func (l *Logger) Infof(format string, v ...any) { - l.logf(hlog.LevelInfo, format, v...) -} - -func (l *Logger) Noticef(format string, v ...any) { - l.logf(hlog.LevelNotice, format, v...) -} - -func (l *Logger) Warnf(format string, v ...any) { - l.logf(hlog.LevelWarn, format, v...) -} - -func (l *Logger) Errorf(format string, v ...any) { - l.logf(hlog.LevelError, format, v...) -} - -func (l *Logger) Fatalf(format string, v ...any) { - l.logf(hlog.LevelFatal, format, v...) -} - -func (l *Logger) CtxTracef(ctx context.Context, format string, v ...any) { - l.ctxLogf(hlog.LevelDebug, ctx, format, v...) + return cwslog.NewLogger(opts...) } -func (l *Logger) CtxDebugf(ctx context.Context, format string, v ...any) { - l.ctxLogf(hlog.LevelDebug, ctx, format, v...) -} - -func (l *Logger) CtxInfof(ctx context.Context, format string, v ...any) { - l.ctxLogf(hlog.LevelInfo, ctx, format, v...) -} - -func (l *Logger) CtxNoticef(ctx context.Context, format string, v ...any) { - l.ctxLogf(hlog.LevelNotice, ctx, format, v...) -} - -func (l *Logger) CtxWarnf(ctx context.Context, format string, v ...any) { - l.ctxLogf(hlog.LevelWarn, ctx, format, v...) -} - -func (l *Logger) CtxErrorf(ctx context.Context, format string, v ...any) { - l.ctxLogf(hlog.LevelError, ctx, format, v...) -} - -func (l *Logger) CtxFatalf(ctx context.Context, format string, v ...any) { - l.ctxLogf(hlog.LevelFatal, ctx, format, v...) -} - -func (l *Logger) SetLevel(level hlog.Level) { - lvl := hLevelToSLevel(level) - l.cfg.level.Set(lvl) -} - -func (l *Logger) SetOutput(writer io.Writer) { - l.cfg.output = writer - l.l = slog.New(slog.NewJSONHandler(writer, l.cfg.handlerOptions)) -} +type ( + // Logger slog impl + Logger = cwslog.Logger +) diff --git a/slog/option.go b/slog/option.go index 0accc41..f57ae6d 100644 --- a/slog/option.go +++ b/slog/option.go @@ -17,61 +17,20 @@ package slog import ( "io" "log/slog" - "os" - "github.com/cloudwego/hertz/pkg/common/hlog" + cwslog "github.com/cloudwego-contrib/cwgo-pkg/log/logging/slog" ) -type Option interface { - apply(cfg *config) -} - -type option func(cfg *config) - -func (fn option) apply(cfg *config) { - fn(cfg) -} - -type config struct { - level *slog.LevelVar - withLevel bool - handlerOptions *slog.HandlerOptions - withHandlerOptions bool - output io.Writer -} - -func defaultConfig() *config { - lvl := &slog.LevelVar{} - lvl.Set(hLevelToSLevel(hlog.LevelInfo)) - - handlerOptions := &slog.HandlerOptions{ - Level: lvl, - } - return &config{ - level: lvl, - withLevel: false, - handlerOptions: handlerOptions, - withHandlerOptions: false, - output: os.Stdout, - } -} +type Option = cwslog.Option func WithLevel(lvl *slog.LevelVar) Option { - return option(func(cfg *config) { - cfg.level = lvl - cfg.withLevel = true - }) + return cwslog.WithLevel(lvl) } func WithHandlerOptions(opts *slog.HandlerOptions) Option { - return option(func(cfg *config) { - cfg.handlerOptions = opts - cfg.withHandlerOptions = true - }) + return cwslog.WithHandlerOptions(opts) } func WithOutput(writer io.Writer) Option { - return option(func(cfg *config) { - cfg.output = writer - }) + return cwslog.WithOutput(writer) } diff --git a/slog/utils.go b/slog/utils.go index b543c48..0729fea 100644 --- a/slog/utils.go +++ b/slog/utils.go @@ -13,31 +13,3 @@ // limitations under the License. package slog - -import ( - "log/slog" - - "github.com/cloudwego/hertz/pkg/common/hlog" -) - -func hLevelToSLevel(level hlog.Level) (lvl slog.Level) { - switch level { - case hlog.LevelTrace: - lvl = LevelTrace - case hlog.LevelDebug: - lvl = slog.LevelDebug - case hlog.LevelInfo: - lvl = slog.LevelInfo - case hlog.LevelWarn: - lvl = slog.LevelWarn - case hlog.LevelNotice: - lvl = LevelNotice - case hlog.LevelError: - lvl = slog.LevelError - case hlog.LevelFatal: - lvl = LevelFatal - default: - lvl = slog.LevelWarn - } - return -} diff --git a/zap/go.mod b/zap/go.mod index f218b4a..f7e1c58 100644 --- a/zap/go.mod +++ b/zap/go.mod @@ -1,17 +1,19 @@ module github.com/hertz-contrib/logger/zap -go 1.17 +go 1.21 require ( - github.com/cloudwego/hertz v0.6.2 - github.com/stretchr/testify v1.8.1 - go.uber.org/zap v1.23.0 + github.com/cloudwego-contrib/cwgo-pkg/log/logging/zap v0.0.0-20241014044734-80a98dbe0b6a + github.com/cloudwego/hertz v0.9.2 + github.com/stretchr/testify v1.9.0 + go.uber.org/zap v1.24.0 ) require ( - github.com/davecgh/go-spew v1.1.1 // indirect + github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect + github.com/kr/text v0.2.0 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect - go.uber.org/atomic v1.7.0 // indirect - go.uber.org/multierr v1.6.0 // indirect + go.uber.org/atomic v1.11.0 // indirect + go.uber.org/multierr v1.11.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/zap/go.sum b/zap/go.sum index 08e2d03..acbb801 100644 --- a/zap/go.sum +++ b/zap/go.sum @@ -1,4 +1,5 @@ github.com/benbjohnson/clock v1.1.0 h1:Q92kusRqC1XV2MjkWETPvjJVqKetz1OzxZB7mHJLju8= +github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= github.com/bytedance/go-tagexpr/v2 v2.9.2/go.mod h1:5qsx05dYOiUXOUgnQ7w3Oz8BYs2qtM/bJokdLb79wRM= github.com/bytedance/gopkg v0.0.0-20220413063733-65bf48ffb3a7/go.mod h1:2ZlV9BaUH4+NXIBF0aMdKKAnHTzqH+iMU4KUjAbL23Q= github.com/bytedance/mockey v1.2.1/go.mod h1:+Jm/fzWZAuhEDrPXVjDf/jLM2BlLXJkwk94zf2JZ3X4= @@ -6,12 +7,16 @@ github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1 github.com/bytedance/sonic v1.8.1/go.mod h1:i736AoUSYt75HyZLoJW9ERYxcy6eaN6h4BZXU064P/U= github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY= github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk= -github.com/cloudwego/hertz v0.6.2 h1:8NM0yHbyv8B4dNYgICirk733S7monTNB+uR9as1It1Y= -github.com/cloudwego/hertz v0.6.2/go.mod h1:2em2hGREvCBawsTQcQxyWBGVlCeo+N1pp2q0HkkbwR0= -github.com/cloudwego/netpoll v0.3.1/go.mod h1:1T2WVuQ+MQw6h6DpE45MohSvDTKdy2DlzCx2KsnPI4E= +github.com/cloudwego-contrib/cwgo-pkg/log/logging/zap v0.0.0-20241014044734-80a98dbe0b6a h1:OI76G86lG5bvE+7MOiu4tBKb9DpIcmUg7yKbhLJjHmk= +github.com/cloudwego-contrib/cwgo-pkg/log/logging/zap v0.0.0-20241014044734-80a98dbe0b6a/go.mod h1:UG/qXE1cyVHIrr0xGCek6YyxJyTyeXDa79Py6H+wkhA= +github.com/cloudwego/hertz v0.9.2 h1:VbqddZ5RuvcgxzfxvXcmTiRisGYoo0+WnHGeDJKhjqI= +github.com/cloudwego/hertz v0.9.2/go.mod h1:cs8dH6unM4oaJ5k9m6pqbgLBPqakGWMG0+cthsxitsg= +github.com/cloudwego/netpoll v0.6.0/go.mod h1:xVefXptcyheopwNDZjDPcfU6kIjZXZ4nY550k1yH9eQ= +github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/fsnotify/fsnotify v1.5.4/go.mod h1:OVB6XrOHzAwXMpEM7uPOzcehqUV2UqJxmVXmkdnm1bU= github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= @@ -22,35 +27,43 @@ github.com/henrylee2cn/ameda v1.4.10/go.mod h1:liZulR8DgHxdK+MEwvZIylGnmcjzQ6N6f github.com/henrylee2cn/goutil v0.0.0-20210127050712-89660552f6f8/go.mod h1:Nhe/DM3671a5udlv2AdV2ni/MZzgfv2qrPL5nIi3EGQ= github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/nyaruka/phonenumbers v1.0.55/go.mod h1:sDaTZ/KPX5f8qyV9qN+hIm+4ZBARJrupC6LuhshJq1U= -github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= +github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= -github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= -github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= +github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/tidwall/gjson v1.9.3/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= -github.com/tidwall/gjson v1.13.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= +github.com/tidwall/gjson v1.14.4/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM= github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= -go.uber.org/atomic v1.7.0 h1:ADUqmZGgLDDfbSL9ZmPxKTybcoEYHgpYfELNoN+7hsw= -go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= -go.uber.org/goleak v1.1.11 h1:wy28qYRKZgnJTxGxvye5/wgWr1EKjmUDGYox5mGlRlI= -go.uber.org/multierr v1.6.0 h1:y6IPFStTAIT5Ytl7/XYmHvzXQ7S3g/IeZW9hyZ5thw4= -go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU= -go.uber.org/zap v1.23.0 h1:OjGQ5KQDEUawVHxNwQgPpiypGHOxo2mNZsOqTak4fFY= -go.uber.org/zap v1.23.0/go.mod h1:D+nX8jyLsMHMYrln8A0rJjFt/T/9/bGgIhAqxv5URuY= +go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= +go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= +go.uber.org/goleak v1.2.1 h1:NBol2c7O1ZokfZ0LEU9K6Whx/KnwvepVetCUhtKja4A= +go.uber.org/goleak v1.2.1/go.mod h1:qlT2yGI9QafXHhZZLxlSuNsMw3FFLxBr+tBRlmO1xH4= +go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= +go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= +go.uber.org/zap v1.24.0 h1:FiJd5l1UOLj0wCgbSE0rwwXHzEdAZS6hiiSnxJN/D60= +go.uber.org/zap v1.24.0/go.mod h1:2kMP+WWQ8aoFoedH3T2sq6iJ2yDWpHbP0f6MQbS9Gkg= golang.org/x/arch v0.0.0-20201008161808-52c3e6f60cff/go.mod h1:flIaEI6LNU6xOCD5PaJvn9wGP0agmIOqjrtsKGRguv4= golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= @@ -64,8 +77,9 @@ golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3 golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= diff --git a/zap/logger.go b/zap/logger.go index d017ef3..f4a3722 100644 --- a/zap/logger.go +++ b/zap/logger.go @@ -15,253 +15,14 @@ package zap import ( - "context" - "io" - + cwzap "github.com/cloudwego-contrib/cwgo-pkg/log/logging/zap" "github.com/cloudwego/hertz/pkg/common/hlog" - "go.uber.org/zap" - "go.uber.org/zap/zapcore" ) var _ hlog.FullLogger = (*Logger)(nil) -type Logger struct { - l *zap.Logger - config *config -} +type Logger = cwzap.Logger func NewLogger(opts ...Option) *Logger { - config := defaultConfig() - - // apply options - for _, opt := range opts { - opt.apply(config) - } - - cores := make([]zapcore.Core, 0, len(config.coreConfigs)) - for _, coreConfig := range config.coreConfigs { - cores = append(cores, zapcore.NewCore(coreConfig.Enc, coreConfig.Ws, coreConfig.Lvl)) - } - - logger := zap.New( - zapcore.NewTee(cores[:]...), - config.zapOpts...) - - return &Logger{ - l: logger, - config: config, - } -} - -// GetExtraKeys get extraKeys from logger config -func (l *Logger) GetExtraKeys() []ExtraKey { - return l.config.extraKeys -} - -// PutExtraKeys add extraKeys after init -func (l *Logger) PutExtraKeys(keys ...ExtraKey) { - for _, k := range keys { - if !InArray(k, l.config.extraKeys) { - l.config.extraKeys = append(l.config.extraKeys, k) - } - } -} - -func (l *Logger) Log(level hlog.Level, kvs ...interface{}) { - sugar := l.l.Sugar() - switch level { - case hlog.LevelTrace, hlog.LevelDebug: - sugar.Debug(kvs...) - case hlog.LevelInfo: - sugar.Info(kvs...) - case hlog.LevelNotice, hlog.LevelWarn: - sugar.Warn(kvs...) - case hlog.LevelError: - sugar.Error(kvs...) - case hlog.LevelFatal: - sugar.Fatal(kvs...) - default: - sugar.Warn(kvs...) - } -} - -func (l *Logger) Logf(level hlog.Level, format string, kvs ...interface{}) { - logger := l.l.Sugar().With() - switch level { - case hlog.LevelTrace, hlog.LevelDebug: - logger.Debugf(format, kvs...) - case hlog.LevelInfo: - logger.Infof(format, kvs...) - case hlog.LevelNotice, hlog.LevelWarn: - logger.Warnf(format, kvs...) - case hlog.LevelError: - logger.Errorf(format, kvs...) - case hlog.LevelFatal: - logger.Fatalf(format, kvs...) - default: - logger.Warnf(format, kvs...) - } -} - -func (l *Logger) CtxLogf(level hlog.Level, ctx context.Context, format string, kvs ...interface{}) { - zLevel := hLevelToZapLevel(level) - if !l.config.coreConfigs[0].Lvl.Enabled(zLevel) { - return - } - zapLogger := l.l - if len(l.config.extraKeys) > 0 { - for _, k := range l.config.extraKeys { - if l.config.extraKeyAsStr { - v := ctx.Value(string(k)) - if v != nil { - zapLogger = zapLogger.With(zap.Any(string(k), v)) - } - } else { - v := ctx.Value(k) - if v != nil { - zapLogger = zapLogger.With(zap.Any(string(k), v)) - } - } - } - } - log := zapLogger.Sugar() - switch level { - case hlog.LevelDebug, hlog.LevelTrace: - log.Debugf(format, kvs...) - case hlog.LevelInfo: - log.Infof(format, kvs...) - case hlog.LevelNotice, hlog.LevelWarn: - log.Warnf(format, kvs...) - case hlog.LevelError: - log.Errorf(format, kvs...) - case hlog.LevelFatal: - log.Fatalf(format, kvs...) - default: - log.Warnf(format, kvs...) - } -} - -func (l *Logger) Trace(v ...interface{}) { - l.Log(hlog.LevelTrace, v...) -} - -func (l *Logger) Debug(v ...interface{}) { - l.Log(hlog.LevelDebug, v...) -} - -func (l *Logger) Info(v ...interface{}) { - l.Log(hlog.LevelInfo, v...) -} - -func (l *Logger) Notice(v ...interface{}) { - l.Log(hlog.LevelNotice, v...) -} - -func (l *Logger) Warn(v ...interface{}) { - l.Log(hlog.LevelWarn, v...) -} - -func (l *Logger) Error(v ...interface{}) { - l.Log(hlog.LevelError, v...) -} - -func (l *Logger) Fatal(v ...interface{}) { - l.Log(hlog.LevelFatal, v...) -} - -func (l *Logger) Tracef(format string, v ...interface{}) { - l.Logf(hlog.LevelTrace, format, v...) -} - -func (l *Logger) Debugf(format string, v ...interface{}) { - l.Logf(hlog.LevelDebug, format, v...) -} - -func (l *Logger) Infof(format string, v ...interface{}) { - l.Logf(hlog.LevelInfo, format, v...) -} - -func (l *Logger) Noticef(format string, v ...interface{}) { - l.Logf(hlog.LevelWarn, format, v...) -} - -func (l *Logger) Warnf(format string, v ...interface{}) { - l.Logf(hlog.LevelWarn, format, v...) -} - -func (l *Logger) Errorf(format string, v ...interface{}) { - l.Logf(hlog.LevelError, format, v...) -} - -func (l *Logger) Fatalf(format string, v ...interface{}) { - l.Logf(hlog.LevelFatal, format, v...) -} - -func (l *Logger) CtxTracef(ctx context.Context, format string, v ...interface{}) { - l.CtxLogf(hlog.LevelDebug, ctx, format, v...) -} - -func (l *Logger) CtxDebugf(ctx context.Context, format string, v ...interface{}) { - l.CtxLogf(hlog.LevelDebug, ctx, format, v...) -} - -func (l *Logger) CtxInfof(ctx context.Context, format string, v ...interface{}) { - l.CtxLogf(hlog.LevelInfo, ctx, format, v...) -} - -func (l *Logger) CtxNoticef(ctx context.Context, format string, v ...interface{}) { - l.CtxLogf(hlog.LevelWarn, ctx, format, v...) -} - -func (l *Logger) CtxWarnf(ctx context.Context, format string, v ...interface{}) { - l.CtxLogf(hlog.LevelWarn, ctx, format, v...) -} - -func (l *Logger) CtxErrorf(ctx context.Context, format string, v ...interface{}) { - l.CtxLogf(hlog.LevelError, ctx, format, v...) -} - -func (l *Logger) CtxFatalf(ctx context.Context, format string, v ...interface{}) { - l.CtxLogf(hlog.LevelFatal, ctx, format, v...) -} - -func (l *Logger) SetLevel(level hlog.Level) { - lvl := hLevelToZapLevel(level) - - l.config.coreConfigs[0].Lvl = lvl - - cores := make([]zapcore.Core, 0, len(l.config.coreConfigs)) - for _, coreConfig := range l.config.coreConfigs { - cores = append(cores, zapcore.NewCore(coreConfig.Enc, coreConfig.Ws, coreConfig.Lvl)) - } - - logger := zap.New( - zapcore.NewTee(cores[:]...), - l.config.zapOpts...) - - l.l = logger -} - -func (l *Logger) SetOutput(writer io.Writer) { - l.config.coreConfigs[0].Ws = zapcore.AddSync(writer) - - cores := make([]zapcore.Core, 0, len(l.config.coreConfigs)) - for _, coreConfig := range l.config.coreConfigs { - cores = append(cores, zapcore.NewCore(coreConfig.Enc, coreConfig.Ws, coreConfig.Lvl)) - } - - logger := zap.New( - zapcore.NewTee(cores[:]...), - l.config.zapOpts...) - - l.l = logger -} - -// Logger is used to return an instance of *zap.Logger for custom fields, etc. -func (l *Logger) Logger() *zap.Logger { - return l.l -} - -func (l *Logger) Sync() { - _ = l.l.Sync() + return cwzap.NewLogger(opts...) } diff --git a/zap/option.go b/zap/option.go index dba64bf..cf8d540 100644 --- a/zap/option.go +++ b/zap/option.go @@ -15,106 +15,46 @@ package zap import ( - "os" + cwzap "github.com/cloudwego-contrib/cwgo-pkg/log/logging/zap" "go.uber.org/zap" "go.uber.org/zap/zapcore" ) -type Option interface { - apply(cfg *config) -} - -type ExtraKey string - -type option func(cfg *config) - -func (fn option) apply(cfg *config) { - fn(cfg) -} - -type CoreConfig struct { - Enc zapcore.Encoder - Ws zapcore.WriteSyncer - Lvl zapcore.LevelEnabler -} - -type config struct { - extraKeys []ExtraKey - coreConfigs []CoreConfig - zapOpts []zap.Option - extraKeyAsStr bool -} +type Option = cwzap.Option -// defaultCoreConfig default zapcore config: json encoder, atomic level, stdout write syncer -func defaultCoreConfig() *CoreConfig { - // default log encoder - enc := zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig()) - // default log level - lvl := zap.NewAtomicLevelAt(zap.InfoLevel) - // default write syncer stdout - ws := zapcore.AddSync(os.Stdout) +type ExtraKey = cwzap.ExtraKey - return &CoreConfig{ - Enc: enc, - Ws: ws, - Lvl: lvl, - } -} - -// defaultConfig default config -func defaultConfig() *config { - return &config{ - coreConfigs: []CoreConfig{*defaultCoreConfig()}, - zapOpts: []zap.Option{}, - extraKeyAsStr: false, - } -} +type CoreConfig = cwzap.CoreConfig // WithCoreEnc zapcore encoder func WithCoreEnc(enc zapcore.Encoder) Option { - return option(func(cfg *config) { - cfg.coreConfigs[0].Enc = enc - }) + return cwzap.WithCoreEnc(enc) } // WithCoreWs zapcore write syncer func WithCoreWs(ws zapcore.WriteSyncer) Option { - return option(func(cfg *config) { - cfg.coreConfigs[0].Ws = ws - }) + return cwzap.WithCoreWs(ws) } // WithCoreLevel zapcore log level func WithCoreLevel(lvl zap.AtomicLevel) Option { - return option(func(cfg *config) { - cfg.coreConfigs[0].Lvl = lvl - }) + return cwzap.WithCoreLevel(lvl) } // WithCores zapcore func WithCores(coreConfigs ...CoreConfig) Option { - return option(func(cfg *config) { - cfg.coreConfigs = coreConfigs - }) + return cwzap.WithCores(coreConfigs...) } // WithZapOptions add origin zap option func WithZapOptions(opts ...zap.Option) Option { - return option(func(cfg *config) { - cfg.zapOpts = append(cfg.zapOpts, opts...) - }) + return cwzap.WithZapOptions(opts...) } // WithExtraKeys allow you log extra values from context func WithExtraKeys(keys []ExtraKey) Option { - return option(func(cfg *config) { - for _, k := range keys { - if !InArray(k, cfg.extraKeys) { - cfg.extraKeys = append(cfg.extraKeys, k) - } - } - }) + return cwzap.WithExtraKeys(keys) } // WithExtraKeyAsStr convert extraKey to a string type when retrieving value from context @@ -123,7 +63,5 @@ func WithExtraKeys(keys []ExtraKey) Option { // For more information, refer to the documentation at // `https://pkg.go.dev/context#WithValue` func WithExtraKeyAsStr() Option { - return option(func(cfg *config) { - cfg.extraKeyAsStr = true - }) + return cwzap.WithExtraKeyAsStr() } diff --git a/zap/utils.go b/zap/utils.go index 282295e..d93fb94 100644 --- a/zap/utils.go +++ b/zap/utils.go @@ -14,12 +14,6 @@ package zap -import ( - "github.com/cloudwego/hertz/pkg/common/hlog" - "go.uber.org/zap" - "go.uber.org/zap/zapcore" -) - // InArray check if a string in a slice func InArray(key ExtraKey, arr []ExtraKey) bool { for _, k := range arr { @@ -29,22 +23,3 @@ func InArray(key ExtraKey, arr []ExtraKey) bool { } return false } - -func hLevelToZapLevel(level hlog.Level) zapcore.Level { - var lvl zapcore.Level - switch level { - case hlog.LevelTrace, hlog.LevelDebug: - lvl = zap.DebugLevel - case hlog.LevelInfo: - lvl = zap.InfoLevel - case hlog.LevelWarn, hlog.LevelNotice: - lvl = zap.WarnLevel - case hlog.LevelError: - lvl = zap.ErrorLevel - case hlog.LevelFatal: - lvl = zap.FatalLevel - default: - lvl = zap.WarnLevel - } - return lvl -} diff --git a/zerolog/go.mod b/zerolog/go.mod index e9793c3..0530582 100644 --- a/zerolog/go.mod +++ b/zerolog/go.mod @@ -1,28 +1,26 @@ module github.com/hertz-contrib/logger/zerolog -go 1.19 +go 1.21 require ( - github.com/cloudwego/hertz v0.4.0 + github.com/cloudwego-contrib/cwgo-pkg/log/logging/zerolog v0.0.0-20241014044734-80a98dbe0b6a + github.com/cloudwego/hertz v0.9.2 github.com/rs/zerolog v1.30.0 - github.com/stretchr/testify v1.8.4 + github.com/stretchr/testify v1.9.0 ) require ( - github.com/bytedance/sonic v1.10.1 // indirect + github.com/bytedance/sonic v1.11.2 // indirect github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d // indirect - github.com/chenzhuoyu/iasm v0.9.0 // indirect - github.com/davecgh/go-spew v1.1.1 // indirect + github.com/chenzhuoyu/iasm v0.9.1 // indirect + github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/klauspost/cpuid/v2 v2.2.5 // indirect - github.com/kr/pretty v0.3.0 // indirect + github.com/kr/text v0.2.0 // indirect github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-isatty v0.0.16 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect - github.com/rogpeppe/go-internal v1.8.0 // indirect - github.com/stretchr/objx v0.5.1 // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect golang.org/x/arch v0.5.0 // indirect - golang.org/x/sys v0.12.0 // indirect - gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect + golang.org/x/sys v0.21.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/zerolog/go.sum b/zerolog/go.sum index 3f59c70..e1f0d8f 100644 --- a/zerolog/go.sum +++ b/zerolog/go.sum @@ -1,44 +1,45 @@ github.com/bytedance/go-tagexpr/v2 v2.9.2/go.mod h1:5qsx05dYOiUXOUgnQ7w3Oz8BYs2qtM/bJokdLb79wRM= github.com/bytedance/gopkg v0.0.0-20220413063733-65bf48ffb3a7/go.mod h1:2ZlV9BaUH4+NXIBF0aMdKKAnHTzqH+iMU4KUjAbL23Q= -github.com/bytedance/sonic v1.5.0 h1:XWdTi8bwPgxIML+eNV1IwNuTROK6EUrQ65ey8yd6fRQ= +github.com/bytedance/mockey v1.2.1/go.mod h1:+Jm/fzWZAuhEDrPXVjDf/jLM2BlLXJkwk94zf2JZ3X4= github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM= +github.com/bytedance/sonic v1.8.1/go.mod h1:i736AoUSYt75HyZLoJW9ERYxcy6eaN6h4BZXU064P/U= github.com/bytedance/sonic v1.10.0-rc/go.mod h1:ElCzW+ufi8qKqNW0FY314xriJhyJhuoJ3gFZdAHF7NM= -github.com/bytedance/sonic v1.10.1 h1:7a1wuFXL1cMy7a3f7/VFcEtriuXQnUBhtoVfOZiaysc= -github.com/bytedance/sonic v1.10.1/go.mod h1:iZcSUejdk5aukTND/Eu/ivjQuEL0Cu9/rf50Hi0u/g4= -github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06 h1:1sDoSuDPWzhkdzNVxCxtIaKiAe96ESVPv8coGwc1gZ4= +github.com/bytedance/sonic v1.11.2 h1:ywfwo0a/3j9HR8wsYGWsIWl2mvRsI950HyoxiBERw5A= +github.com/bytedance/sonic v1.11.2/go.mod h1:iZcSUejdk5aukTND/Eu/ivjQuEL0Cu9/rf50Hi0u/g4= github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY= github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk= github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d h1:77cEq6EriyTZ0g/qfRdp61a3Uu/AWrgIq2s0ClJV1g0= github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d/go.mod h1:8EPpVsBuRksnlj1mLy4AWzRNQYxauNi62uWcE3to6eA= -github.com/chenzhuoyu/iasm v0.9.0 h1:9fhXjVzq5hUy2gkhhgHl95zG2cEAhw9OSGs8toWWAwo= github.com/chenzhuoyu/iasm v0.9.0/go.mod h1:Xjy2NpN3h7aUqeqM+woSuuvxmIe6+DDsiNLIrkAmYog= -github.com/cloudwego/hertz v0.4.0 h1:qigNIzhOpydsEgenCCHoLObQgkumg7aPR7MvvkbeVuo= -github.com/cloudwego/hertz v0.4.0/go.mod h1:QSD2254yaf43BIy4isrlfKR42R3uFAT+6G5CpeROOJs= -github.com/cloudwego/netpoll v0.2.6/go.mod h1:1T2WVuQ+MQw6h6DpE45MohSvDTKdy2DlzCx2KsnPI4E= +github.com/chenzhuoyu/iasm v0.9.1 h1:tUHQJXo3NhBqw6s33wkGn9SP3bvrWLdlVIJ3hQBL7P0= +github.com/chenzhuoyu/iasm v0.9.1/go.mod h1:Xjy2NpN3h7aUqeqM+woSuuvxmIe6+DDsiNLIrkAmYog= +github.com/cloudwego-contrib/cwgo-pkg/log/logging/zerolog v0.0.0-20241014044734-80a98dbe0b6a h1:BnXZJacWw/kkDja8iNO4H+IO8y6NRfK5wMOE8rdjgFc= +github.com/cloudwego-contrib/cwgo-pkg/log/logging/zerolog v0.0.0-20241014044734-80a98dbe0b6a/go.mod h1:PgM5tUxUjuQ5nK7DqFnEXUctO6nr321KlrvOhN1fGi4= +github.com/cloudwego/hertz v0.9.2 h1:VbqddZ5RuvcgxzfxvXcmTiRisGYoo0+WnHGeDJKhjqI= +github.com/cloudwego/hertz v0.9.2/go.mod h1:cs8dH6unM4oaJ5k9m6pqbgLBPqakGWMG0+cthsxitsg= +github.com/cloudwego/netpoll v0.6.0/go.mod h1:xVefXptcyheopwNDZjDPcfU6kIjZXZ4nY550k1yH9eQ= github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/fsnotify/fsnotify v1.5.4/go.mod h1:OVB6XrOHzAwXMpEM7uPOzcehqUV2UqJxmVXmkdnm1bU= github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/henrylee2cn/ameda v1.4.8/go.mod h1:liZulR8DgHxdK+MEwvZIylGnmcjzQ6N6f2PlWe7nEO4= github.com/henrylee2cn/ameda v1.4.10/go.mod h1:liZulR8DgHxdK+MEwvZIylGnmcjzQ6N6f2PlWe7nEO4= github.com/henrylee2cn/goutil v0.0.0-20210127050712-89660552f6f8/go.mod h1:Nhe/DM3671a5udlv2AdV2ni/MZzgfv2qrPL5nIi3EGQ= -github.com/klauspost/cpuid/v2 v2.0.9 h1:lgaqFMSdTdQYdZ04uHyN2d/eKdOMyi2YLSvlQIBFYa4= +github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= github.com/klauspost/cpuid/v2 v2.2.5 h1:0E5MSMDEoAulmXNFquVs//DdoomxaoTY1kUhbc/qbZg= github.com/klauspost/cpuid/v2 v2.2.5/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws= github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M= -github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= -github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= -github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0= -github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= -github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= -github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4= @@ -48,64 +49,59 @@ github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27k github.com/mattn/go-isatty v0.0.16 h1:bq3VjFmv/sOjHtdEhmkEV4x1AJtvUvOJ2PFAZ5+peKQ= github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= github.com/nyaruka/phonenumbers v1.0.55/go.mod h1:sDaTZ/KPX5f8qyV9qN+hIm+4ZBARJrupC6LuhshJq1U= -github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= -github.com/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUAtL9R8= -github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE= +github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= +github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog= github.com/rs/xid v1.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= github.com/rs/zerolog v1.30.0 h1:SymVODrcRsaRaSInD9yQtKbtWqwsfoPcRff/oRXLj4c= github.com/rs/zerolog v1.30.0/go.mod h1:/tk+P47gFdPXq4QYjvCmT5/Gsug2nagsFWBWhAiSi1w= +github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= +github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= -github.com/stretchr/objx v0.5.1 h1:4VhoImhV/Bm0ToFkXFi8hXNXwpDRZ/ynw3amt82mzq0= -github.com/stretchr/objx v0.5.1/go.mod h1:/iHQpkQwBD6DLUmQ4pE+s1TXdob1mORJ4/UFdrifcy0= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= -github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= -github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= -github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= -github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= +github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/tidwall/gjson v1.9.3/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= -github.com/tidwall/gjson v1.13.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= +github.com/tidwall/gjson v1.14.4/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM= github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= -golang.org/x/arch v0.0.0-20210923205945-b76863e36670 h1:18EFjUmQOcUvxNYSkA6jO9VAiXCnxFY6NyDX0bHDmkU= +golang.org/x/arch v0.0.0-20201008161808-52c3e6f60cff/go.mod h1:flIaEI6LNU6xOCD5PaJvn9wGP0agmIOqjrtsKGRguv4= golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= golang.org/x/arch v0.5.0 h1:jpGode6huXQxcskEIpOCvrU+tzo81b6+oFLUYXWtH/Y= golang.org/x/arch v0.5.0/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220110181412-a018aaa089fe/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.1.0 h1:kunALQeHf1/185U1i0GOB/fy1IPRDDpuoOOqRReG57U= -golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.12.0 h1:CM0HF96J0hcLAwsHPJZjfdNzs0gftsLfgKt57wWHJ0o= -golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.21.0 h1:rF+pYz3DAGSQAxAu1CbC7catZg4ebC4UIeIhKxBZvws= +golang.org/x/sys v0.21.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= -gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= -gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50= diff --git a/zerolog/logger.go b/zerolog/logger.go index dcf2c8a..bd264d5 100644 --- a/zerolog/logger.go +++ b/zerolog/logger.go @@ -17,12 +17,9 @@ package zerolog import ( - "context" - "errors" - "fmt" "io" - "os" + cwzerolog "github.com/cloudwego-contrib/cwgo-pkg/log/logging/zerolog" "github.com/cloudwego/hertz/pkg/common/hlog" "github.com/rs/zerolog" ) @@ -30,248 +27,28 @@ import ( var _ hlog.FullLogger = (*Logger)(nil) // Logger is a wrapper around `zerolog.Logger` that provides an implementation of `hlog.FullLogger` interface -type Logger struct { - log zerolog.Logger - out io.Writer - level zerolog.Level - options []Opt -} +type Logger = cwzerolog.Logger // ConsoleWriter parses the JSON input and writes it in an // (optionally) colorized, human-friendly format to Out. -type ConsoleWriter = zerolog.ConsoleWriter +type ConsoleWriter = cwzerolog.ConsoleWriter // MultiLevelWriter may be used to send the log message to multiple outputs. func MultiLevelWriter(writers ...io.Writer) zerolog.LevelWriter { - return zerolog.MultiLevelWriter(writers...) + return cwzerolog.MultiLevelWriter(writers...) } // New returns a new Logger instance func New(options ...Opt) *Logger { - return newLogger(zerolog.New(os.Stdout), options) + return cwzerolog.New(options...) } // From returns a new Logger instance using an existing logger func From(log zerolog.Logger, options ...Opt) *Logger { - return newLogger(log, options) + return cwzerolog.From(log, options...) } // GetLogger returns the default logger instance func GetLogger() (Logger, error) { - defaultLogger := hlog.DefaultLogger() - - if logger, ok := defaultLogger.(*Logger); ok { - return *logger, nil - } - - return Logger{}, errors.New("hlog.DefaultLogger is not a zerolog logger") -} - -// SetLevel setting logging level for logger -func (l *Logger) SetLevel(level hlog.Level) { - lvl := matchHlogLevel(level) - l.level = lvl - l.log = l.log.Level(lvl) -} - -// SetOutput setting output for logger -func (l *Logger) SetOutput(writer io.Writer) { - l.out = writer - l.log = l.log.Output(writer) -} - -// WithContext returns context with logger attached -func (l *Logger) WithContext(ctx context.Context) context.Context { - return l.log.WithContext(ctx) -} - -// WithField appends a field to the logger -func (l *Logger) WithField(key string, value interface{}) Logger { - l.log = l.log.With().Interface(key, value).Logger() - return *l -} - -// Unwrap returns the underlying zerolog logger -func (l *Logger) Unwrap() zerolog.Logger { - return l.log -} - -// Log log using zerolog logger with specified level -func (l *Logger) Log(level hlog.Level, kvs ...interface{}) { - switch level { - case hlog.LevelTrace, hlog.LevelDebug: - l.log.Debug().Msg(fmt.Sprint(kvs...)) - case hlog.LevelInfo: - l.log.Info().Msg(fmt.Sprint(kvs...)) - case hlog.LevelNotice, hlog.LevelWarn: - l.log.Warn().Msg(fmt.Sprint(kvs...)) - case hlog.LevelError: - l.log.Error().Msg(fmt.Sprint(kvs...)) - case hlog.LevelFatal: - l.log.Fatal().Msg(fmt.Sprint(kvs...)) - default: - l.log.Warn().Msg(fmt.Sprint(kvs...)) - } -} - -// Logf log using zerolog logger with specified level and formatting -func (l *Logger) Logf(level hlog.Level, format string, kvs ...interface{}) { - switch level { - case hlog.LevelTrace, hlog.LevelDebug: - l.log.Debug().Msg(fmt.Sprintf(format, kvs...)) - case hlog.LevelInfo: - l.log.Info().Msg(fmt.Sprintf(format, kvs...)) - case hlog.LevelNotice, hlog.LevelWarn: - l.log.Warn().Msg(fmt.Sprintf(format, kvs...)) - case hlog.LevelError: - l.log.Error().Msg(fmt.Sprintf(format, kvs...)) - case hlog.LevelFatal: - l.log.Fatal().Msg(fmt.Sprintf(format, kvs...)) - default: - l.log.Warn().Msg(fmt.Sprintf(format, kvs...)) - } -} - -// CtxLogf log with logger associated with context. -// If no logger is associated, DefaultContextLogger is used, unless DefaultContextLogger is nil, in which case a disabled logger is used. -func (l *Logger) CtxLogf(level hlog.Level, ctx context.Context, format string, kvs ...interface{}) { - logger := l.Unwrap() - // todo add hook - switch level { - case hlog.LevelTrace, hlog.LevelDebug: - logger.Debug().Ctx(ctx).Msg(fmt.Sprintf(format, kvs...)) - case hlog.LevelInfo: - logger.Info().Ctx(ctx).Msg(fmt.Sprintf(format, kvs...)) - case hlog.LevelNotice, hlog.LevelWarn: - logger.Warn().Ctx(ctx).Msg(fmt.Sprintf(format, kvs...)) - case hlog.LevelError: - logger.Error().Ctx(ctx).Msg(fmt.Sprintf(format, kvs...)) - case hlog.LevelFatal: - logger.Fatal().Ctx(ctx).Msg(fmt.Sprintf(format, kvs...)) - default: - logger.Warn().Ctx(ctx).Msg(fmt.Sprintf(format, kvs...)) - } -} - -// Trace logs a message at trace level. -func (l *Logger) Trace(v ...interface{}) { - l.Log(hlog.LevelTrace, v...) -} - -// Debug logs a message at debug level. -func (l *Logger) Debug(v ...interface{}) { - l.Log(hlog.LevelDebug, v...) -} - -// Info logs a message at info level. -func (l *Logger) Info(v ...interface{}) { - l.Log(hlog.LevelInfo, v...) -} - -// Notice logs a message at notice level. -func (l *Logger) Notice(v ...interface{}) { - l.Log(hlog.LevelNotice, v...) -} - -// Warn logs a message at warn level. -func (l *Logger) Warn(v ...interface{}) { - l.Log(hlog.LevelWarn, v...) -} - -// Error logs a message at error level. -func (l *Logger) Error(v ...interface{}) { - l.Log(hlog.LevelError, v...) -} - -// Fatal logs a message at fatal level. -func (l *Logger) Fatal(v ...interface{}) { - l.Log(hlog.LevelFatal, v...) -} - -// Tracef logs a formatted message at trace level. -func (l *Logger) Tracef(format string, v ...interface{}) { - l.Logf(hlog.LevelTrace, format, v...) -} - -// Debugf logs a formatted message at debug level. -func (l *Logger) Debugf(format string, v ...interface{}) { - l.Logf(hlog.LevelDebug, format, v...) -} - -// Infof logs a formatted message at info level. -func (l *Logger) Infof(format string, v ...interface{}) { - l.Logf(hlog.LevelInfo, format, v...) -} - -// Noticef logs a formatted message at notice level. -func (l *Logger) Noticef(format string, v ...interface{}) { - l.Logf(hlog.LevelWarn, format, v...) -} - -// Warnf logs a formatted message at warn level. -func (l *Logger) Warnf(format string, v ...interface{}) { - l.Logf(hlog.LevelWarn, format, v...) -} - -// Errorf logs a formatted message at error level. -func (l *Logger) Errorf(format string, v ...interface{}) { - l.Logf(hlog.LevelError, format, v...) -} - -// Fatalf logs a formatted message at fatal level. -func (l *Logger) Fatalf(format string, v ...interface{}) { - l.Logf(hlog.LevelError, format, v...) -} - -// CtxTracef logs a message at trace level with logger associated with context. -// If no logger is associated, DefaultContextLogger is used, unless DefaultContextLogger is nil, in which case a disabled logger is used. -func (l *Logger) CtxTracef(ctx context.Context, format string, v ...interface{}) { - l.CtxLogf(hlog.LevelTrace, ctx, format, v...) -} - -// CtxDebugf logs a message at debug level with logger associated with context. -// If no logger is associated, DefaultContextLogger is used, unless DefaultContextLogger is nil, in which case a disabled logger is used. -func (l *Logger) CtxDebugf(ctx context.Context, format string, v ...interface{}) { - l.CtxLogf(hlog.LevelDebug, ctx, format, v...) -} - -// CtxInfof logs a message at info level with logger associated with context. -// If no logger is associated, DefaultContextLogger is used, unless DefaultContextLogger is nil, in which case a disabled logger is used. -func (l *Logger) CtxInfof(ctx context.Context, format string, v ...interface{}) { - l.CtxLogf(hlog.LevelInfo, ctx, format, v...) -} - -// CtxNoticef logs a message at notice level with logger associated with context. -// If no logger is associated, DefaultContextLogger is used, unless DefaultContextLogger is nil, in which case a disabled logger is used. -func (l *Logger) CtxNoticef(ctx context.Context, format string, v ...interface{}) { - l.CtxLogf(hlog.LevelNotice, ctx, format, v...) -} - -// CtxWarnf logs a message at warn level with logger associated with context. -// If no logger is associated, DefaultContextLogger is used, unless DefaultContextLogger is nil, in which case a disabled logger is used. -func (l *Logger) CtxWarnf(ctx context.Context, format string, v ...interface{}) { - l.CtxLogf(hlog.LevelWarn, ctx, format, v...) -} - -// CtxErrorf logs a message at error level with logger associated with context. -// If no logger is associated, DefaultContextLogger is used, unless DefaultContextLogger is nil, in which case a disabled logger is used. -func (l *Logger) CtxErrorf(ctx context.Context, format string, v ...interface{}) { - l.CtxLogf(hlog.LevelError, ctx, format, v...) -} - -// CtxFatalf logs a message at fatal level with logger associated with context. -// If no logger is associated, DefaultContextLogger is used, unless DefaultContextLogger is nil, in which case a disabled logger is used. -func (l *Logger) CtxFatalf(ctx context.Context, format string, v ...interface{}) { - l.CtxLogf(hlog.LevelFatal, ctx, format, v...) -} - -func newLogger(log zerolog.Logger, options []Opt) *Logger { - opts := newOptions(log, options) - - return &Logger{ - log: opts.context.Logger(), - out: nil, - level: opts.level, - options: options, - } + return cwzerolog.GetLogger() } diff --git a/zerolog/logger_test.go b/zerolog/logger_test.go index 3e6597a..c5cd2a9 100644 --- a/zerolog/logger_test.go +++ b/zerolog/logger_test.go @@ -222,7 +222,7 @@ func TestCtxTracef(t *testing.T) { b := &bytes.Buffer{} l := New() l.SetOutput(b) - ctx := l.log.WithContext(context.Background()) + ctx := l.Unwrap().WithContext(context.Background()) l.CtxTracef(ctx, "foo%s", "bar") assert.Equal( @@ -238,7 +238,7 @@ func TestCtxDebugf(t *testing.T) { b := &bytes.Buffer{} l := New() l.SetOutput(b) - ctx := l.log.WithContext(context.Background()) + ctx := l.Unwrap().WithContext(context.Background()) l.CtxDebugf(ctx, "foo%s", "bar") assert.Equal( @@ -254,7 +254,7 @@ func TestCtxInfof(t *testing.T) { b := &bytes.Buffer{} l := New() l.SetOutput(b) - ctx := l.log.WithContext(context.Background()) + ctx := l.Unwrap().WithContext(context.Background()) l.CtxInfof(ctx, "foo%s", "bar") assert.Equal( @@ -270,7 +270,7 @@ func TestCtxNoticef(t *testing.T) { b := &bytes.Buffer{} l := New() l.SetOutput(b) - ctx := l.log.WithContext(context.Background()) + ctx := l.Unwrap().WithContext(context.Background()) l.CtxNoticef(ctx, "foo%s", "bar") assert.Equal( @@ -286,7 +286,7 @@ func TestCtxWarnf(t *testing.T) { b := &bytes.Buffer{} l := New() l.SetOutput(b) - ctx := l.log.WithContext(context.Background()) + ctx := l.Unwrap().WithContext(context.Background()) l.CtxWarnf(ctx, "foo%s", "bar") assert.Equal( @@ -302,7 +302,7 @@ func TestCtxErrorf(t *testing.T) { b := &bytes.Buffer{} l := New() l.SetOutput(b) - ctx := l.log.WithContext(context.Background()) + ctx := l.Unwrap().WithContext(context.Background()) l.CtxErrorf(ctx, "foo%s", "bar") assert.Equal( @@ -318,11 +318,11 @@ func TestSetLevel(t *testing.T) { l := New() l.SetLevel(hlog.LevelDebug) - assert.Equal(t, l.log.GetLevel(), zerolog.DebugLevel) + assert.Equal(t, l.Unwrap().GetLevel(), zerolog.DebugLevel) l.SetLevel(hlog.LevelDebug) - assert.Equal(t, l.log.GetLevel(), zerolog.DebugLevel) + assert.Equal(t, l.Unwrap().GetLevel(), zerolog.DebugLevel) l.SetLevel(hlog.LevelError) - assert.Equal(t, l.log.GetLevel(), zerolog.ErrorLevel) + assert.Equal(t, l.Unwrap().GetLevel(), zerolog.ErrorLevel) } diff --git a/zerolog/options.go b/zerolog/options.go index e95ed7d..0c01626 100644 --- a/zerolog/options.go +++ b/zerolog/options.go @@ -19,103 +19,66 @@ package zerolog import ( "io" + cwzerolog "github.com/cloudwego-contrib/cwgo-pkg/log/logging/zerolog" + "github.com/cloudwego/hertz/pkg/common/hlog" "github.com/rs/zerolog" ) type ( - Options struct { - context zerolog.Context - level zerolog.Level - } - - Opt func(opts *Options) + Opt = cwzerolog.Opt ) -func newOptions(log zerolog.Logger, options []Opt) *Options { - opts := &Options{ - context: log.With(), - level: log.GetLevel(), - } - - for _, set := range options { - set(opts) - } - - return opts -} - // WithOutput allows to specify the output of the logger. By default, it is set to os.Stdout. func WithOutput(out io.Writer) Opt { - return func(opts *Options) { - opts.context = opts.context.Logger().Output(out).With() - } + return cwzerolog.WithOutput(out) } // WithLevel allows to specify the level of the logger. By default, it is set to WarnLevel. func WithLevel(level hlog.Level) Opt { - lvl := matchHlogLevel(level) - return func(opts *Options) { - opts.context = opts.context.Logger().Level(lvl).With() - opts.level = lvl - } + // lvl := matchHlogLevel(level) + return cwzerolog.WithLevel(level) } // WithField adds a field to the logger's context func WithField(name string, value interface{}) Opt { - return func(opts *Options) { - opts.context = opts.context.Interface(name, value) - } + return cwzerolog.WithField(name, value) } // WithFields adds fields to the logger's context func WithFields(fields map[string]interface{}) Opt { - return func(opts *Options) { - opts.context = opts.context.Fields(fields) - } + return cwzerolog.WithFields(fields) } // WithTimestamp adds a timestamp field to the logger's context func WithTimestamp() Opt { - return func(opts *Options) { - opts.context = opts.context.Timestamp() - } + return cwzerolog.WithTimestamp() } // WithFormattedTimestamp adds a formatted timestamp field to the logger's context func WithFormattedTimestamp(format string) Opt { - zerolog.TimeFieldFormat = format - return func(opts *Options) { - opts.context = opts.context.Timestamp() - } + // zerolog.TimeFieldFormat = format + return cwzerolog.WithFormattedTimestamp(format) } // WithCaller adds a caller field to the logger's context func WithCaller() Opt { - return func(opts *Options) { - opts.context = opts.context.Caller() - } + return cwzerolog.WithCaller() } // WithCallerSkipFrameCount adds a caller field to the logger's context // The specified skipFrameCount int will override the global CallerSkipFrameCount for this context's respective logger. // If set to -1 the global CallerSkipFrameCount will be used. func WithCallerSkipFrameCount(skipFrameCount int) Opt { - return func(opts *Options) { - opts.context = opts.context.CallerWithSkipFrameCount(skipFrameCount) - } + return cwzerolog.WithCallerSkipFrameCount(skipFrameCount) } // WithHook adds a hook to the logger's context func WithHook(hook zerolog.Hook) Opt { - return func(opts *Options) { - opts.context = opts.context.Logger().Hook(hook).With() - } + return cwzerolog.WithHook(hook) } // WithHookFunc adds hook function to the logger's context func WithHookFunc(hook zerolog.HookFunc) Opt { - return func(opts *Options) { - opts.context = opts.context.Logger().Hook(hook).With() - } + return cwzerolog.WithHookFunc(hook) }