update zap/logrus hanler #1

Merged
andrey merged 5 commits from handler into master 3 years ago
  1. 34
      .drone.yml
  2. 14
      .golangci.yml
  3. 5
      entry/entry.go
  4. 1
      entry/pool.go
  5. 2
      field/field.go
  6. 4
      field/key.go
  7. 101
      field/value.go
  8. 18
      go.mod
  9. 93
      go.sum
  10. 90
      handler/logrus/logger.go
  11. 4
      handler/logrus/logger_test.go
  12. 14
      handler/otel/helpers.go
  13. 94
      handler/zap/logger.go
  14. 4
      handler/zap/logger_test.go
  15. 10
      level/level.go
  16. 27
      logger.go
  17. 27
      logger_example_logrus_test.go
  18. 10
      logger_example_test.go
  19. 7
      logger_example_trace_test.go
  20. 27
      logger_example_zap_test.go
  21. 6
      logger_test.go
  22. 25
      writter.go

34
.drone.yml

@ -3,7 +3,7 @@ name: default
steps: steps:
- name: test - name: test
image: golang:1.14.2 image: golang:1.17.1
volumes: volumes:
- name: deps - name: deps
path: /go/src/mod path: /go/src/mod
@ -11,40 +11,10 @@ steps:
- go test - go test
- name: golangci-lint - name: golangci-lint
image: golangci/golangci-lint:v1.29 image: golangci/golangci-lint:v1.42
commands: commands:
- golangci-lint run - golangci-lint run
- name: logrus golangci-lint
image: golangci/golangci-lint:v1.29
commands:
- cd logrus
- golangci-lint run
- name: logrus test
image: golang:1.14.2
volumes:
- name: deps
path: /go/src/mod
commands:
- cd logrus
- go test
- name: zap golangci-lint
image: golangci/golangci-lint:v1.29
commands:
- cd zap
- golangci-lint run
- name: zap test
image: golang:1.14.2
volumes:
- name: deps
path: /go/src/mod
commands:
- cd zap
- go test
volumes: volumes:
- name: deps - name: deps
temp: {} temp: {}

14
.golangci.yml

@ -9,18 +9,25 @@ linters-settings:
min-occurrences: 2 min-occurrences: 2
gocyclo: gocyclo:
min-complexity: 15 min-complexity: 15
golint:
min-confidence: 0
govet: govet:
check-shadowing: true check-shadowing: true
lll: lll:
line-length: 140 line-length: 140
maligned: fieldalignment:
suggest-new: true suggest-new: true
misspell: misspell:
locale: US locale: US
exhaustive: exhaustive:
default-signifies-exhaustive: true default-signifies-exhaustive: true
tagliatelle:
case:
use-field-name: true
rules:
json: snake
yaml: camel
xml: camel
bson: camel
avro: snake
linters: linters:
enable-all: true enable-all: true
@ -31,3 +38,4 @@ issues:
- path: _test\.go - path: _test\.go
linters: linters:
- gomnd - gomnd
- exhaustivestruct

5
entry/entry.go

@ -13,9 +13,9 @@ const (
type Option func(*Entry) type Option func(*Entry)
func WithCapacity(cap int) Option { func WithCapacity(c int) Option {
return func(e *Entry) { return func(e *Entry) {
e.fields = make(field.Fields, 0, cap+1) e.fields = make(field.Fields, 0, c+1)
} }
} }
@ -41,6 +41,7 @@ func New(opts ...Option) *Entry {
e := &Entry{ e := &Entry{
fields: make(field.Fields, 0, defaultCap+1), fields: make(field.Fields, 0, defaultCap+1),
level: level.Debug, level: level.Debug,
msg: "",
} }
for _, opt := range opts { for _, opt := range opts {

1
entry/pool.go

@ -9,6 +9,7 @@ var pool = sync.Pool{
}, },
} }
//nolint: forcetypeassert
func Get() *Entry { func Get() *Entry {
e := pool.Get().(*Entry) e := pool.Get().(*Entry)
e.Reset() e.Reset()

2
field/field.go

@ -255,7 +255,7 @@ type Field struct {
value Value value Value
} }
//nolint: gocyclo //nolint: gocyclo,cyclop
func (f Field) AddTo(enc Encoder) { func (f Field) AddTo(enc Encoder) {
key := string(f.key) key := string(f.key)

4
field/key.go

@ -6,7 +6,7 @@ import (
type Key string type Key string
//nolint: gocyclo, funlen //nolint: gocyclo,funlen,cyclop
func (k Key) Any(value interface{}) Field { func (k Key) Any(value interface{}) Field {
switch v := value.(type) { switch v := value.(type) {
case string: case string:
@ -122,6 +122,8 @@ func (k Key) Any(value interface{}) Field {
value: Value{ value: Value{
value: value, value: value,
vtype: TypeAny, vtype: TypeAny,
numeric: 0,
stringly: "",
}, },
} }
} }

101
field/value.go

@ -16,10 +16,15 @@ type Value struct {
} }
func (v Value) MarshalJSON() ([]byte, error) { func (v Value) MarshalJSON() ([]byte, error) {
return json.Marshal(v.AsInterface()) b, err := json.Marshal(v.AsInterface())
if err != nil {
return nil, fmt.Errorf("marshal err: %w", err)
}
return b, nil
} }
//nolint: gocyclo //nolint: gocyclo,gomnd,cyclop
func (v Value) String() string { func (v Value) String() string {
switch { switch {
case v.vtype.IsArray(), v.vtype.IsAny(): case v.vtype.IsArray(), v.vtype.IsAny():
@ -57,7 +62,7 @@ func (v Value) String() string {
return fmt.Sprintf("%+v", v.AsInterface()) return fmt.Sprintf("%+v", v.AsInterface())
} }
//nolint: gocyclo //nolint: gocyclo,cyclop
func (v Value) AsInterface() interface{} { func (v Value) AsInterface() interface{} {
switch { switch {
case v.vtype.IsArray(): case v.vtype.IsArray():
@ -288,13 +293,20 @@ func (v Value) asError() error {
} }
func nilValue(t Type) Value { func nilValue(t Type) Value {
return Value{vtype: t | TypeNil} return Value{
vtype: t | TypeNil,
value: nil,
numeric: 0,
stringly: "",
}
} }
func stringValue(v string) Value { func stringValue(v string) Value {
return Value{ return Value{
stringly: v, stringly: v,
vtype: TypeString, vtype: TypeString,
numeric: 0,
value: nil,
} }
} }
@ -302,6 +314,8 @@ func stringsValue(v []string) Value {
return Value{ return Value{
value: v, value: v,
vtype: TypeString | TypeArray, vtype: TypeString | TypeArray,
numeric: 0,
stringly: "",
} }
} }
@ -318,11 +332,16 @@ func boolValue(b bool) Value {
return Value{ return Value{
numeric: 1, numeric: 1,
vtype: TypeBool, vtype: TypeBool,
value: nil,
stringly: "",
} }
} }
return Value{ return Value{
vtype: TypeBool, vtype: TypeBool,
value: nil,
numeric: 0,
stringly: "",
} }
} }
@ -330,6 +349,8 @@ func boolsValue(b []bool) Value {
return Value{ return Value{
value: b, value: b,
vtype: TypeBool | TypeArray, vtype: TypeBool | TypeArray,
numeric: 0,
stringly: "",
} }
} }
@ -345,6 +366,8 @@ func intValue(i int) Value {
return Value{ return Value{
vtype: TypeInt, vtype: TypeInt,
numeric: uint64(i), numeric: uint64(i),
value: nil,
stringly: "",
} }
} }
@ -352,6 +375,8 @@ func intsValue(i []int) Value {
return Value{ return Value{
value: i, value: i,
vtype: TypeInt | TypeArray, vtype: TypeInt | TypeArray,
numeric: 0,
stringly: "",
} }
} }
@ -367,6 +392,8 @@ func int8Value(i int8) Value {
return Value{ return Value{
vtype: TypeInt8, vtype: TypeInt8,
numeric: uint64(i), numeric: uint64(i),
value: nil,
stringly: "",
} }
} }
@ -374,6 +401,8 @@ func int8sValue(i []int8) Value {
return Value{ return Value{
value: i, value: i,
vtype: TypeInt8 | TypeArray, vtype: TypeInt8 | TypeArray,
numeric: 0,
stringly: "",
} }
} }
@ -389,6 +418,8 @@ func int16Value(i int16) Value {
return Value{ return Value{
vtype: TypeInt16, vtype: TypeInt16,
numeric: uint64(i), numeric: uint64(i),
value: 0,
stringly: "",
} }
} }
@ -396,6 +427,8 @@ func int16sValue(i []int16) Value {
return Value{ return Value{
value: i, value: i,
vtype: TypeInt16 | TypeArray, vtype: TypeInt16 | TypeArray,
numeric: 0,
stringly: "",
} }
} }
@ -411,6 +444,8 @@ func int32Value(i int32) Value {
return Value{ return Value{
vtype: TypeInt32, vtype: TypeInt32,
numeric: uint64(i), numeric: uint64(i),
value: nil,
stringly: "",
} }
} }
@ -418,6 +453,8 @@ func int32sValue(i []int32) Value {
return Value{ return Value{
value: i, value: i,
vtype: TypeInt32 | TypeArray, vtype: TypeInt32 | TypeArray,
numeric: 0,
stringly: "",
} }
} }
@ -433,6 +470,8 @@ func int64Value(i int64) Value {
return Value{ return Value{
vtype: TypeInt64, vtype: TypeInt64,
numeric: uint64(i), numeric: uint64(i),
value: nil,
stringly: "",
} }
} }
@ -440,6 +479,8 @@ func int64sValue(i []int64) Value {
return Value{ return Value{
value: i, value: i,
vtype: TypeInt64 | TypeArray, vtype: TypeInt64 | TypeArray,
numeric: 0,
stringly: "",
} }
} }
@ -455,6 +496,8 @@ func uintValue(i uint) Value {
return Value{ return Value{
vtype: TypeUint, vtype: TypeUint,
numeric: uint64(i), numeric: uint64(i),
value: nil,
stringly: "",
} }
} }
@ -462,6 +505,8 @@ func uintsValue(i []uint) Value {
return Value{ return Value{
value: i, value: i,
vtype: TypeUint | TypeArray, vtype: TypeUint | TypeArray,
numeric: 0,
stringly: "",
} }
} }
@ -477,6 +522,8 @@ func uint8Value(i uint8) Value {
return Value{ return Value{
vtype: TypeUint8, vtype: TypeUint8,
numeric: uint64(i), numeric: uint64(i),
value: nil,
stringly: "",
} }
} }
@ -484,6 +531,8 @@ func uint8sValue(i []uint8) Value {
return Value{ return Value{
value: i, value: i,
vtype: TypeUint8 | TypeArray, vtype: TypeUint8 | TypeArray,
numeric: 0,
stringly: "",
} }
} }
@ -499,6 +548,8 @@ func uint16Value(i uint16) Value {
return Value{ return Value{
vtype: TypeUint16, vtype: TypeUint16,
numeric: uint64(i), numeric: uint64(i),
value: nil,
stringly: "",
} }
} }
@ -506,6 +557,8 @@ func uint16sValue(i []uint16) Value {
return Value{ return Value{
value: i, value: i,
vtype: TypeUint16 | TypeArray, vtype: TypeUint16 | TypeArray,
numeric: 0,
stringly: "",
} }
} }
@ -521,6 +574,8 @@ func uint32Value(i uint32) Value {
return Value{ return Value{
vtype: TypeUint32, vtype: TypeUint32,
numeric: uint64(i), numeric: uint64(i),
value: nil,
stringly: "",
} }
} }
@ -528,6 +583,8 @@ func uint32sValue(i []uint32) Value {
return Value{ return Value{
value: i, value: i,
vtype: TypeUint32 | TypeArray, vtype: TypeUint32 | TypeArray,
numeric: 0,
stringly: "",
} }
} }
@ -543,6 +600,8 @@ func uint64Value(i uint64) Value {
return Value{ return Value{
vtype: TypeUint64, vtype: TypeUint64,
numeric: i, numeric: i,
value: nil,
stringly: "",
} }
} }
@ -550,6 +609,8 @@ func uint64sValue(i []uint64) Value {
return Value{ return Value{
value: i, value: i,
vtype: TypeUint64 | TypeArray, vtype: TypeUint64 | TypeArray,
numeric: 0,
stringly: "",
} }
} }
@ -565,6 +626,8 @@ func float32Value(i float32) Value {
return Value{ return Value{
vtype: TypeFloat32, vtype: TypeFloat32,
numeric: uint64(math.Float32bits(i)), numeric: uint64(math.Float32bits(i)),
value: nil,
stringly: "",
} }
} }
@ -572,6 +635,8 @@ func float32sValue(i []float32) Value {
return Value{ return Value{
value: i, value: i,
vtype: TypeFloat32 | TypeArray, vtype: TypeFloat32 | TypeArray,
numeric: 0,
stringly: "",
} }
} }
@ -587,6 +652,8 @@ func float64Value(i float64) Value {
return Value{ return Value{
vtype: TypeFloat64, vtype: TypeFloat64,
numeric: math.Float64bits(i), numeric: math.Float64bits(i),
value: nil,
stringly: "",
} }
} }
@ -594,6 +661,8 @@ func float64sValue(i []float64) Value {
return Value{ return Value{
value: i, value: i,
vtype: TypeFloat64 | TypeArray, vtype: TypeFloat64 | TypeArray,
numeric: 0,
stringly: "",
} }
} }
@ -609,6 +678,8 @@ func complex64Value(in complex64) Value {
return Value{ return Value{
vtype: TypeComplex64, vtype: TypeComplex64,
value: in, value: in,
numeric: 0,
stringly: "",
} }
} }
@ -616,6 +687,8 @@ func complex64sValue(in []complex64) Value {
return Value{ return Value{
vtype: TypeComplex64 | TypeArray, vtype: TypeComplex64 | TypeArray,
value: in, value: in,
numeric: 0,
stringly: "",
} }
} }
@ -631,6 +704,8 @@ func complex128Value(in complex128) Value {
return Value{ return Value{
vtype: TypeComplex64, vtype: TypeComplex64,
value: in, value: in,
numeric: 0,
stringly: "",
} }
} }
@ -638,6 +713,8 @@ func complex128sValue(in []complex128) Value {
return Value{ return Value{
vtype: TypeComplex128 | TypeArray, vtype: TypeComplex128 | TypeArray,
value: in, value: in,
numeric: 0,
stringly: "",
} }
} }
@ -652,6 +729,8 @@ func complex128pValue(in *complex128) Value {
func uintptrValue(in uintptr) Value { func uintptrValue(in uintptr) Value {
return Value{ return Value{
vtype: TypeUintptr, vtype: TypeUintptr,
numeric: 0,
stringly: "",
value: in, value: in,
} }
} }
@ -660,6 +739,8 @@ func uintptrsValue(in []uintptr) Value {
return Value{ return Value{
vtype: TypeUintptr | TypeArray, vtype: TypeUintptr | TypeArray,
value: in, value: in,
numeric: 0,
stringly: "",
} }
} }
@ -675,6 +756,8 @@ func bytesValue(in []byte) Value {
return Value{ return Value{
vtype: TypeBinary, vtype: TypeBinary,
value: in, value: in,
numeric: 0,
stringly: "",
} }
} }
@ -682,6 +765,8 @@ func durationValue(in time.Duration) Value {
return Value{ return Value{
vtype: TypeDuration, vtype: TypeDuration,
value: in, value: in,
numeric: 0,
stringly: "",
} }
} }
@ -689,6 +774,8 @@ func durationsValue(in []time.Duration) Value {
return Value{ return Value{
vtype: TypeDuration | TypeArray, vtype: TypeDuration | TypeArray,
value: in, value: in,
numeric: 0,
stringly: "",
} }
} }
@ -717,6 +804,7 @@ func formatTimeValue(format string, in time.Time) Value {
vtype: TypeTime, vtype: TypeTime,
value: in, value: in,
stringly: format, stringly: format,
numeric: 0,
} }
} }
@ -725,6 +813,7 @@ func formatTimesValue(format string, in []time.Time) Value {
vtype: TypeTime | TypeArray, vtype: TypeTime | TypeArray,
value: in, value: in,
stringly: format, stringly: format,
numeric: 0,
} }
} }
@ -741,6 +830,8 @@ func errorValue(in error) Value {
return Value{ return Value{
vtype: TypeError, vtype: TypeError,
value: in, value: in,
numeric: 0,
stringly: "",
} }
} }
@ -751,5 +842,7 @@ func errorsValue(in []error) Value {
return Value{ return Value{
vtype: TypeError | TypeArray, vtype: TypeError | TypeArray,
value: in, value: in,
numeric: 0,
stringly: "",
} }
} }

18
go.mod

@ -1,10 +1,18 @@
module gitoa.ru/go-4devs/log module gitoa.ru/go-4devs/log
go 1.15 go 1.17
require ( require (
github.com/sirupsen/logrus v1.7.0 github.com/sirupsen/logrus v1.8.1
go.opentelemetry.io/otel v0.13.0 go.opentelemetry.io/otel v0.20.0
go.opentelemetry.io/otel/sdk v0.13.0 go.opentelemetry.io/otel/sdk v0.20.0
go.uber.org/zap v1.16.0 go.opentelemetry.io/otel/trace v0.20.0
go.uber.org/zap v1.19.1
)
require (
go.opentelemetry.io/otel/metric v0.20.0 // indirect
go.uber.org/atomic v1.7.0 // indirect
go.uber.org/multierr v1.6.0 // indirect
golang.org/x/sys v0.0.0-20210510120138-977fb7262007 // indirect
) )

93
go.sum

@ -1,76 +1,75 @@
github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ= github.com/benbjohnson/clock v1.1.0 h1:Q92kusRqC1XV2MjkWETPvjJVqKetz1OzxZB7mHJLju8=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA=
github.com/DataDog/sketches-go v0.0.1/go.mod h1:Q5DbzQ+3AkgGwymQO7aZFNP7ns2lZKGtvRBzRXfdi60=
github.com/benbjohnson/clock v1.0.3/go.mod h1:bGMdMPoPVvcYyt1gHDf4J2KE153Yf9BuiUKYMaxlTDM=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 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 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.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/google/go-cmp v0.5.2 h1:X2ev0eStA3AbceY54o37/0PQ/UWqKEiiO2dKL5OPaFM= github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/gofuzz v1.1.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I= github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.8.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 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE=
github.com/sirupsen/logrus v1.7.0 h1:ShrD1U9pZB12TX0cVy0DtePoCH97K8EtX+mg7ZARUtM= github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk= github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0= github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= go.opentelemetry.io/otel v0.20.0 h1:eaP0Fqu7SXHwvjiqDq83zImeehOHX8doTvU9AwXON8g=
go.opentelemetry.io/otel v0.13.0 h1:2isEnyzjjJZq6r2EKMsFj4TxiQiexsM04AVhwbR/oBA= go.opentelemetry.io/otel v0.20.0/go.mod h1:Y3ugLH2oa81t5QO+Lty+zXf8zC9L26ax4Nzoxm/dooo=
go.opentelemetry.io/otel v0.13.0/go.mod h1:dlSNewoRYikTkotEnxdmuBHgzT+k/idJSfDv/FxEnOY= go.opentelemetry.io/otel/metric v0.20.0 h1:4kzhXFP+btKm4jwxpjIqjs41A7MakRFUS86bqLHTIw8=
go.opentelemetry.io/otel/sdk v0.13.0 h1:4VCfpKamZ8GtnepXxMRurSpHpMKkcxhtO33z1S4rGDQ= go.opentelemetry.io/otel/metric v0.20.0/go.mod h1:598I5tYlH1vzBjn+BTuhzTCSb/9debfNp6R3s7Pr1eU=
go.opentelemetry.io/otel/sdk v0.13.0/go.mod h1:dKvLH8Uu8LcEPlSAUsfW7kMGaJBhk/1NYvpPZ6wIMbU= go.opentelemetry.io/otel/oteltest v0.20.0 h1:HiITxCawalo5vQzdHfKeZurV8x7ljcqAgiWzF6Vaeaw=
go.uber.org/atomic v1.6.0 h1:Ezj3JGmsOnG1MoRWQkPBsKLe9DwWD9QeXzTRzzldNVk= go.opentelemetry.io/otel/oteltest v0.20.0/go.mod h1:L7bgKf9ZB7qCwT9Up7i9/pn0PWIa9FqQ2IQ8LoxiGnw=
go.uber.org/atomic v1.6.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= go.opentelemetry.io/otel/sdk v0.20.0 h1:JsxtGXd06J8jrnya7fdI/U/MR6yXA5DtbZy+qoHQlr8=
go.uber.org/multierr v1.5.0 h1:KCa4XfM8CWFCpxXRGok+Q0SS/0XBhMDbHHGABQLvD2A= go.opentelemetry.io/otel/sdk v0.20.0/go.mod h1:g/IcepuwNsoiX5Byy2nNV0ySUF1em498m7hBWC279Yc=
go.uber.org/multierr v1.5.0/go.mod h1:FeouvMocqHpRaaGuG9EjoKcStLC43Zu/fmqdUMPcKYU= go.opentelemetry.io/otel/trace v0.20.0 h1:1DL6EXUdcg95gukhuRRvLDO/4X5THh/5dIV52lqtnbw=
go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee h1:0mgffUl7nfd+FpvXMVz4IDEaUSmT1ysygQC7qYo7sG4= go.opentelemetry.io/otel/trace v0.20.0/go.mod h1:6GjCW8zgDjwGHGa6GkyeB8+/5vjT16gUEi0Nf1iBdgw=
go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA= go.uber.org/atomic v1.7.0 h1:ADUqmZGgLDDfbSL9ZmPxKTybcoEYHgpYfELNoN+7hsw=
go.uber.org/zap v1.16.0 h1:uFRZXykJGK9lLY4HtgSw44DnIcAM+kRBP7x5m+NpAOM= go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
go.uber.org/zap v1.16.0/go.mod h1:MA8QOfq0BHJwdXa996Y4dYkAqRKB8/1K1QMMZVaNZjQ= go.uber.org/goleak v1.1.11-0.20210813005559-691160354723 h1:sHOAIxRGBp443oHZIPB+HsUGaksVCXVQENPxwTfQdH4=
go.uber.org/goleak v1.1.11-0.20210813005559-691160354723/go.mod h1:cwTWslyiVhfpKIDGSZEM2HlOvcqm+tG4zioyIeLoqMQ=
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.19.1 h1:ue41HOKd1vGURxrmeKIgELGb3jPW9DMUDGtsinblHwI=
go.uber.org/zap v1.19.1/go.mod h1:j3DNczoxDZroyBnOT1L/Q79cfUMGZxlv/9dzN7SM1rI=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/lint v0.0.0-20190930215403-16217165b5de h1:5hukYrvBGR8/eNkX5mdUezrA6JiaEZDtJb9Ei+1LlBs=
golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859 h1:R/3boaszxrf1GEUWTVDzSKVwLmSJpwZ1yqXm8j0v2QI=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
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-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037 h1:YyJpGZS1sBuBCzLAR1VEpK193GlqGZbnPFnPV/5Rsb4=
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210510120138-977fb7262007 h1:gG67DSER+11cZvqIMb8S8bt0vZtiN6xWYARwirrOSfE=
golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5 h1:hKsoRgsbwY1NafxrwTs+k64bikrLBkAgPir1TNCj3Zs=
golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
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.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
honnef.co/go/tools v0.0.1-2019.2.3 h1:3JgtbtFHMiCmsznwGVTUWbgGov+pVqnlf1dEJTNAXeM= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo=
honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

90
handler/logrus/logger.go

@ -9,82 +9,36 @@ import (
"gitoa.ru/go-4devs/log/level" "gitoa.ru/go-4devs/log/level"
) )
// Option configure logger. // Standard create new standart logrus handler.
type Option func(*logger) func Standard() log.Logger {
return New(logrus.StandardLogger())
// WithLevel sets callback level to log level.
func WithLevel(level level.Level, c func(*logrus.Entry, string)) Option {
return func(l *logger) {
l.levels[level] = c
}
}
// WithLogrus sets logrus logger.
func WithLogrus(logrus *logrus.Logger) Option {
return func(l *logger) {
l.logrus = logrus
}
} }
// New create new logrus handler. // New create new logrus handler.
func New(opts ...Option) log.Logger { func New(log *logrus.Logger) log.Logger {
log := logger{ return func(ctx context.Context, e *entry.Entry) (int, error) {
logrus: logrus.StandardLogger(),
levels: map[level.Level]func(*logrus.Entry, string){
level.Emergency: panicLog,
level.Alert: fatalLog,
level.Critical: errorLog,
level.Error: errorLog,
level.Warning: warnLog,
level.Notice: infoLog,
level.Info: infoLog,
level.Debug: debugLog,
},
}
for _, o := range opts {
o(&log)
}
return log.log
}
type logger struct {
levels map[level.Level]func(l *logrus.Entry, msg string)
logrus *logrus.Logger
}
func (l *logger) log(ctx context.Context, e *entry.Entry) (int, error) {
lrgFields := make(logrus.Fields, e.Fields().Len()) lrgFields := make(logrus.Fields, e.Fields().Len())
for _, field := range e.Fields() { for _, field := range e.Fields() {
lrgFields[string(field.Key())] = field.AsInterface() lrgFields[string(field.Key())] = field.AsInterface()
} }
l.levels[e.Level()](l.logrus.WithFields(lrgFields), e.Message()) entry := log.WithContext(ctx).WithFields(lrgFields)
switch e.Level() {
case level.Emergency:
entry.Panic(e.Message())
case level.Alert:
entry.Fatal(e.Message())
case level.Critical, level.Error:
entry.Error(e.Message())
case level.Warning:
entry.Warn(e.Message())
case level.Notice, level.Info:
entry.Info(e.Message())
case level.Debug:
entry.Debug(e.Message())
}
return 0, nil return 0, nil
} }
func panicLog(e *logrus.Entry, msg string) {
e.Panic(msg)
}
func fatalLog(e *logrus.Entry, msg string) {
e.Fatal(msg)
}
func errorLog(e *logrus.Entry, msg string) {
e.Error(msg)
}
func warnLog(e *logrus.Entry, msg string) {
e.Warn(msg)
}
func infoLog(e *logrus.Entry, msg string) {
e.Info(msg)
}
func debugLog(e *logrus.Entry, msg string) {
e.Debug(msg)
} }

4
handler/logrus/logger_test.go

@ -13,6 +13,8 @@ import (
) )
func TestNew(t *testing.T) { func TestNew(t *testing.T) {
t.Parallel()
ctx := context.Background() ctx := context.Background()
buf := &bytes.Buffer{} buf := &bytes.Buffer{}
@ -23,7 +25,7 @@ func TestNew(t *testing.T) {
DisableTimestamp: true, DisableTimestamp: true,
}) })
handler := logrus.New(logrus.WithLogrus(lgrus)) handler := logrus.New(lgrus)
expect := "level=info msg=\"handle logrus message\"\n" expect := "level=info msg=\"handle logrus message\"\n"
if _, err := handler(ctx, entry.New(entry.WithLevel(level.Info), entry.WithMessage("handle logrus message"))); err != nil { if _, err := handler(ctx, entry.New(entry.WithLevel(level.Info), entry.WithMessage("handle logrus message"))); err != nil {

14
handler/otel/helpers.go

@ -5,8 +5,8 @@ import (
"gitoa.ru/go-4devs/log/entry" "gitoa.ru/go-4devs/log/entry"
"gitoa.ru/go-4devs/log/level" "gitoa.ru/go-4devs/log/level"
"go.opentelemetry.io/otel/api/trace" "go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/label" "go.opentelemetry.io/otel/trace"
) )
const ( const (
@ -40,17 +40,17 @@ func levels(lvl level.Level) Level {
func addEvent(ctx context.Context, e *entry.Entry) { func addEvent(ctx context.Context, e *entry.Entry) {
span := trace.SpanFromContext(ctx) span := trace.SpanFromContext(ctx)
attrs := make([]label.KeyValue, 0, e.Fields().Len()+levelFields) attrs := make([]attribute.KeyValue, 0, e.Fields().Len()+levelFields)
lvl := levels(e.Level()) lvl := levels(e.Level())
attrs = append(attrs, attrs = append(attrs,
label.String(fieldSeverityText, lvl.String()), attribute.String(fieldSeverityText, lvl.String()),
label.Int(fieldSeverityNumber, int(lvl)), attribute.Int(fieldSeverityNumber, int(lvl)),
) )
for _, field := range e.Fields() { for _, field := range e.Fields() {
attrs = append(attrs, label.String(string(field.Key()), field.Value().String())) attrs = append(attrs, attribute.String(string(field.Key()), field.Value().String()))
} }
span.AddEvent(ctx, e.Message(), attrs...) span.AddEvent(e.Message(), trace.WithAttributes(attrs...))
} }

94
handler/zap/logger.go

@ -9,87 +9,55 @@ import (
"go.uber.org/zap" "go.uber.org/zap"
) )
// Option configure logger. func Nop() log.Logger {
type Option func(*logger) return New(zap.NewNop())
// WithLevel sets level logged message.
func WithLevel(level level.Level, f func(z *zap.Logger, msg string, fields ...zap.Field)) Option {
return func(l *logger) {
l.levels[level] = f
}
} }
// WithZap sets zap logger. func Example(options ...zap.Option) log.Logger {
func WithZap(z *zap.Logger) Option { return New(zap.NewExample(options...))
return func(l *logger) {
l.zap = z
}
} }
// New create handler by zap logger. func Production(options ...zap.Option) log.Logger {
func New(opts ...Option) log.Logger { z, err := zap.NewProduction(options...)
z, err := zap.NewDevelopment()
if err != nil { if err != nil {
panic(err) panic(err)
} }
log := logger{ return New(z)
zap: z, }
levels: map[level.Level]func(z *zap.Logger, msg string, fields ...zap.Field){
level.Emergency: fatalLog,
level.Alert: panicLog,
level.Critical: errorLog,
level.Error: errorLog,
level.Warning: warnLog,
level.Notice: infoLog,
level.Info: infoLog,
level.Debug: debugLog,
},
}
for _, opt := range opts { func Development(options ...zap.Option) log.Logger {
opt(&log) z, err := zap.NewDevelopment(options...)
if err != nil {
panic(err)
} }
return log.log return New(z)
}
type logger struct {
zap *zap.Logger
levels map[level.Level]func(z *zap.Logger, msg string, fields ...zap.Field)
} }
func (l *logger) log(ctx context.Context, e *entry.Entry) (int, error) { // New create handler by zap logger.
func New(z *zap.Logger) log.Logger {
return func(ctx context.Context, e *entry.Entry) (int, error) {
zf := make([]zap.Field, e.Fields().Len()) zf := make([]zap.Field, e.Fields().Len())
for i, field := range e.Fields() { for i, field := range e.Fields() {
zf[i] = zap.Any(string(field.Key()), field.AsInterface()) zf[i] = zap.Any(string(field.Key()), field.AsInterface())
} }
l.levels[e.Level()](l.zap, e.Message(), zf...) switch e.Level() {
case level.Emergency:
z.Fatal(e.Message(), zf...)
case level.Alert:
z.Panic(e.Message(), zf...)
case level.Critical, level.Error:
z.Error(e.Message(), zf...)
case level.Warning:
z.Warn(e.Message(), zf...)
case level.Notice, level.Info:
z.Info(e.Message(), zf...)
case level.Debug:
z.Debug(e.Message(), zf...)
}
return 0, nil return 0, nil
} }
func panicLog(z *zap.Logger, msg string, fields ...zap.Field) {
z.Panic(msg, fields...)
}
func fatalLog(z *zap.Logger, msg string, fields ...zap.Field) {
z.Fatal(msg, fields...)
}
func errorLog(z *zap.Logger, msg string, fields ...zap.Field) {
z.Error(msg, fields...)
}
func warnLog(z *zap.Logger, msg string, fields ...zap.Field) {
z.Warn(msg, fields...)
}
func infoLog(z *zap.Logger, msg string, fields ...zap.Field) {
z.Info(msg, fields...)
}
func debugLog(z *zap.Logger, msg string, fields ...zap.Field) {
z.Debug(msg, fields...)
} }

4
handler/zap/logger_test.go

@ -14,6 +14,8 @@ import (
) )
func TestNew(t *testing.T) { func TestNew(t *testing.T) {
t.Parallel()
ctx := context.Background() ctx := context.Background()
buf := &bytes.Buffer{} buf := &bytes.Buffer{}
core := zapcore.NewCore(zapcore.NewJSONEncoder(zapcore.EncoderConfig{ core := zapcore.NewCore(zapcore.NewJSONEncoder(zapcore.EncoderConfig{
@ -24,7 +26,7 @@ func TestNew(t *testing.T) {
EncodeTime: zapcore.ISO8601TimeEncoder, EncodeTime: zapcore.ISO8601TimeEncoder,
EncodeDuration: zapcore.StringDurationEncoder, EncodeDuration: zapcore.StringDurationEncoder,
}), zapcore.AddSync(buf), zapcore.DebugLevel) }), zapcore.AddSync(buf), zapcore.DebugLevel)
logger := zlog.New(zlog.WithZap(zap.New(core))) logger := zlog.New(zap.New(core))
expect := `{"level":"info","msg":"handle zap message","env":"test"}` + "\n" expect := `{"level":"info","msg":"handle zap message","env":"test"}` + "\n"
if _, err := logger(ctx, entry.New( if _, err := logger(ctx, entry.New(

10
level/level.go

@ -2,6 +2,7 @@ package level
import ( import (
"encoding/json" "encoding/json"
"fmt"
"strings" "strings"
) )
@ -28,7 +29,12 @@ const (
) )
func (l Level) MarshalJSON() ([]byte, error) { func (l Level) MarshalJSON() ([]byte, error) {
return json.Marshal(l.String()) b, err := json.Marshal(l.String())
if err != nil {
return nil, fmt.Errorf("marshal err: %w", err)
}
return b, nil
} }
func (l Level) Is(level Level) bool { func (l Level) Is(level Level) bool {
@ -42,7 +48,7 @@ func (l Level) Enabled(level Level) bool {
func (l *Level) UnmarshalJSON(in []byte) error { func (l *Level) UnmarshalJSON(in []byte) error {
var v string var v string
if err := json.Unmarshal(in, &v); err != nil { if err := json.Unmarshal(in, &v); err != nil {
return err return fmt.Errorf("unmarshal err: %w", err)
} }
lvl := Parse(v) lvl := Parse(v)

27
logger.go

@ -323,6 +323,33 @@ type writer struct {
Logger Logger
} }
func (w writer) WithLevel(level level.Level) writer {
return writer{
level: level,
Logger: w.Logger,
ctx: w.ctx,
fields: w.fields,
}
}
func (w writer) WithContext(ctx context.Context) writer {
return writer{
level: w.level,
Logger: w.Logger,
ctx: ctx,
fields: w.fields,
}
}
func (w writer) WithFields(fields ...field.Field) writer {
return writer{
level: w.level,
Logger: w.Logger,
ctx: w.ctx,
fields: fields,
}
}
func (w writer) Write(in []byte) (int, error) { func (w writer) Write(in []byte) (int, error) {
return w.write(w.ctx, w.level, string(in), w.fields...) return w.write(w.ctx, w.level, string(in), w.fields...)
} }

27
logger_example_logrus_test.go

@ -2,20 +2,27 @@ package log_test
import ( import (
"io" "io"
"os"
slogrus "github.com/sirupsen/logrus"
"gitoa.ru/go-4devs/log/field" "gitoa.ru/go-4devs/log/field"
"gitoa.ru/go-4devs/log/handler/zap" "gitoa.ru/go-4devs/log/handler/logrus"
uzap "go.uber.org/zap"
) )
func ExampleNew_zapHandler() { func ExampleNew_logrusHandler() {
log := zap.New(zap.WithZap(uzap.NewExample())) lgrs := slogrus.New()
log.Err(ctx, "log zap") lgrs.SetOutput(os.Stdout)
log.ErrKV(ctx, "log zap kv", field.Int("int", 42)) lgrs.SetFormatter(&slogrus.TextFormatter{
log.ErrKVs(ctx, "log zap kv sugar", "err", io.EOF) DisableTimestamp: true,
})
log := logrus.New(lgrs)
log.Err(ctx, "log logrus")
log.ErrKV(ctx, "log logrus kv", field.Int("int", 42))
log.ErrKVs(ctx, "log logrus kv sugar", "err", io.EOF)
// Output: // Output:
// {"level":"error","msg":"log zap"} // level=error msg="log logrus"
// {"level":"error","msg":"log zap kv","int":42} // level=error msg="log logrus kv" int=42
// {"level":"error","msg":"log zap kv sugar","err":"EOF"} // level=error msg="log logrus kv sugar" err=EOF
} }

10
logger_example_test.go

@ -66,7 +66,7 @@ func ExampleNew_jsonFormat() {
log.GoVersion("go-version"), log.GoVersion("go-version"),
) )
logger.Err(ctx, "same error message") logger.Err(ctx, "same error message")
// Output: {"go-version":"go1.15.2","level":"error","msg":"same error message"} // Output: {"go-version":"go1.17.1","level":"error","msg":"same error message"}
} }
func ExampleNew_textEncoding() { func ExampleNew_textEncoding() {
@ -79,8 +79,8 @@ func ExampleNew_textEncoding() {
logger.InfoKVs(ctx, "same info message", "api-version", 0.1) logger.InfoKVs(ctx, "same info message", "api-version", 0.1)
// Output: // Output:
// msg="same error message" level=error go-version=go1.15.2 // msg="same error message" level=error go-version=go1.17.1
// msg="same info message" api-version=0.1 level=info go-version=go1.15.2 // msg="same info message" api-version=0.1 level=info go-version=go1.17.1
} }
type ctxKey string type ctxKey string
@ -102,7 +102,7 @@ func ExampleWith() {
levelInfo, log.WithContextValue(requestID), log.KeyValue("api", "0.1.0"), log.GoVersion("go"), levelInfo, log.WithContextValue(requestID), log.KeyValue("api", "0.1.0"), log.GoVersion("go"),
) )
logger.Info(vctx, "same message") logger.Info(vctx, "same message")
// Output: msg="same message" level=info requestID=6a5fa048-7181-11ea-bc55-0242ac130003 api=0.1.0 go=go1.15.2 // Output: msg="same message" level=info requestID=6a5fa048-7181-11ea-bc55-0242ac130003 api=0.1.0 go=go1.17.1
} }
func ExampleLogger_Print() { func ExampleLogger_Print() {
@ -111,7 +111,7 @@ func ExampleLogger_Print() {
levelInfo, log.KeyValue("client", "http"), log.KeyValue("api", "0.1.0"), log.GoVersion("go"), levelInfo, log.KeyValue("client", "http"), log.KeyValue("api", "0.1.0"), log.GoVersion("go"),
) )
logger.Print("same message") logger.Print("same message")
// Output: msg="same message" level=info client=http api=0.1.0 go=go1.15.2 // Output: msg="same message" level=info client=http api=0.1.0 go=go1.17.1
} }
func ExamplePrint() { func ExamplePrint() {

7
logger_example_trace_test.go

@ -8,9 +8,8 @@ import (
"gitoa.ru/go-4devs/log" "gitoa.ru/go-4devs/log"
"gitoa.ru/go-4devs/log/field" "gitoa.ru/go-4devs/log/field"
"gitoa.ru/go-4devs/log/handler/otel" "gitoa.ru/go-4devs/log/handler/otel"
apitrace "go.opentelemetry.io/otel/api/trace"
"go.opentelemetry.io/otel/sdk/export/trace"
sdktrace "go.opentelemetry.io/otel/sdk/trace" sdktrace "go.opentelemetry.io/otel/sdk/trace"
"go.opentelemetry.io/otel/trace"
) )
func ExampleNew_withTrace() { func ExampleNew_withTrace() {
@ -33,7 +32,7 @@ func ExampleNew_withTrace() {
// event: log logrus kv sugar, SeverityText = ERROR, SeverityNumber = 17, err = EOF // event: log logrus kv sugar, SeverityText = ERROR, SeverityNumber = 17, err = EOF
} }
func startSpan(ctx context.Context) (context.Context, apitrace.Span) { func startSpan(ctx context.Context) (context.Context, trace.Span) {
tp := sdktrace.NewTracerProvider(sdktrace.WithSyncer(exporter{})) tp := sdktrace.NewTracerProvider(sdktrace.WithSyncer(exporter{}))
return tp.Tracer("logger").Start(ctx, "operation") return tp.Tracer("logger").Start(ctx, "operation")
@ -45,7 +44,7 @@ func (e exporter) Shutdown(_ context.Context) error {
return nil return nil
} }
func (e exporter) ExportSpans(ctx context.Context, spanData []*trace.SpanData) error { func (e exporter) ExportSpans(ctx context.Context, spanData []*sdktrace.SpanSnapshot) error {
for _, data := range spanData { for _, data := range spanData {
for _, events := range data.MessageEvents { for _, events := range data.MessageEvents {
fmt.Print("event: ", events.Name) fmt.Print("event: ", events.Name)

27
logger_example_zap_test.go

@ -2,27 +2,20 @@ package log_test
import ( import (
"io" "io"
"os"
slogrus "github.com/sirupsen/logrus"
"gitoa.ru/go-4devs/log/field" "gitoa.ru/go-4devs/log/field"
"gitoa.ru/go-4devs/log/handler/logrus" "gitoa.ru/go-4devs/log/handler/zap"
uzap "go.uber.org/zap"
) )
func ExampleNew_logrusHandler() { func ExampleNew_zapHandler() {
lgrs := slogrus.New() log := zap.New(uzap.NewExample())
lgrs.SetOutput(os.Stdout) log.Err(ctx, "log zap")
lgrs.SetFormatter(&slogrus.TextFormatter{ log.ErrKV(ctx, "log zap kv", field.Int("int", 42))
DisableTimestamp: true, log.ErrKVs(ctx, "log zap kv sugar", "err", io.EOF)
})
log := logrus.New(logrus.WithLogrus(lgrs))
log.Err(ctx, "log logrus")
log.ErrKV(ctx, "log logrus kv", field.Int("int", 42))
log.ErrKVs(ctx, "log logrus kv sugar", "err", io.EOF)
// Output: // Output:
// level=error msg="log logrus" // {"level":"error","msg":"log zap"}
// level=error msg="log logrus kv" int=42 // {"level":"error","msg":"log zap kv","int":42}
// level=error msg="log logrus kv sugar" err=EOF // {"level":"error","msg":"log zap kv sugar","err":"EOF"}
} }

6
logger_test.go

@ -17,6 +17,8 @@ import (
var requestID ctxKey = "requestID" var requestID ctxKey = "requestID"
func TestFields(t *testing.T) { func TestFields(t *testing.T) {
t.Parallel()
type rObj struct { type rObj struct {
id string id string
} }
@ -58,6 +60,8 @@ func TestFields(t *testing.T) {
} }
func TestWriter(t *testing.T) { func TestWriter(t *testing.T) {
t.Parallel()
ctx := context.Background() ctx := context.Background()
success := "msg=\"info message\" err=file already exists requestID=6a5fa048-7181-11ea-bc55-0242ac1311113 level=info\n" success := "msg=\"info message\" err=file already exists requestID=6a5fa048-7181-11ea-bc55-0242ac1311113 level=info\n"
@ -84,6 +88,8 @@ func TestWriter(t *testing.T) {
} }
func TestLogger(t *testing.T) { func TestLogger(t *testing.T) {
t.Parallel()
ctx := context.Background() ctx := context.Background()
buf := &bytes.Buffer{} buf := &bytes.Buffer{}
logger := log.New(log.WithWriter(buf)).With(log.WithContextValue(requestID), log.WithLevel("level", level.Info)) logger := log.New(log.WithWriter(buf)).With(log.WithContextValue(requestID), log.WithLevel("level", level.Info))

25
writter.go

@ -4,6 +4,7 @@ import (
"bytes" "bytes"
"context" "context"
"encoding/json" "encoding/json"
"fmt"
"io" "io"
"os" "os"
"strings" "strings"
@ -23,10 +24,15 @@ func New(opts ...Option) Logger {
return func(_ context.Context, entry *entry.Entry) (int, error) { return func(_ context.Context, entry *entry.Entry) (int, error) {
b, err := l.e(entry) b, err := l.e(entry)
if err != nil { if err != nil {
return 0, err return 0, fmt.Errorf("enode err: %w", err)
} }
return l.w.Write(b) n, err := l.w.Write(b)
if err != nil {
return 0, fmt.Errorf("failed write: %w", err)
}
return n, nil
} }
} }
@ -50,9 +56,7 @@ func WithWriter(writer io.Writer) Option {
// WithStdout sets logged to os.Stdout. // WithStdout sets logged to os.Stdout.
func WithStdout() Option { func WithStdout() Option {
return func(l *log) { return WithWriter(os.Stdout)
l.w = os.Stdout
}
} }
// WithEncode sets format log. // WithEncode sets format log.
@ -64,18 +68,15 @@ func WithEncode(e Encode) Option {
// WithStringFormat sets format as simple string. // WithStringFormat sets format as simple string.
func WithStringFormat() Option { func WithStringFormat() Option {
return func(l *log) { return WithEncode(stringFormat())
l.e = stringFormat()
}
} }
// WithJSONFormat sets json output format. // WithJSONFormat sets json output format.
func WithJSONFormat() Option { func WithJSONFormat() Option {
return func(l *log) { return WithEncode(jsonFormat)
l.e = jsonFormat
}
} }
//nolint: forcetypeassert
func stringFormat() func(entry *entry.Entry) ([]byte, error) { func stringFormat() func(entry *entry.Entry) ([]byte, error) {
pool := sync.Pool{ pool := sync.Pool{
New: func() interface{} { New: func() interface{} {
@ -111,7 +112,7 @@ func stringFormat() func(entry *entry.Entry) ([]byte, error) {
func jsonFormat(entry *entry.Entry) ([]byte, error) { func jsonFormat(entry *entry.Entry) ([]byte, error) {
res, err := json.Marshal(entry.AddString("msg", entry.Message()).Fields().AsMap()) res, err := json.Marshal(entry.AddString("msg", entry.Message()).Fields().AsMap())
if err != nil { if err != nil {
return nil, err return nil, fmt.Errorf("marshal err: %w", err)
} }
return append(res, []byte("\n")...), nil return append(res, []byte("\n")...), nil

Loading…
Cancel
Save