9 Commits

Author SHA1 Message Date
andrey1s
fac9762f72 skip check error in example
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
continuous-integration/drone/tag Build is passing
2022-03-14 09:45:40 +03:00
andrey1s
0dc4c80cc2 upddate caller write method
Some checks failed
continuous-integration/drone/push Build is failing
continuous-integration/drone/pr Build is failing
2022-03-14 09:37:48 +03:00
012e2ce197 Merge pull request 'update golang' (#4) from fields into master
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #4
2022-03-13 13:17:01 +03:00
andrey1s
51b844d50b update golang
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2022-03-13 12:01:36 +03:00
f70653066a Merge pull request 'add test append fields' (#2) from fields into master
Some checks failed
continuous-integration/drone/push Build is failing
Reviewed-on: #2
2022-03-13 11:10:16 +03:00
andrey1s
21c14e24be update go version
Some checks failed
continuous-integration/drone/push Build is failing
2022-03-12 20:00:01 +03:00
andrey1s
d7310ed1df add test append fields 2022-03-12 10:01:11 +03:00
b80e6d1a29 Delete '.DS_Store' 2022-02-04 22:48:48 +03:00
b56ca08811 update zap/logrus hanler (#1)
Co-authored-by: andrey1s <andrey_simfi@list.ru>
Reviewed-on: #1
Co-authored-by: andrey <andrey@4devs.io>
Co-committed-by: andrey <andrey@4devs.io>
2022-01-02 14:32:19 +03:00
29 changed files with 668 additions and 547 deletions

BIN
.DS_Store vendored

Binary file not shown.

View File

@@ -3,7 +3,7 @@ name: default
steps: steps:
- name: test - name: test
image: golang:1.14.2 image: golang:1.17.8
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.44
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: {}

View File

@@ -9,18 +9,31 @@ 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
varnamelen:
min-name-length: 2
ignore-names:
- err
- "n"
- i
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 +44,5 @@ issues:
- path: _test\.go - path: _test\.go
linters: linters:
- gomnd - gomnd
- exhaustivestruct
- ireturn

View File

@@ -1,4 +1,4 @@
MIT License Copyright (c) 2020 go-4devs MIT License Copyright (c) 2020-2022 4devs
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal

View File

@@ -7,14 +7,14 @@ import (
) )
func Caller(depth int, full bool) string { func Caller(depth int, full bool) string {
const offset = 4 const offset = 3
_, file, line, ok := runtime.Caller(depth + offset) _, file, line, has := runtime.Caller(depth + offset)
if !ok { if !has {
file, line = "???", 0 file, line = "???", 0
} }
if !full && ok { if !full && has {
file = filepath.Base(file) file = filepath.Base(file)
} }

View File

@@ -1,6 +1,7 @@
package entry package entry
import ( import (
"fmt"
"strings" "strings"
"gitoa.ru/go-4devs/log/field" "gitoa.ru/go-4devs/log/field"
@@ -13,9 +14,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)
} }
} }
@@ -27,7 +28,14 @@ func WithFields(fields ...field.Field) Option {
func WithMessage(msg string) Option { func WithMessage(msg string) Option {
return func(e *Entry) { return func(e *Entry) {
e.msg = msg e.format = msg
}
}
func WithMessagef(format string, args ...interface{}) Option {
return func(e *Entry) {
e.format = format
e.args = args
} }
} }
@@ -38,27 +46,32 @@ func WithLevel(lvl level.Level) Option {
} }
func New(opts ...Option) *Entry { func New(opts ...Option) *Entry {
e := &Entry{ entry := &Entry{
fields: make(field.Fields, 0, defaultCap+1), fields: make(field.Fields, 0, defaultCap+1),
level: level.Debug, level: level.Debug,
format: "",
args: make([]interface{}, 0, defaultCap+1),
} }
for _, opt := range opts { for _, opt := range opts {
opt(e) opt(entry)
} }
return e return entry
} }
// Entry slice field. // Entry slice field.
type Entry struct { type Entry struct {
msg string format string
args []interface{}
level level.Level level level.Level
fields field.Fields fields field.Fields
} }
func (e *Entry) Reset() { func (e *Entry) Reset() {
e.fields = e.fields[:0] e.fields = e.fields[:0]
e.args = e.args[:0]
e.format = ""
} }
func (e *Entry) Fields() field.Fields { func (e *Entry) Fields() field.Fields {
@@ -72,7 +85,7 @@ func (e *Entry) String() string {
} }
str := make([]string, len(e.fields)+1) str := make([]string, len(e.fields)+1)
str[0] = e.msg str[0] = e.Message()
for i, field := range e.fields { for i, field := range e.fields {
str[i+1] = field.String() str[i+1] = field.String()
@@ -82,7 +95,14 @@ func (e *Entry) String() string {
} }
func (e *Entry) Message() string { func (e *Entry) Message() string {
return e.msg switch {
case len(e.args) > 0 && e.format != "":
return fmt.Sprintf(e.format, e.args...)
case len(e.args) > 0:
return fmt.Sprint(e.args...)
default:
return e.format
}
} }
func (e *Entry) Level() level.Level { func (e *Entry) Level() level.Level {
@@ -108,7 +128,18 @@ func (e *Entry) SetMessage(msg string) *Entry {
return New().SetMessage(msg) return New().SetMessage(msg)
} }
e.msg = msg e.format = msg
return e
}
func (e *Entry) SetMessagef(format string, args ...interface{}) *Entry {
if e == nil {
return New().SetMessagef(format, args...)
}
e.format = format
e.args = append(e.args[:0], args...)
return e return e
} }

View File

@@ -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()

View File

@@ -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)

View File

@@ -19,11 +19,11 @@ func (f Fields) Len() int {
} }
func (f Fields) AsMap() MapField { func (f Fields) AsMap() MapField {
m := make(MapField, len(f)) fields := make(MapField, len(f))
for _, field := range f { for _, field := range f {
m[field.Key()] = field.Value() fields[field.Key()] = field.Value()
} }
return m return fields
} }

17
field/fields_test.go Normal file
View File

@@ -0,0 +1,17 @@
package field_test
import (
"testing"
"github.com/stretchr/testify/require"
"gitoa.ru/go-4devs/log/field"
)
func TestFields_Append(t *testing.T) {
t.Parallel()
fields := field.Fields{field.Any("any", "value")}
fields = fields.Append(field.String("string", "value"))
require.Len(t, fields, 2)
}

View File

@@ -6,122 +6,124 @@ 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 val := value.(type) {
case string: case string:
return k.String(v) return k.String(val)
case *string: case *string:
return k.Stringp(v) return k.Stringp(val)
case []string: case []string:
return k.Strings(v...) return k.Strings(val...)
case bool: case bool:
return k.Bool(v) return k.Bool(val)
case *bool: case *bool:
return k.Boolp(v) return k.Boolp(val)
case []bool: case []bool:
return k.Bools(v...) return k.Bools(val...)
case int8: case int8:
return k.Int8(v) return k.Int8(val)
case []int8: case []int8:
return k.Int8s(v...) return k.Int8s(val...)
case *int8: case *int8:
return k.Int8p(v) return k.Int8p(val)
case int16: case int16:
return k.Int16(v) return k.Int16(val)
case []int16: case []int16:
return k.Int16s(v...) return k.Int16s(val...)
case *int16: case *int16:
return k.Int16p(v) return k.Int16p(val)
case int32: case int32:
return k.Int32(v) return k.Int32(val)
case []int32: case []int32:
return k.Int32s(v...) return k.Int32s(val...)
case *int32: case *int32:
return k.Int32p(v) return k.Int32p(val)
case int64: case int64:
return k.Int64(v) return k.Int64(val)
case []int64: case []int64:
return k.Int64s(v...) return k.Int64s(val...)
case *int64: case *int64:
return k.Int64p(v) return k.Int64p(val)
case uint: case uint:
return k.Uint(v) return k.Uint(val)
case []uint: case []uint:
return k.Uints(v...) return k.Uints(val...)
case *uint: case *uint:
return k.Uintp(v) return k.Uintp(val)
case uint8: case uint8:
return k.Uint8(v) return k.Uint8(val)
case *uint8: case *uint8:
return k.Uint8p(v) return k.Uint8p(val)
case uint16: case uint16:
return k.Uint16(v) return k.Uint16(val)
case []uint16: case []uint16:
return k.Uint16s(v...) return k.Uint16s(val...)
case *uint16: case *uint16:
return k.Uint16p(v) return k.Uint16p(val)
case uint32: case uint32:
return k.Uint32(v) return k.Uint32(val)
case []uint32: case []uint32:
return k.Uint32s(v...) return k.Uint32s(val...)
case *uint32: case *uint32:
return k.Uint32p(v) return k.Uint32p(val)
case uint64: case uint64:
return k.Uint64(v) return k.Uint64(val)
case []uint64: case []uint64:
return k.Uint64s(v...) return k.Uint64s(val...)
case *uint64: case *uint64:
return k.Uint64p(v) return k.Uint64p(val)
case float32: case float32:
return k.Float32(v) return k.Float32(val)
case []float32: case []float32:
return k.Float32s(v...) return k.Float32s(val...)
case *float32: case *float32:
return k.Float32p(v) return k.Float32p(val)
case float64: case float64:
return k.Float64(v) return k.Float64(val)
case []float64: case []float64:
return k.Float64s(v...) return k.Float64s(val...)
case *float64: case *float64:
return k.Float64p(v) return k.Float64p(val)
case complex64: case complex64:
return k.Complex64(v) return k.Complex64(val)
case []complex64: case []complex64:
return k.Complex64s(v...) return k.Complex64s(val...)
case *complex64: case *complex64:
return k.Complex64p(v) return k.Complex64p(val)
case uintptr: case uintptr:
return k.Uintptr(v) return k.Uintptr(val)
case []uintptr: case []uintptr:
return k.Uintptrs(v...) return k.Uintptrs(val...)
case *uintptr: case *uintptr:
return k.Uintptrp(v) return k.Uintptrp(val)
case []byte: case []byte:
return k.Bytes(v) return k.Bytes(val)
case time.Duration: case time.Duration:
return k.Dureation(v) return k.Dureation(val)
case []time.Duration: case []time.Duration:
return k.Dureations(v) return k.Dureations(val)
case *time.Duration: case *time.Duration:
return k.Dureationp(v) return k.Dureationp(val)
case time.Time: case time.Time:
return k.Time(v) return k.Time(val)
case []time.Time: case []time.Time:
return k.Times(v...) return k.Times(val...)
case *time.Time: case *time.Time:
return k.Timep(v) return k.Timep(val)
case error: case error:
return k.Error(v) return k.Error(val)
case []error: case []error:
return k.Errors(v...) return k.Errors(val...)
} }
return Field{ return Field{
key: k, key: k,
value: Value{ value: Value{
value: value, value: value,
vtype: TypeAny, vtype: TypeAny,
numeric: 0,
stringly: "",
}, },
} }
} }

View File

@@ -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():
@@ -260,48 +265,71 @@ func (v Value) asFloat64() float64 {
} }
func (v Value) asComplex64() complex64 { func (v Value) asComplex64() complex64 {
return v.value.(complex64) cmplex, _ := v.value.(complex64)
return cmplex
} }
func (v Value) asComplex128() complex128 { func (v Value) asComplex128() complex128 {
return v.value.(complex128) cmplex, _ := v.value.(complex128)
return cmplex
} }
func (v Value) asUintptr() uintptr { func (v Value) asUintptr() uintptr {
return v.value.(uintptr) val, _ := v.value.(uintptr)
return val
} }
func (v Value) asBinary() []byte { func (v Value) asBinary() []byte {
return v.value.([]byte) bytes, _ := v.value.([]byte)
return bytes
} }
func (v Value) asDuration() time.Duration { func (v Value) asDuration() time.Duration {
return v.value.(time.Duration) duration, _ := v.value.(time.Duration)
return duration
} }
func (v Value) asTime() time.Time { func (v Value) asTime() time.Time {
return v.value.(time.Time) value, _ := v.value.(time.Time)
return value
} }
func (v Value) asError() error { func (v Value) asError() error {
return v.value.(error) err, _ := v.value.(error)
return err
} }
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,
} }
} }
func stringsValue(v []string) Value { func stringsValue(v []string) Value {
return Value{ return Value{
value: v, value: v,
vtype: TypeString | TypeArray, vtype: TypeString | TypeArray,
numeric: 0,
stringly: "",
} }
} }
@@ -316,20 +344,27 @@ func stringpValue(v *string) Value {
func boolValue(b bool) Value { func boolValue(b bool) Value {
if b { if b {
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: "",
} }
} }
func boolsValue(b []bool) Value { func boolsValue(b []bool) Value {
return Value{ return Value{
value: b, value: b,
vtype: TypeBool | TypeArray, vtype: TypeBool | TypeArray,
numeric: 0,
stringly: "",
} }
} }
@@ -343,15 +378,19 @@ func boolpValue(b *bool) Value {
func intValue(i int) Value { func intValue(i int) Value {
return Value{ return Value{
vtype: TypeInt, vtype: TypeInt,
numeric: uint64(i), numeric: uint64(i),
value: nil,
stringly: "",
} }
} }
func intsValue(i []int) Value { func intsValue(i []int) Value {
return Value{ return Value{
value: i, value: i,
vtype: TypeInt | TypeArray, vtype: TypeInt | TypeArray,
numeric: 0,
stringly: "",
} }
} }
@@ -365,15 +404,19 @@ func intpValue(in *int) Value {
func int8Value(i int8) Value { func int8Value(i int8) Value {
return Value{ return Value{
vtype: TypeInt8, vtype: TypeInt8,
numeric: uint64(i), numeric: uint64(i),
value: nil,
stringly: "",
} }
} }
func int8sValue(i []int8) Value { func int8sValue(i []int8) Value {
return Value{ return Value{
value: i, value: i,
vtype: TypeInt8 | TypeArray, vtype: TypeInt8 | TypeArray,
numeric: 0,
stringly: "",
} }
} }
@@ -387,15 +430,19 @@ func int8pValue(in *int8) Value {
func int16Value(i int16) Value { func int16Value(i int16) Value {
return Value{ return Value{
vtype: TypeInt16, vtype: TypeInt16,
numeric: uint64(i), numeric: uint64(i),
value: 0,
stringly: "",
} }
} }
func int16sValue(i []int16) Value { func int16sValue(i []int16) Value {
return Value{ return Value{
value: i, value: i,
vtype: TypeInt16 | TypeArray, vtype: TypeInt16 | TypeArray,
numeric: 0,
stringly: "",
} }
} }
@@ -409,15 +456,19 @@ func int16pValue(in *int16) Value {
func int32Value(i int32) Value { func int32Value(i int32) Value {
return Value{ return Value{
vtype: TypeInt32, vtype: TypeInt32,
numeric: uint64(i), numeric: uint64(i),
value: nil,
stringly: "",
} }
} }
func int32sValue(i []int32) Value { func int32sValue(i []int32) Value {
return Value{ return Value{
value: i, value: i,
vtype: TypeInt32 | TypeArray, vtype: TypeInt32 | TypeArray,
numeric: 0,
stringly: "",
} }
} }
@@ -431,15 +482,19 @@ func int32pValue(in *int32) Value {
func int64Value(i int64) Value { func int64Value(i int64) Value {
return Value{ return Value{
vtype: TypeInt64, vtype: TypeInt64,
numeric: uint64(i), numeric: uint64(i),
value: nil,
stringly: "",
} }
} }
func int64sValue(i []int64) Value { func int64sValue(i []int64) Value {
return Value{ return Value{
value: i, value: i,
vtype: TypeInt64 | TypeArray, vtype: TypeInt64 | TypeArray,
numeric: 0,
stringly: "",
} }
} }
@@ -453,15 +508,19 @@ func int64pValue(in *int64) Value {
func uintValue(i uint) Value { func uintValue(i uint) Value {
return Value{ return Value{
vtype: TypeUint, vtype: TypeUint,
numeric: uint64(i), numeric: uint64(i),
value: nil,
stringly: "",
} }
} }
func uintsValue(i []uint) Value { func uintsValue(i []uint) Value {
return Value{ return Value{
value: i, value: i,
vtype: TypeUint | TypeArray, vtype: TypeUint | TypeArray,
numeric: 0,
stringly: "",
} }
} }
@@ -475,15 +534,19 @@ func uintpValue(in *uint) Value {
func uint8Value(i uint8) Value { func uint8Value(i uint8) Value {
return Value{ return Value{
vtype: TypeUint8, vtype: TypeUint8,
numeric: uint64(i), numeric: uint64(i),
value: nil,
stringly: "",
} }
} }
func uint8sValue(i []uint8) Value { func uint8sValue(i []uint8) Value {
return Value{ return Value{
value: i, value: i,
vtype: TypeUint8 | TypeArray, vtype: TypeUint8 | TypeArray,
numeric: 0,
stringly: "",
} }
} }
@@ -497,15 +560,19 @@ func uint8pValue(in *uint8) Value {
func uint16Value(i uint16) Value { func uint16Value(i uint16) Value {
return Value{ return Value{
vtype: TypeUint16, vtype: TypeUint16,
numeric: uint64(i), numeric: uint64(i),
value: nil,
stringly: "",
} }
} }
func uint16sValue(i []uint16) Value { func uint16sValue(i []uint16) Value {
return Value{ return Value{
value: i, value: i,
vtype: TypeUint16 | TypeArray, vtype: TypeUint16 | TypeArray,
numeric: 0,
stringly: "",
} }
} }
@@ -519,15 +586,19 @@ func uint16pValue(in *uint16) Value {
func uint32Value(i uint32) Value { func uint32Value(i uint32) Value {
return Value{ return Value{
vtype: TypeUint32, vtype: TypeUint32,
numeric: uint64(i), numeric: uint64(i),
value: nil,
stringly: "",
} }
} }
func uint32sValue(i []uint32) Value { func uint32sValue(i []uint32) Value {
return Value{ return Value{
value: i, value: i,
vtype: TypeUint32 | TypeArray, vtype: TypeUint32 | TypeArray,
numeric: 0,
stringly: "",
} }
} }
@@ -541,15 +612,19 @@ func uint32pValue(in *uint32) Value {
func uint64Value(i uint64) Value { func uint64Value(i uint64) Value {
return Value{ return Value{
vtype: TypeUint64, vtype: TypeUint64,
numeric: i, numeric: i,
value: nil,
stringly: "",
} }
} }
func uint64sValue(i []uint64) Value { func uint64sValue(i []uint64) Value {
return Value{ return Value{
value: i, value: i,
vtype: TypeUint64 | TypeArray, vtype: TypeUint64 | TypeArray,
numeric: 0,
stringly: "",
} }
} }
@@ -563,15 +638,19 @@ func uint64pValue(in *uint64) Value {
func float32Value(i float32) Value { 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: "",
} }
} }
func float32sValue(i []float32) Value { func float32sValue(i []float32) Value {
return Value{ return Value{
value: i, value: i,
vtype: TypeFloat32 | TypeArray, vtype: TypeFloat32 | TypeArray,
numeric: 0,
stringly: "",
} }
} }
@@ -585,15 +664,19 @@ func float32pValue(in *float32) Value {
func float64Value(i float64) Value { func float64Value(i float64) Value {
return Value{ return Value{
vtype: TypeFloat64, vtype: TypeFloat64,
numeric: math.Float64bits(i), numeric: math.Float64bits(i),
value: nil,
stringly: "",
} }
} }
func float64sValue(i []float64) Value { func float64sValue(i []float64) Value {
return Value{ return Value{
value: i, value: i,
vtype: TypeFloat64 | TypeArray, vtype: TypeFloat64 | TypeArray,
numeric: 0,
stringly: "",
} }
} }
@@ -607,15 +690,19 @@ func float64pValue(in *float64) Value {
func complex64Value(in complex64) Value { func complex64Value(in complex64) Value {
return Value{ return Value{
vtype: TypeComplex64, vtype: TypeComplex64,
value: in, value: in,
numeric: 0,
stringly: "",
} }
} }
func complex64sValue(in []complex64) Value { func complex64sValue(in []complex64) Value {
return Value{ return Value{
vtype: TypeComplex64 | TypeArray, vtype: TypeComplex64 | TypeArray,
value: in, value: in,
numeric: 0,
stringly: "",
} }
} }
@@ -629,15 +716,19 @@ func complex64pValue(in *complex64) Value {
func complex128Value(in complex128) Value { func complex128Value(in complex128) Value {
return Value{ return Value{
vtype: TypeComplex64, vtype: TypeComplex64,
value: in, value: in,
numeric: 0,
stringly: "",
} }
} }
func complex128sValue(in []complex128) Value { func complex128sValue(in []complex128) Value {
return Value{ return Value{
vtype: TypeComplex128 | TypeArray, vtype: TypeComplex128 | TypeArray,
value: in, value: in,
numeric: 0,
stringly: "",
} }
} }
@@ -651,15 +742,19 @@ func complex128pValue(in *complex128) Value {
func uintptrValue(in uintptr) Value { func uintptrValue(in uintptr) Value {
return Value{ return Value{
vtype: TypeUintptr, vtype: TypeUintptr,
value: in, numeric: 0,
stringly: "",
value: in,
} }
} }
func uintptrsValue(in []uintptr) Value { func uintptrsValue(in []uintptr) Value {
return Value{ return Value{
vtype: TypeUintptr | TypeArray, vtype: TypeUintptr | TypeArray,
value: in, value: in,
numeric: 0,
stringly: "",
} }
} }
@@ -673,22 +768,28 @@ func uintptrpValue(in *uintptr) Value {
func bytesValue(in []byte) Value { func bytesValue(in []byte) Value {
return Value{ return Value{
vtype: TypeBinary, vtype: TypeBinary,
value: in, value: in,
numeric: 0,
stringly: "",
} }
} }
func durationValue(in time.Duration) Value { func durationValue(in time.Duration) Value {
return Value{ return Value{
vtype: TypeDuration, vtype: TypeDuration,
value: in, value: in,
numeric: 0,
stringly: "",
} }
} }
func durationsValue(in []time.Duration) Value { 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 +818,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 +827,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,
} }
} }
@@ -739,8 +842,10 @@ func formatTimepValue(format string, in *time.Time) Value {
func errorValue(in error) Value { func errorValue(in error) Value {
if in != nil { if in != nil {
return Value{ return Value{
vtype: TypeError, vtype: TypeError,
value: in, value: in,
numeric: 0,
stringly: "",
} }
} }
@@ -749,7 +854,9 @@ func errorValue(in error) Value {
func errorsValue(in []error) Value { func errorsValue(in []error) Value {
return Value{ return Value{
vtype: TypeError | TypeArray, vtype: TypeError | TypeArray,
value: in, value: in,
numeric: 0,
stringly: "",
} }
} }

22
go.mod
View File

@@ -1,10 +1,22 @@
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 github.com/stretchr/testify v1.7.0
go.opentelemetry.io/otel/sdk v0.13.0 go.opentelemetry.io/otel v0.20.0
go.uber.org/zap v1.16.0 go.opentelemetry.io/otel/sdk v0.20.0
go.opentelemetry.io/otel/trace v0.20.0
go.uber.org/zap v1.21.0
)
require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
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
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect
) )

93
go.sum
View File

@@ -1,15 +1,10 @@
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 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=
@@ -19,58 +14,68 @@ 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/goleak v1.1.11/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=
go.uber.org/zap v1.21.0 h1:WefMeulhovoZ2sYXz7st6K0sLj7bBhpiFaud4r4zST8=
go.uber.org/zap v1.21.0/go.mod h1:wjWOCqI0f2ZZrJF/UufIOkiC8ii6tm1iqIsLo76RfJw=
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 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=

View File

@@ -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, data *entry.Entry) (int, error) {
logrus: logrus.StandardLogger(), lrgFields := make(logrus.Fields, data.Fields().Len())
levels: map[level.Level]func(*logrus.Entry, string){ for _, field := range data.Fields() {
level.Emergency: panicLog, lrgFields[string(field.Key())] = field.AsInterface()
level.Alert: fatalLog, }
level.Critical: errorLog,
level.Error: errorLog, entry := log.WithContext(ctx).WithFields(lrgFields)
level.Warning: warnLog,
level.Notice: infoLog, switch data.Level() {
level.Info: infoLog, case level.Emergency:
level.Debug: debugLog, entry.Panic(data.Message())
}, case level.Alert:
entry.Fatal(data.Message())
case level.Critical, level.Error:
entry.Error(data.Message())
case level.Warning:
entry.Warn(data.Message())
case level.Notice, level.Info:
entry.Info(data.Message())
case level.Debug:
entry.Debug(data.Message())
}
return 0, nil
} }
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())
for _, field := range e.Fields() {
lrgFields[string(field.Key())] = field.AsInterface()
}
l.levels[e.Level()](l.logrus.WithFields(lrgFields), e.Message())
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)
} }

View File

@@ -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 {

View File

@@ -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 (
@@ -38,19 +38,19 @@ func levels(lvl level.Level) Level {
return 0 return 0
} }
func addEvent(ctx context.Context, e *entry.Entry) { func addEvent(ctx context.Context, data *entry.Entry) {
span := trace.SpanFromContext(ctx) span := trace.SpanFromContext(ctx)
attrs := make([]label.KeyValue, 0, e.Fields().Len()+levelFields) attrs := make([]attribute.KeyValue, 0, data.Fields().Len()+levelFields)
lvl := levels(e.Level()) lvl := levels(data.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 data.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(data.Message(), trace.WithAttributes(attrs...))
} }

View File

@@ -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, func Development(options ...zap.Option) log.Logger {
level.Alert: panicLog, z, err := zap.NewDevelopment(options...)
level.Critical: errorLog, if err != nil {
level.Error: errorLog, panic(err)
level.Warning: warnLog,
level.Notice: infoLog,
level.Info: infoLog,
level.Debug: debugLog,
},
} }
for _, opt := range opts { return New(z)
opt(&log) }
// New create handler by zap logger.
func New(logger *zap.Logger) log.Logger {
return func(ctx context.Context, data *entry.Entry) (int, error) {
zf := make([]zap.Field, data.Fields().Len())
for i, field := range data.Fields() {
zf[i] = zap.Any(string(field.Key()), field.AsInterface())
}
switch data.Level() {
case level.Emergency:
logger.Fatal(data.Message(), zf...)
case level.Alert:
logger.Panic(data.Message(), zf...)
case level.Critical, level.Error:
logger.Error(data.Message(), zf...)
case level.Warning:
logger.Warn(data.Message(), zf...)
case level.Notice, level.Info:
logger.Info(data.Message(), zf...)
case level.Debug:
logger.Debug(data.Message(), zf...)
}
return 0, nil
} }
return log.log
}
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) {
zf := make([]zap.Field, e.Fields().Len())
for i, field := range e.Fields() {
zf[i] = zap.Any(string(field.Key()), field.AsInterface())
}
l.levels[e.Level()](l.zap, e.Message(), zf...)
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...)
} }

View File

@@ -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(

View File

@@ -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)

152
logger.go
View File

@@ -28,56 +28,46 @@ func writeOutput(_ int, err error) {
// Logger logged message. // Logger logged message.
type Logger func(ctx context.Context, entry *entry.Entry) (int, error) type Logger func(ctx context.Context, entry *entry.Entry) (int, error)
func (l Logger) log(ctx context.Context, level level.Level, args ...interface{}) {
writeOutput(l.write(ctx, level, fmt.Sprint(args...)))
}
func (l Logger) Write(in []byte) (int, error) { func (l Logger) Write(in []byte) (int, error) {
return l.write(context.Background(), level.Info, string(in)) return l.write(context.Background(), level.Info, string(in))
} }
func (l Logger) write(ctx context.Context, level level.Level, msg string, fields ...field.Field) (int, error) { func (l Logger) write(ctx context.Context, level level.Level, msg string, fields ...field.Field) (int, error) {
e := entry.Get() data := entry.Get()
defer func() { defer func() {
entry.Put(e) entry.Put(data)
}() }()
return l(ctx, e.SetLevel(level).SetMessage(msg).Add(fields...)) return l(ctx, data.SetLevel(level).SetMessage(msg).Add(fields...))
} }
func (l Logger) logKVs(ctx context.Context, level level.Level, msg string, args ...interface{}) { func (l Logger) writef(ctx context.Context, level level.Level, format string, args ...interface{}) (int, error) {
writeOutput(l.write(ctx, level, msg, l.kv(ctx, args...)...)) data := entry.Get()
}
func (l Logger) logKV(ctx context.Context, level level.Level, msg string, fields ...field.Field) { defer func() {
writeOutput(l.write(ctx, level, msg, fields...)) entry.Put(data)
} }()
func (l Logger) logf(ctx context.Context, level level.Level, format string, args ...interface{}) { return l(ctx, data.SetLevel(level).SetMessagef(format, args...))
writeOutput(l.write(ctx, level, fmt.Sprintf(format, args...)))
}
func (l Logger) logln(ctx context.Context, level level.Level, args ...interface{}) {
writeOutput(l.write(ctx, level, fmt.Sprintln(args...)))
} }
func (l Logger) kv(ctx context.Context, args ...interface{}) field.Fields { func (l Logger) kv(ctx context.Context, args ...interface{}) field.Fields {
e := entry.Get() kvEntry := entry.Get()
defer func() { defer func() {
entry.Put(e) entry.Put(kvEntry)
}() }()
for i := 0; i < len(args); i++ { for i := 0; i < len(args); i++ {
if f, ok := args[i].(field.Field); ok { if f, ok := args[i].(field.Field); ok {
e = e.Add(f) kvEntry = kvEntry.Add(f)
continue continue
} }
if i == len(args)-1 { if i == len(args)-1 {
l.logKV(ctx, level.Critical, fmt.Sprint("Ignored key without a value.", args[i]), e.Fields()...) writeOutput(l.write(ctx, level.Critical, fmt.Sprint("Ignored key without a value.", args[i]), kvEntry.Fields()...))
break break
} }
@@ -86,15 +76,15 @@ func (l Logger) kv(ctx context.Context, args ...interface{}) field.Fields {
key, val := args[i-1], args[i] key, val := args[i-1], args[i]
if keyStr, ok := key.(string); ok { if keyStr, ok := key.(string); ok {
e = e.AddAny(keyStr, val) kvEntry = kvEntry.AddAny(keyStr, val)
continue continue
} }
l.logKV(ctx, level.Critical, fmt.Sprint("Ignored key-value pairs with non-string keys.", key, val), e.Fields()...) writeOutput(l.write(ctx, level.Critical, fmt.Sprint("Ignored key-value pairs with non-string keys.", key, val), kvEntry.Fields()...))
} }
return e.Fields() return kvEntry.Fields()
} }
// With adds middlewares to logger. // With adds middlewares to logger.
@@ -104,207 +94,207 @@ func (l Logger) With(mw ...Middleware) Logger {
// Emerg log by emergency level. // Emerg log by emergency level.
func (l Logger) Emerg(ctx context.Context, args ...interface{}) { func (l Logger) Emerg(ctx context.Context, args ...interface{}) {
l.log(ctx, level.Emergency, args...) writeOutput(l.writef(ctx, level.Emergency, "", args...))
} }
// Alert log by alert level. // Alert log by alert level.
func (l Logger) Alert(ctx context.Context, args ...interface{}) { func (l Logger) Alert(ctx context.Context, args ...interface{}) {
l.log(ctx, level.Alert, args...) writeOutput(l.writef(ctx, level.Alert, "", args...))
} }
// Crit log by critical level. // Crit log by critical level.
func (l Logger) Crit(ctx context.Context, args ...interface{}) { func (l Logger) Crit(ctx context.Context, args ...interface{}) {
l.log(ctx, level.Critical, args...) writeOutput(l.writef(ctx, level.Critical, "", args...))
} }
// Err log by error level. // Err log by error level.
func (l Logger) Err(ctx context.Context, args ...interface{}) { func (l Logger) Err(ctx context.Context, args ...interface{}) {
l.log(ctx, level.Error, args...) writeOutput(l.writef(ctx, level.Error, "", args...))
} }
// Warn log by warning level. // Warn log by warning level.
func (l Logger) Warn(ctx context.Context, args ...interface{}) { func (l Logger) Warn(ctx context.Context, args ...interface{}) {
l.log(ctx, level.Warning, args...) writeOutput(l.writef(ctx, level.Warning, "", args...))
} }
// Notice log by notice level. // Notice log by notice level.
func (l Logger) Notice(ctx context.Context, args ...interface{}) { func (l Logger) Notice(ctx context.Context, args ...interface{}) {
l.log(ctx, level.Notice, args...) writeOutput(l.writef(ctx, level.Notice, "", args...))
} }
// Info log by info level. // Info log by info level.
func (l Logger) Info(ctx context.Context, args ...interface{}) { func (l Logger) Info(ctx context.Context, args ...interface{}) {
l.log(ctx, level.Info, args...) writeOutput(l.writef(ctx, level.Info, "", args...))
} }
// Debug log by debug level. // Debug log by debug level.
func (l Logger) Debug(ctx context.Context, args ...interface{}) { func (l Logger) Debug(ctx context.Context, args ...interface{}) {
l.log(ctx, level.Debug, args...) writeOutput(l.writef(ctx, level.Debug, "", args...))
} }
// Print log by info level and arguments. // Print log by info level and arguments.
func (l Logger) Print(args ...interface{}) { func (l Logger) Print(args ...interface{}) {
l.log(context.Background(), level.Info, args...) writeOutput(l.writef(context.Background(), level.Info, "", args...))
} }
// Fatal log by alert level and arguments. // Fatal log by alert level and arguments.
func (l Logger) Fatal(args ...interface{}) { func (l Logger) Fatal(args ...interface{}) {
l.log(context.Background(), level.Alert, args...) writeOutput(l.writef(context.Background(), level.Alert, "", args...))
} }
// Panic log by emergency level and arguments. // Panic log by emergency level and arguments.
func (l Logger) Panic(args ...interface{}) { func (l Logger) Panic(args ...interface{}) {
l.log(context.Background(), level.Emergency, args...) writeOutput(l.writef(context.Background(), level.Emergency, "", args...))
} }
// Println log by info level and arguments. // Println log by info level and arguments.
func (l Logger) Println(args ...interface{}) { func (l Logger) Println(args ...interface{}) {
l.logln(context.Background(), level.Info, args...) writeOutput(l.write(context.Background(), level.Info, fmt.Sprintln(args...)))
} }
// Fatalln log by alert level and arguments. // Fatalln log by alert level and arguments.
func (l Logger) Fatalln(args ...interface{}) { func (l Logger) Fatalln(args ...interface{}) {
l.logln(context.Background(), level.Alert, args...) writeOutput(l.write(context.Background(), level.Alert, fmt.Sprintln(args...)))
} }
// Panicln log by emergency level and arguments. // Panicln log by emergency level and arguments.
func (l Logger) Panicln(args ...interface{}) { func (l Logger) Panicln(args ...interface{}) {
l.logln(context.Background(), level.Emergency, args...) writeOutput(l.write(context.Background(), level.Emergency, fmt.Sprintln(args...)))
} }
// EmergKVs sugared log by emergency level and key-values. // EmergKVs sugared log by emergency level and key-values.
func (l Logger) EmergKVs(ctx context.Context, msg string, args ...interface{}) { func (l Logger) EmergKVs(ctx context.Context, msg string, args ...interface{}) {
l.logKVs(ctx, level.Emergency, msg, args...) writeOutput(l.write(ctx, level.Emergency, msg, l.kv(ctx, args...)...))
} }
// AlertKVs sugared log by alert level and key-values. // AlertKVs sugared log by alert level and key-values.
func (l Logger) AlertKVs(ctx context.Context, msg string, args ...interface{}) { func (l Logger) AlertKVs(ctx context.Context, msg string, args ...interface{}) {
l.logKVs(ctx, level.Alert, msg, args...) writeOutput(l.write(ctx, level.Alert, msg, l.kv(ctx, args...)...))
} }
// CritKVs sugared log by critcal level and key-values. // CritKVs sugared log by critcal level and key-values.
func (l Logger) CritKVs(ctx context.Context, msg string, args ...interface{}) { func (l Logger) CritKVs(ctx context.Context, msg string, args ...interface{}) {
l.logKVs(ctx, level.Critical, msg, args...) writeOutput(l.write(ctx, level.Critical, msg, l.kv(ctx, args...)...))
} }
// ErrKVs sugared log by error level and key-values. // ErrKVs sugared log by error level and key-values.
func (l Logger) ErrKVs(ctx context.Context, msg string, args ...interface{}) { func (l Logger) ErrKVs(ctx context.Context, msg string, args ...interface{}) {
l.logKVs(ctx, level.Error, msg, args...) writeOutput(l.write(ctx, level.Error, msg, l.kv(ctx, args...)...))
} }
// WarnKVs sugared log by warning level and key-values. // WarnKVs sugared log by warning level and key-values.
func (l Logger) WarnKVs(ctx context.Context, msg string, args ...interface{}) { func (l Logger) WarnKVs(ctx context.Context, msg string, args ...interface{}) {
l.logKVs(ctx, level.Warning, msg, args...) writeOutput(l.write(ctx, level.Warning, msg, l.kv(ctx, args...)...))
} }
// NoticeKVs sugared log by notice level and key-values. // NoticeKVs sugared log by notice level and key-values.
func (l Logger) NoticeKVs(ctx context.Context, msg string, args ...interface{}) { func (l Logger) NoticeKVs(ctx context.Context, msg string, args ...interface{}) {
l.logKVs(ctx, level.Notice, msg, args...) writeOutput(l.write(ctx, level.Notice, msg, l.kv(ctx, args...)...))
} }
// InfoKVs sugared log by info level and key-values. // InfoKVs sugared log by info level and key-values.
func (l Logger) InfoKVs(ctx context.Context, msg string, args ...interface{}) { func (l Logger) InfoKVs(ctx context.Context, msg string, args ...interface{}) {
l.logKVs(ctx, level.Info, msg, args...) writeOutput(l.write(ctx, level.Info, msg, l.kv(ctx, args...)...))
} }
// DebugKVs sugared log by debug level and key-values. // DebugKVs sugared log by debug level and key-values.
func (l Logger) DebugKVs(ctx context.Context, msg string, args ...interface{}) { func (l Logger) DebugKVs(ctx context.Context, msg string, args ...interface{}) {
l.logKVs(ctx, level.Debug, msg, args...) writeOutput(l.write(ctx, level.Debug, msg, l.kv(ctx, args...)...))
} }
// EmergKV log by emergency level and key-values. // EmergKV log by emergency level and key-values.
func (l Logger) EmergKV(ctx context.Context, msg string, args ...field.Field) { func (l Logger) EmergKV(ctx context.Context, msg string, args ...field.Field) {
l.logKV(ctx, level.Emergency, msg, args...) writeOutput(l.write(ctx, level.Emergency, msg, args...))
} }
// AlertKV log by alert level and key-values. // AlertKV log by alert level and key-values.
func (l Logger) AlertKV(ctx context.Context, msg string, args ...field.Field) { func (l Logger) AlertKV(ctx context.Context, msg string, args ...field.Field) {
l.logKV(ctx, level.Alert, msg, args...) writeOutput(l.write(ctx, level.Alert, msg, args...))
} }
// CritKV log by critcal level and key-values. // CritKV log by critcal level and key-values.
func (l Logger) CritKV(ctx context.Context, msg string, args ...field.Field) { func (l Logger) CritKV(ctx context.Context, msg string, args ...field.Field) {
l.logKV(ctx, level.Critical, msg, args...) writeOutput(l.write(ctx, level.Critical, msg, args...))
} }
// ErrKV log by error level and key-values. // ErrKV log by error level and key-values.
func (l Logger) ErrKV(ctx context.Context, msg string, args ...field.Field) { func (l Logger) ErrKV(ctx context.Context, msg string, args ...field.Field) {
l.logKV(ctx, level.Error, msg, args...) writeOutput(l.write(ctx, level.Error, msg, args...))
} }
// WarnKV log by warning level and key-values. // WarnKV log by warning level and key-values.
func (l Logger) WarnKV(ctx context.Context, msg string, args ...field.Field) { func (l Logger) WarnKV(ctx context.Context, msg string, args ...field.Field) {
l.logKV(ctx, level.Warning, msg, args...) writeOutput(l.write(ctx, level.Warning, msg, args...))
} }
// NoticeKV log by notice level and key-values. // NoticeKV log by notice level and key-values.
func (l Logger) NoticeKV(ctx context.Context, msg string, args ...field.Field) { func (l Logger) NoticeKV(ctx context.Context, msg string, args ...field.Field) {
l.logKV(ctx, level.Notice, msg, args...) writeOutput(l.write(ctx, level.Notice, msg, args...))
} }
// InfoKV log by info level and key-values. // InfoKV log by info level and key-values.
func (l Logger) InfoKV(ctx context.Context, msg string, args ...field.Field) { func (l Logger) InfoKV(ctx context.Context, msg string, args ...field.Field) {
l.logKV(ctx, level.Info, msg, args...) writeOutput(l.write(ctx, level.Info, msg, args...))
} }
// DebugKV log by debug level and key-values. // DebugKV log by debug level and key-values.
func (l Logger) DebugKV(ctx context.Context, msg string, args ...field.Field) { func (l Logger) DebugKV(ctx context.Context, msg string, args ...field.Field) {
l.logKV(ctx, level.Debug, msg, args...) writeOutput(l.write(ctx, level.Debug, msg, args...))
} }
// Emergf log by emergency level by format and arguments. // Emergf log by emergency level by format and arguments.
func (l Logger) Emergf(ctx context.Context, format string, args ...interface{}) { func (l Logger) Emergf(ctx context.Context, format string, args ...interface{}) {
l.logf(ctx, level.Emergency, format, args...) writeOutput(l.writef(ctx, level.Emergency, format, args...))
} }
// Alertf log by alert level by format and arguments. // Alertf log by alert level by format and arguments.
func (l Logger) Alertf(ctx context.Context, format string, args ...interface{}) { func (l Logger) Alertf(ctx context.Context, format string, args ...interface{}) {
l.logf(ctx, level.Alert, format, args...) writeOutput(l.writef(ctx, level.Alert, format, args...))
} }
// Critf log by critical level by format and arguments. // Critf log by critical level by format and arguments.
func (l Logger) Critf(ctx context.Context, format string, args ...interface{}) { func (l Logger) Critf(ctx context.Context, format string, args ...interface{}) {
l.logf(ctx, level.Critical, format, args...) writeOutput(l.writef(ctx, level.Critical, format, args...))
} }
// Errf log by error level by format and arguments. // Errf log by error level by format and arguments.
func (l Logger) Errf(ctx context.Context, format string, args ...interface{}) { func (l Logger) Errf(ctx context.Context, format string, args ...interface{}) {
l.logf(ctx, level.Error, format, args...) writeOutput(l.writef(ctx, level.Error, format, args...))
} }
// Warnf log by warning level by format and arguments. // Warnf log by warning level by format and arguments.
func (l Logger) Warnf(ctx context.Context, format string, args ...interface{}) { func (l Logger) Warnf(ctx context.Context, format string, args ...interface{}) {
l.logf(ctx, level.Warning, format, args...) writeOutput(l.writef(ctx, level.Warning, format, args...))
} }
// Noticef log by notice level by format and arguments. // Noticef log by notice level by format and arguments.
func (l Logger) Noticef(ctx context.Context, format string, args ...interface{}) { func (l Logger) Noticef(ctx context.Context, format string, args ...interface{}) {
l.logf(ctx, level.Notice, format, args...) writeOutput(l.writef(ctx, level.Notice, format, args...))
} }
// Infof log by info level by format and arguments. // Infof log by info level by format and arguments.
func (l Logger) Infof(ctx context.Context, format string, args ...interface{}) { func (l Logger) Infof(ctx context.Context, format string, args ...interface{}) {
l.logf(ctx, level.Info, format, args...) writeOutput(l.writef(ctx, level.Info, format, args...))
} }
// Debugf log by debug level by format and arguments. // Debugf log by debug level by format and arguments.
func (l Logger) Debugf(ctx context.Context, format string, args ...interface{}) { func (l Logger) Debugf(ctx context.Context, format string, args ...interface{}) {
l.logf(ctx, level.Debug, format, args...) writeOutput(l.writef(ctx, level.Debug, format, args...))
} }
// Printf log by info level by format and arguments without context. // Printf log by info level by format and arguments without context.
func (l Logger) Printf(format string, args ...interface{}) { func (l Logger) Printf(format string, args ...interface{}) {
l.logf(context.Background(), level.Info, format, args...) writeOutput(l.writef(context.Background(), level.Info, format, args...))
} }
// Fatalf log by alert level by format and arguments without context. // Fatalf log by alert level by format and arguments without context.
func (l Logger) Fatalf(format string, args ...interface{}) { func (l Logger) Fatalf(format string, args ...interface{}) {
l.logf(context.Background(), level.Alert, format, args...) writeOutput(l.writef(context.Background(), level.Alert, format, args...))
} }
// Panicf log by emergency level and arguments without context. // Panicf log by emergency level and arguments without context.
func (l Logger) Panicf(format string, args ...interface{}) { func (l Logger) Panicf(format string, args ...interface{}) {
l.logf(context.Background(), level.Emergency, format, args...) writeOutput(l.writef(context.Background(), level.Emergency, format, args...))
} }
func (l Logger) Writer(ctx context.Context, level level.Level, fields ...field.Field) io.Writer { func (l Logger) Writer(ctx context.Context, level level.Level, fields ...field.Field) io.Writer {
@@ -316,6 +306,7 @@ func (l Logger) Writer(ctx context.Context, level level.Level, fields ...field.F
} }
} }
//nolint: containedctx
type writer struct { type writer struct {
ctx context.Context ctx context.Context
level level.Level level level.Level
@@ -323,6 +314,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...)
} }

View File

@@ -13,8 +13,10 @@ func ExampleNew_withCaller() {
) )
logger.Err(ctx, "same error message") logger.Err(ctx, "same error message")
logger.InfoKVs(ctx, "same info message", "api-version", 0.1) logger.InfoKVs(ctx, "same info message", "api-version", 0.1)
_, _ = logger.Write([]byte("same write message"))
// Output: // Output:
// msg="same error message" level=error caller=logger_example_caller_test.go:14 // msg="same error message" level=error caller=logger_example_caller_test.go:14
// msg="same info message" api-version=0.1 level=info caller=logger_example_caller_test.go:15 // msg="same info message" api-version=0.1 level=info caller=logger_example_caller_test.go:15
// msg="same write message" level=info caller=logger_example_caller_test.go:16
} }

View File

@@ -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
} }

View File

@@ -52,13 +52,16 @@ func ExampleNew_debugKV() {
func ExampleNew_level() { func ExampleNew_level() {
logger := log.New(log.WithStdout()).With(log.WithLevel("level", level.Error)) logger := log.New(log.WithStdout()).With(log.WithLevel("level", level.Error))
logger.Info(ctx, "same message")
// Output:
logger.Err(ctx, "same error message") logger.Err(ctx, "same error message")
// Output: msg="same error message" level=error // Output: msg="same error message" level=error
} }
func ExampleNew_level_info() {
logger := log.New(log.WithStdout()).With(log.WithLevel("level", level.Error))
logger.Info(ctx, "same message")
// Output:
}
func ExampleNew_jsonFormat() { func ExampleNew_jsonFormat() {
logger := log.New(log.WithStdout(), log.WithJSONFormat()). logger := log.New(log.WithStdout(), log.WithJSONFormat()).
With( With(
@@ -66,7 +69,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.8","level":"error","msg":"same error message"}
} }
func ExampleNew_textEncoding() { func ExampleNew_textEncoding() {
@@ -79,8 +82,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.8
// 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.8
} }
type ctxKey string type ctxKey string
@@ -102,7 +105,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.8
} }
func ExampleLogger_Print() { func ExampleLogger_Print() {
@@ -111,7 +114,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.8
} }
func ExamplePrint() { func ExamplePrint() {

View File

@@ -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)

View File

@@ -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"}
} }

View File

@@ -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))

View File

@@ -30,7 +30,7 @@ func With(logger Logger, mw ...Middleware) Logger {
lastI := len(mw) - 1 lastI := len(mw) - 1
return func(ctx context.Context, e *entry.Entry) (int, error) { return func(ctx context.Context, data *entry.Entry) (int, error) {
var ( var (
chainHandler func(context.Context, *entry.Entry) (int, error) chainHandler func(context.Context, *entry.Entry) (int, error)
curI int curI int
@@ -47,7 +47,7 @@ func With(logger Logger, mw ...Middleware) Logger {
return n, err return n, err
} }
return mw[0](ctx, e, chainHandler) return mw[0](ctx, data, chainHandler)
} }
} }
@@ -62,16 +62,16 @@ func WithLevel(key string, lvl level.Level) Middleware {
} }
} }
func WithClosure(ctx context.Context, e *entry.Entry, handler Logger) (int, error) { func WithClosure(ctx context.Context, data *entry.Entry, handler Logger) (int, error) {
for i, field := range e.Fields() { for i, field := range data.Fields() {
if field.Type().IsAny() { if field.Type().IsAny() {
if f, ok := field.AsInterface().(func() string); ok { if f, ok := field.AsInterface().(func() string); ok {
e.Fields().Set(i, field.Key().String(f())) data.Fields().Set(i, field.Key().String(f()))
} }
} }
} }
return handler(ctx, e) return handler(ctx, data)
} }
// KeyValue add field by const key value. // KeyValue add field by const key value.

View File

@@ -4,6 +4,7 @@ import (
"bytes" "bytes"
"context" "context"
"encoding/json" "encoding/json"
"fmt"
"io" "io"
"os" "os"
"strings" "strings"
@@ -14,19 +15,24 @@ import (
// New creates standart logger. // New creates standart logger.
func New(opts ...Option) Logger { func New(opts ...Option) Logger {
l := log{e: stringFormat(), w: os.Stderr} logger := log{e: stringFormat(), w: os.Stderr}
for _, opt := range opts { for _, opt := range opts {
opt(&l) opt(&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 := logger.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 := logger.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{} {
@@ -84,34 +85,34 @@ func stringFormat() func(entry *entry.Entry) ([]byte, error) {
} }
return func(entry *entry.Entry) ([]byte, error) { return func(entry *entry.Entry) ([]byte, error) {
b := pool.Get().(*bytes.Buffer) buf := pool.Get().(*bytes.Buffer)
b.Reset() buf.Reset()
defer func() { defer func() {
pool.Put(b) pool.Put(buf)
}() }()
b.WriteString("msg=\"") buf.WriteString("msg=\"")
b.WriteString(strings.TrimSpace(entry.Message())) buf.WriteString(strings.TrimSpace(entry.Message()))
b.WriteString("\"") buf.WriteString("\"")
for _, field := range entry.Fields() { for _, field := range entry.Fields() {
b.WriteString(" ") buf.WriteString(" ")
b.WriteString(string(field.Key())) buf.WriteString(string(field.Key()))
b.WriteString("=") buf.WriteString("=")
b.WriteString(field.Value().String()) buf.WriteString(field.Value().String())
} }
b.WriteString("\n") buf.WriteString("\n")
return b.Bytes(), nil return buf.Bytes(), nil
} }
} }
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