9 Commits

Author SHA1 Message Date
81eaf8c8b2 update opentelemetry version (#6)
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/tag Build is passing
Co-authored-by: andrey1s <andrey@4devs.pro>
Reviewed-on: #6
Co-authored-by: andrey <andrey@4devs.io>
Co-committed-by: andrey <andrey@4devs.io>
2022-09-06 22:25:04 +03:00
7570ade82a upddate caller write method (#5)
All checks were successful
continuous-integration/drone/push Build is passing
Co-authored-by: andrey1s <andrey@4devs.pro>
Reviewed-on: #5
Co-authored-by: andrey <andrey@4devs.io>
Co-committed-by: andrey <andrey@4devs.io>
2022-03-14 09:58:23 +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 580 additions and 376 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.17.1 image: golang:1.18.1
volumes: volumes:
- name: deps - name: deps
path: /go/src/mod path: /go/src/mod
@@ -11,7 +11,7 @@ steps:
- go test - go test
- name: golangci-lint - name: golangci-lint
image: golangci/golangci-lint:v1.42 image: golangci/golangci-lint:v1.49
commands: commands:
- golangci-lint run - golangci-lint run

View File

@@ -9,21 +9,45 @@ 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
disable:
- exhaustivestruct
- maligned
- deadcode
- interfacer
- golint
- varcheck
- nosnakecase
- scopelint
- ifshort
- structcheck
issues: issues:
# Excluding configuration per-path, per-linter, per-text and per-source # Excluding configuration per-path, per-linter, per-text and per-source
@@ -31,3 +55,5 @@ issues:
- path: _test\.go - path: _test\.go
linters: linters:
- gomnd - gomnd
- ireturn
- exhaustruct

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

@@ -4,7 +4,7 @@ import (
"context" "context"
"errors" "errors"
"fmt" "fmt"
"io/ioutil" "io"
"testing" "testing"
"time" "time"
@@ -12,7 +12,7 @@ import (
"gitoa.ru/go-4devs/log/field" "gitoa.ru/go-4devs/log/field"
) )
// nolint: gochecknoglobals //nolint:gochecknoglobals
var ( var (
errExample = errors.New("fail") errExample = errors.New("fail")
_messages = fakeMessages(1000) _messages = fakeMessages(1000)
@@ -118,7 +118,7 @@ func fakeSugarFields() []interface{} {
} }
func NewLogger() log.Logger { func NewLogger() log.Logger {
return log.New(log.WithWriter(ioutil.Discard)) return log.New(log.WithWriter(io.Discard))
} }
func BenchmarkDisabledWithoutFields(b *testing.B) { func BenchmarkDisabledWithoutFields(b *testing.B) {

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

@@ -2,13 +2,14 @@ package entry
import "sync" import "sync"
// nolint: gochecknoglobals //nolint:gochecknoglobals
var pool = sync.Pool{ var pool = sync.Pool{
New: func() interface{} { New: func() interface{} {
return New() return New()
}, },
} }
//nolint:forcetypeassert
func Get() *Entry { func Get() *Entry {
e := pool.Get().(*Entry) e := pool.Get().(*Entry)
e.Reset() e.Reset()

View File

@@ -2,6 +2,7 @@ package field
import "time" import "time"
//nolint:interfacebloat
type Encoder interface { type Encoder interface {
// Built-in types. // Built-in types.
AddArray(key string, value Value) AddArray(key string, value Value)

View File

@@ -255,13 +255,13 @@ 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)
switch { switch {
case f.value.IsArray(): case f.value.IsArray():
enc.AddAny(key, f.value) enc.AddArray(key, f.value)
case f.value.IsNil(): case f.value.IsNil():
enc.AddNil(key) enc.AddNil(key)
case f.value.IsBool(): case f.value.IsBool():

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

18
field/fields_test.go Normal file
View File

@@ -0,0 +1,18 @@
package field_test
import (
"testing"
"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"))
if len(fields) != 2 {
t.Fatalf("require 2 field got %v", len(fields))
}
}

View File

@@ -6,122 +6,124 @@ import (
type Key string type Key string
//nolint: gocyclo, funlen //nolint:funlen,cyclop,gocyclo
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: "",
} }
} }

17
go.mod
View File

@@ -3,8 +3,17 @@ module gitoa.ru/go-4devs/log
go 1.17 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 v1.9.0
go.opentelemetry.io/otel/sdk v0.13.0 go.opentelemetry.io/otel/sdk v1.9.0
go.uber.org/zap v1.16.0 go.opentelemetry.io/otel/trace v1.9.0
go.uber.org/zap v1.21.0
)
require (
github.com/go-logr/logr v1.2.3 // indirect
github.com/go-logr/stdr v1.2.2 // 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
) )

109
go.sum
View File

@@ -1,88 +1,77 @@
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 h1:RtG+76WKgZuz6FIaGsjoPePmadDBkuD/KC6+ZWu78b8=
github.com/DataDog/sketches-go v0.0.1/go.mod h1:Q5DbzQ+3AkgGwymQO7aZFNP7ns2lZKGtvRBzRXfdi60=
github.com/benbjohnson/clock v1.0.3 h1:vkLuvpK4fmtSCuo60+yC63p7y0BmQ8gm5ZXGuBCJyXg=
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/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/go-logr/logr v1.2.3 h1:2DntVwHkVopvECVRSlL5PSo9eG+cAkDCuckLubN+rq0=
github.com/google/gofuzz v1.1.0 h1:Hsa8mG0dQ46ij8Sl2AYJDUv1oA9/d6Vk+3LG99Oe02g= github.com/go-logr/logr v1.2.3/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
github.com/google/gofuzz v1.1.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/google/renameio v0.1.0 h1:GOZbcHa3HfsPKPlmyPyN2KEohoMXOhdMbHrvbpl2QaA= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= github.com/google/go-cmp v0.5.8 h1:e6P7q2lk1O+qJJb4BtCQXlK8vWEO8V1ZeuEdJNOqZyg=
github.com/kisielk/gotool v1.0.0 h1:AV2c/EiW3KqPNT9ZKl07ehoAGi4C5/01Cfbblndcapg= github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
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 h1:VkoXIwSboBpnk99O/KFauAEILuNHv5DVFKZMBN/gUgw=
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 h1:RR9dF3JtopPvtkroDZuVD7qquD0bnHlKSqaQhgwt8yk= github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE=
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
github.com/sirupsen/logrus v1.7.0 h1:ShrD1U9pZB12TX0cVy0DtePoCH97K8EtX+mg7ZARUtM=
github.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=
github.com/stretchr/objx v0.1.0 h1:4G4v2dO3VZwixGIRoQ5Lfboy6nUhCyYzaqnIAPPhYs4=
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/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/stretchr/testify v1.7.1 h1:5TQK59W5E3v0r2duFAb7P95B6hEeOyEnHRa8MjYSMTY=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
go.opentelemetry.io/otel v0.13.0 h1:2isEnyzjjJZq6r2EKMsFj4TxiQiexsM04AVhwbR/oBA= github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
go.opentelemetry.io/otel v0.13.0/go.mod h1:dlSNewoRYikTkotEnxdmuBHgzT+k/idJSfDv/FxEnOY= go.opentelemetry.io/otel v1.9.0 h1:8WZNQFIB2a71LnANS9JeyidJKKGOOremcUtb/OtHISw=
go.opentelemetry.io/otel/sdk v0.13.0 h1:4VCfpKamZ8GtnepXxMRurSpHpMKkcxhtO33z1S4rGDQ= go.opentelemetry.io/otel v1.9.0/go.mod h1:np4EoPGzoPs3O67xUVNoPPcmSvsfOxNlNA4F4AC+0Eo=
go.opentelemetry.io/otel/sdk v0.13.0/go.mod h1:dKvLH8Uu8LcEPlSAUsfW7kMGaJBhk/1NYvpPZ6wIMbU= go.opentelemetry.io/otel/sdk v1.9.0 h1:LNXp1vrr83fNXTHgU8eO89mhzxb/bbWAsHG6fNf3qWo=
go.uber.org/atomic v1.6.0 h1:Ezj3JGmsOnG1MoRWQkPBsKLe9DwWD9QeXzTRzzldNVk= go.opentelemetry.io/otel/sdk v1.9.0/go.mod h1:AEZc8nt5bd2F7BC24J5R0mrjYnpEgYHyTcM/vrSple4=
go.uber.org/atomic v1.6.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= go.opentelemetry.io/otel/trace v1.9.0 h1:oZaCNJUjWcg60VXWee8lJKlqhPbXAPB51URuR47pQYc=
go.uber.org/multierr v1.5.0 h1:KCa4XfM8CWFCpxXRGok+Q0SS/0XBhMDbHHGABQLvD2A= go.opentelemetry.io/otel/trace v1.9.0/go.mod h1:2737Q0MuG8q1uILYm2YYVkAyLtOofiTNGg6VODnOiPo=
go.uber.org/multierr v1.5.0/go.mod h1:FeouvMocqHpRaaGuG9EjoKcStLC43Zu/fmqdUMPcKYU= go.uber.org/atomic v1.7.0 h1:ADUqmZGgLDDfbSL9ZmPxKTybcoEYHgpYfELNoN+7hsw=
go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee h1:0mgffUl7nfd+FpvXMVz4IDEaUSmT1ysygQC7qYo7sG4= go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA= go.uber.org/goleak v1.1.11 h1:wy28qYRKZgnJTxGxvye5/wgWr1EKjmUDGYox5mGlRlI=
go.uber.org/zap v1.16.0 h1:uFRZXykJGK9lLY4HtgSw44DnIcAM+kRBP7x5m+NpAOM= go.uber.org/goleak v1.1.11/go.mod h1:cwTWslyiVhfpKIDGSZEM2HlOvcqm+tG4zioyIeLoqMQ=
go.uber.org/zap v1.16.0/go.mod h1:MA8QOfq0BHJwdXa996Y4dYkAqRKB8/1K1QMMZVaNZjQ= 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.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 h1:iMGN4xG0cnqj3t+zOM8wUB0BiPKHEwSxEZCvzcbZuvk= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/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 h1:JgcxKXxCjrA2tyDP/aNU9K0Ck5Czfk6C7e2tMw7+bSI= golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc=
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/sync v0.0.0-20190423024810-112230192c58 h1:8gQV6CLnAEikrhgkHFbMAEhagSSnXWGV915qUMm9mrU= 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/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= 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-20210423185535-09eb48e85fd7/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-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 h1:0vLT13EuvQ0hNvakwLuFZ/jYrLp5F3kcWHXdRggjCE8= gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
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

@@ -16,25 +16,27 @@ func Standard() log.Logger {
// New create new logrus handler. // New create new logrus handler.
func New(log *logrus.Logger) log.Logger { func New(log *logrus.Logger) log.Logger {
return func(ctx context.Context, e *entry.Entry) (int, error) { return func(ctx context.Context, data *entry.Entry) (int, error) {
lrgFields := make(logrus.Fields, e.Fields().Len()) lrgFields := make(logrus.Fields, data.Fields().Len())
for _, field := range e.Fields() { for _, field := range data.Fields() {
lrgFields[string(field.Key())] = field.AsInterface() lrgFields[string(field.Key())] = field.AsInterface()
} }
write := log.WithContext(ctx).WithFields(lrgFields)
switch e.Level() { entry := log.WithContext(ctx).WithFields(lrgFields)
switch data.Level() {
case level.Emergency: case level.Emergency:
write.Panic(e.Message()) entry.Panic(data.Message())
case level.Alert: case level.Alert:
write.Fatal(e.Message()) entry.Fatal(data.Message())
case level.Critical, level.Error: case level.Critical, level.Error:
write.Error(e.Message()) entry.Error(data.Message())
case level.Warning: case level.Warning:
write.Warn(e.Message()) entry.Warn(data.Message())
case level.Notice, level.Info: case level.Notice, level.Info:
write.Info(e.Message()) entry.Info(data.Message())
case level.Debug: case level.Debug:
write.Debug(e.Message()) entry.Debug(data.Message())
} }
return 0, nil return 0, nil

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

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

@@ -36,26 +36,26 @@ func Development(options ...zap.Option) log.Logger {
} }
// New create handler by zap logger. // New create handler by zap logger.
func New(z *zap.Logger) log.Logger { func New(logger *zap.Logger) log.Logger {
return func(ctx context.Context, e *entry.Entry) (int, error) { return func(ctx context.Context, data *entry.Entry) (int, error) {
zf := make([]zap.Field, e.Fields().Len()) zf := make([]zap.Field, data.Fields().Len())
for i, field := range e.Fields() { for i, field := range data.Fields() {
zf[i] = zap.Any(string(field.Key()), field.AsInterface()) zf[i] = zap.Any(string(field.Key()), field.AsInterface())
} }
switch e.Level() { switch data.Level() {
case level.Emergency: case level.Emergency:
z.Fatal(e.Message(), zf...) logger.Fatal(data.Message(), zf...)
case level.Alert: case level.Alert:
z.Panic(e.Message(), zf...) logger.Panic(data.Message(), zf...)
case level.Critical, level.Error: case level.Critical, level.Error:
z.Error(e.Message(), zf...) logger.Error(data.Message(), zf...)
case level.Warning: case level.Warning:
z.Warn(e.Message(), zf...) logger.Warn(data.Message(), zf...)
case level.Notice, level.Info: case level.Notice, level.Info:
z.Info(e.Message(), zf...) logger.Info(data.Message(), zf...)
case level.Debug: case level.Debug:
z.Debug(e.Message(), zf...) logger.Debug(data.Message(), zf...)
} }
return 0, nil return 0, nil

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{

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)

125
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

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

@@ -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.18.1","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.18.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.18.1
} }
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.18.1
} }
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.18.1
} }
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,9 +44,9 @@ 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.ReadOnlySpan) error {
for _, data := range spanData { for _, data := range spanData {
for _, events := range data.MessageEvents { for _, events := range data.Events() {
fmt.Print("event: ", events.Name) fmt.Print("event: ", events.Name)
for _, attr := range events.Attributes { for _, attr := range events.Attributes {

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
} }
} }
@@ -70,6 +76,7 @@ func WithJSONFormat() Option {
return WithEncode(jsonFormat) return WithEncode(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{} {
@@ -78,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