Browse Source

update golang

pull/3/head
andrey1s 3 years ago
parent
commit
615c6b7cd6
  1. 4
      .drone.yml
  2. 7
      .golangci.yml
  3. 6
      entry/caller.go
  4. 6
      entry/entry.go
  5. 6
      field/fields.go
  6. 2
      field/fields_test.go
  7. 108
      field/key.go
  8. 28
      field/value.go
  9. 20
      handler/logrus/logger.go
  10. 10
      handler/otel/helpers.go
  11. 22
      handler/zap/logger.go
  12. 21
      logger.go
  13. 19
      logger_example_test.go
  14. 12
      middleware.go
  15. 32
      writter.go

4
.drone.yml

@ -3,7 +3,7 @@ name: default
steps: steps:
- name: test - name: test
image: golang:1.17.6 image: golang:1.17.8
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.44
commands: commands:
- golangci-lint run - golangci-lint run

7
.golangci.yml

@ -19,6 +19,12 @@ linters-settings:
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: tagliatelle:
case: case:
use-field-name: true use-field-name: true
@ -39,3 +45,4 @@ issues:
linters: linters:
- gomnd - gomnd
- exhaustivestruct - exhaustivestruct
- ireturn

6
entry/caller.go

@ -8,13 +8,13 @@ import (
func Caller(depth int, full bool) string { func Caller(depth int, full bool) string {
const offset = 4 const offset = 4
_, 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)
} }

6
entry/entry.go

@ -38,17 +38,17 @@ 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,
msg: "", msg: "",
} }
for _, opt := range opts { for _, opt := range opts {
opt(e) opt(entry)
} }
return e return entry
} }
// Entry slice field. // Entry slice field.

6
field/fields.go

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

2
field/fields_test.go

@ -8,6 +8,8 @@ import (
) )
func TestFields_Append(t *testing.T) { func TestFields_Append(t *testing.T) {
t.Parallel()
fields := field.Fields{field.Any("any", "value")} fields := field.Fields{field.Any("any", "value")}
fields = fields.Append(field.String("string", "value")) fields = fields.Append(field.String("string", "value"))

108
field/key.go

@ -8,113 +8,113 @@ type Key string
//nolint: gocyclo,funlen,cyclop //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{

28
field/value.go

@ -265,31 +265,45 @@ 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 {

20
handler/logrus/logger.go

@ -16,27 +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()
} }
entry := log.WithContext(ctx).WithFields(lrgFields) entry := log.WithContext(ctx).WithFields(lrgFields)
switch e.Level() { switch data.Level() {
case level.Emergency: case level.Emergency:
entry.Panic(e.Message()) entry.Panic(data.Message())
case level.Alert: case level.Alert:
entry.Fatal(e.Message()) entry.Fatal(data.Message())
case level.Critical, level.Error: case level.Critical, level.Error:
entry.Error(e.Message()) entry.Error(data.Message())
case level.Warning: case level.Warning:
entry.Warn(e.Message()) entry.Warn(data.Message())
case level.Notice, level.Info: case level.Notice, level.Info:
entry.Info(e.Message()) entry.Info(data.Message())
case level.Debug: case level.Debug:
entry.Debug(e.Message()) entry.Debug(data.Message())
} }
return 0, nil return 0, nil

10
handler/otel/helpers.go

@ -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([]attribute.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,
attribute.String(fieldSeverityText, lvl.String()), attribute.String(fieldSeverityText, lvl.String()),
attribute.Int(fieldSeverityNumber, int(lvl)), attribute.Int(fieldSeverityNumber, int(lvl)),
) )
for _, field := range e.Fields() { for _, field := range data.Fields() {
attrs = append(attrs, attribute.String(string(field.Key()), field.Value().String())) attrs = append(attrs, attribute.String(string(field.Key()), field.Value().String()))
} }
span.AddEvent(e.Message(), trace.WithAttributes(attrs...)) span.AddEvent(data.Message(), trace.WithAttributes(attrs...))
} }

22
handler/zap/logger.go

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

21
logger.go

@ -37,13 +37,13 @@ func (l Logger) Write(in []byte) (int, error) {
} }
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() writeEntry := entry.Get()
defer func() { defer func() {
entry.Put(e) entry.Put(writeEntry)
}() }()
return l(ctx, e.SetLevel(level).SetMessage(msg).Add(fields...)) return l(ctx, writeEntry.SetLevel(level).SetMessage(msg).Add(fields...))
} }
func (l Logger) logKVs(ctx context.Context, level level.Level, msg string, args ...interface{}) { func (l Logger) logKVs(ctx context.Context, level level.Level, msg string, args ...interface{}) {
@ -63,21 +63,21 @@ func (l Logger) logln(ctx context.Context, level level.Level, args ...interface{
} }
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()...) l.logKV(ctx, level.Critical, fmt.Sprint("Ignored key without a value.", args[i]), kvEntry.Fields()...)
break break
} }
@ -86,15 +86,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()...) l.logKV(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.
@ -316,6 +316,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

19
logger_example_test.go

@ -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.17.6","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.17.6 // msg="same error message" level=error go-version=go1.17.8
// msg="same info message" api-version=0.1 level=info go-version=go1.17.6 // 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.17.6 // 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.17.6 // Output: msg="same message" level=info client=http api=0.1.0 go=go1.17.8
} }
func ExamplePrint() { func ExamplePrint() {

12
middleware.go

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

32
writter.go

@ -15,19 +15,19 @@ 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, fmt.Errorf("enode err: %w", err) return 0, fmt.Errorf("enode err: %w", err)
} }
n, err := l.w.Write(b) n, err := logger.w.Write(b)
if err != nil { if err != nil {
return 0, fmt.Errorf("failed write: %w", err) return 0, fmt.Errorf("failed write: %w", err)
} }
@ -85,27 +85,27 @@ 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
} }
} }

Loading…
Cancel
Save