1 Commits

Author SHA1 Message Date
andrey
2628202ff1 add source with func name
Some checks failed
continuous-integration/drone/push Build is failing
continuous-integration/drone/pr Build is failing
2024-01-02 20:20:02 +03:00
31 changed files with 519 additions and 740 deletions

View File

@@ -5,7 +5,7 @@ name: logger
steps:
- name: test
image: golang:1.22.2
image: golang:1.21.5
volumes:
- name: deps
path: /go/src/mod
@@ -13,10 +13,85 @@ steps:
- go test
- name: golangci-lint
image: golangci/golangci-lint:v1.57
image: golangci/golangci-lint:v1.55
commands:
- golangci-lint run
volumes:
- name: deps
temp: {}
---
kind: pipeline
type: docker
name: otel
steps:
- name: test
image: golang:1.21.5
volumes:
- name: deps
path: /go/src/mod
commands:
- cd handler/otel
- go test
- name: golangci-lint
image: golangci/golangci-lint:v1.55
commands:
- cd handler/otel
- golangci-lint run
volumes:
- name: deps
temp: {}
---
kind: pipeline
type: docker
name: logrus
steps:
- name: test
image: golang:1.21.5
volumes:
- name: deps
path: /go/src/mod
commands:
- cd handler/logrus
- go test
- name: golangci-lint
image: golangci/golangci-lint:v1.55
commands:
- cd handler/logrus
- golangci-lint run
volumes:
- name: deps
temp: {}
---
kind: pipeline
type: docker
name: zap
steps:
- name: test
image: golang:1.21.5
volumes:
- name: deps
path: /go/src/mod
commands:
- cd handler/zap
- go test
- name: golangci-lint
image: golangci/golangci-lint:v1.55
commands:
- cd handler/zap
- golangci-lint run
volumes:
- name: deps
temp: {}

View File

@@ -1,26 +0,0 @@
name: Go Action
on: [push, pull_request]
jobs:
goaction:
runs-on: ubuntu-latest # Use a Gitea Actions runner label
steps:
- name: Check out repository code
uses: actions/checkout@v4 # Action to clone the repo
- name: Set up Go
uses: actions/setup-go@v5 # Action to install a specific Go version
with:
go-version: '1.25.5' # Specify your required Go version
- name: Run golangci-lint
uses: golangci/golangci-lint-action@v8 # Use the golangci-lint action
with:
version: v2.7.2 # Specify the linter version
# Optional: additional arguments
args: --verbose
- name: Run go test
run: go test ./...

View File

@@ -1,30 +1,9 @@
version: "2"
linters:
default: all
disable:
- wsl
- noinlineerr
settings:
depguard:
rules:
main:
allow:
- $gostd
- gitoa.ru
run:
timeout: 5m
funcorder:
constructor: false
recvcheck:
disable-builtin: false
exclusions:
- "*.String"
- "*.UnmarshalText"
- "*.UnmarshalJSON"
- "*.UnmarshalBinary"
linters-settings:
dupl:
threshold: 100
exhaustive:
default-signifies-exhaustive: true
funlen:
lines: 100
statements: 50
@@ -33,61 +12,61 @@ linters:
min-occurrences: 2
gocyclo:
min-complexity: 15
govet:
check-shadowing: true
lll:
line-length: 140
fieldalignment:
suggest-new: true
misspell:
locale: US
tagliatelle:
case:
rules:
avro: snake
bson: camel
json: snake
xml: camel
yaml: camel
use-field-name: true
exhaustive:
default-signifies-exhaustive: true
varnamelen:
min-name-length: 2
ignore-names:
- err
- "n"
- n
- i
- w
exclusions:
generated: lax
presets:
- comments
- common-false-positives
- legacy
- std-error-handling
tagliatelle:
case:
use-field-name: true
rules:
- linters:
json: snake
yaml: camel
xml: camel
bson: camel
avro: snake
linters:
enable-all: true
disable:
# deprecated
- interfacer
- structcheck
- varcheck
- golint
- deadcode
- scopelint
- exhaustivestruct
- ifshort
- nosnakecase
- maligned
- depguard # need configure
- nolintlint # use with space
issues:
# Excluding configuration per-path, per-linter, per-text and per-source
exclude-rules:
- path: _test\.go
linters:
- gomnd
- ireturn
- exhaustruct
- gochecknoglobals
- ireturn
- mnd
path: _test\.go
- linters:
- err113
- path: _example_test\.go
linters:
- lll
path: _example_test\.go
- linters:
- lll
- mnd
path: example/*
paths:
- third_party$
- builtin$
- examples$
formatters:
enable:
- gci
- gofmt
- gofumpt
- goimports
exclusions:
generated: lax
paths:
- third_party$
- builtin$
- examples$
- goerr113

View File

@@ -1,5 +1,5 @@
# log
![Build Status](https://gitoa.ru/go-4devs/log/actions/workflows/goaction.yml/badge.svg)
[![Build Status](https://drone.gitoa.ru/api/badges/go-4devs/log/status.svg)](https://drone.gitoa.ru/go-4devs/log)
[![Go Report Card](https://goreportcard.com/badge/gitoa.ru/go-4devs/log)](https://goreportcard.com/report/gitoa.ru/go-4devs/log)
[![GoDoc](https://godoc.org/gitoa.ru/go-4devs/log?status.svg)](http://godoc.org/gitoa.ru/go-4devs/log)

View File

@@ -69,10 +69,10 @@ func getMessage(iter int) string {
return _messages[iter%1000]
}
func fakeFmtArgs() []any {
func fakeFmtArgs() []interface{} {
// Need to keep this a function instead of a package-global var so that we
// pay the cast-to-interface{} penalty on each call.
return []any{
return []interface{}{
_tenInts[0],
_tenInts,
_tenStrings[0],
@@ -101,8 +101,8 @@ func fakeFields() []field.Field {
}
}
func fakeSugarFields() []any {
return []any{
func fakeSugarFields() []interface{} {
return []interface{}{
"int", _tenInts[0],
"ints", _tenInts,
"string", _tenStrings[0],
@@ -166,9 +166,7 @@ func BenchmarkDisabledAccumulatedContext(b *testing.B) {
b.Run("4devs/log.Context", func(b *testing.B) {
b.ResetTimer()
logger := NewLogger().With(log.GoVersion("goversion"))
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
logger.InfoKV(ctx, getMessage(0), fakeFields()...)

View File

@@ -8,7 +8,6 @@ import (
func Caller(depth int, full bool) string {
const offset = 3
_, file, line, has := runtime.Caller(depth + offset)
if !has {

View File

@@ -32,7 +32,7 @@ func WithMessage(msg string) Option {
}
}
func WithMessagef(format string, args ...any) Option {
func WithMessagef(format string, args ...interface{}) Option {
return func(e *Entry) {
e.format = format
e.args = args
@@ -50,7 +50,7 @@ func New(opts ...Option) *Entry {
fields: make(field.Fields, 0, defaultCap+1),
level: level.Debug,
format: "",
args: make([]any, 0, defaultCap+1),
args: make([]interface{}, 0, defaultCap+1),
}
for _, opt := range opts {
@@ -63,7 +63,7 @@ func New(opts ...Option) *Entry {
// Entry slice field.
type Entry struct {
format string
args []any
args []interface{}
level level.Level
fields field.Fields
}
@@ -133,7 +133,7 @@ func (e *Entry) SetMessage(msg string) *Entry {
return e
}
func (e *Entry) SetMessagef(format string, args ...any) *Entry {
func (e *Entry) SetMessagef(format string, args ...interface{}) *Entry {
if e == nil {
return New().SetMessagef(format, args...)
}
@@ -154,31 +154,10 @@ func (e *Entry) Add(fields ...field.Field) *Entry {
return e
}
func (e *Entry) AddAny(key string, value any) *Entry {
func (e *Entry) AddAny(key string, value interface{}) *Entry {
return e.Add(field.Any(key, value))
}
func (e *Entry) AddString(key, value string) *Entry {
return e.Add(field.String(key, value))
}
func (e *Entry) Replace(key string, value field.Value) *Entry {
has := false
e.fields.Fields(func(f field.Field) bool {
if f.Key == key {
f.Value = value
has = true
return false
}
return true
})
if !has {
e.AddAny(key, value)
}
return e
}

View File

@@ -4,7 +4,7 @@ import "sync"
//nolint:gochecknoglobals
var pool = sync.Pool{
New: func() any {
New: func() interface{} {
return New()
},
}

View File

@@ -1,38 +0,0 @@
package main
import (
"context"
"time"
"gitoa.ru/go-4devs/log"
"gitoa.ru/go-4devs/log/field"
)
func main() {
ctx := context.Background()
log.DebugKV(ctx, "debug message")
log.ErrKV(ctx, "error message")
log.Errf(ctx, "format error message:%v", 42)
log.Err(ctx, "error message", 42)
service(ctx, log.Log())
logger := log.New(log.WithJSONFormat()).With(log.WithSource(10, log.TrimPath), log.WithTime(log.KeyTime, time.RFC3339))
logger.AlertKV(ctx, "alert message new logger", field.String("string", "value"))
service(ctx, logger)
strLogger := log.New(log.WithFormat(log.FormatWithBracket(field.NewEncoderText()))).With(log.WithSource(10, log.TrimPath), log.WithTime(log.KeyTime, time.RFC3339))
strLogger.AlertKV(ctx, "alert message new txt logger", field.String("string", "value"))
service(ctx, strLogger)
}
func service(ctx context.Context, logger log.Logger) {
logger = logger.With(log.WithName("service"))
logger.WarnKV(ctx, "warn service message")
otherService(ctx, logger)
}
func otherService(ctx context.Context, logger log.Logger) {
logger = logger.With(log.WithName("other_service"))
logger.WarnKV(ctx, "warn other service message")
}

View File

@@ -5,7 +5,7 @@ import (
)
// Field create field.
func Field(key string, value any) field.Field {
func Field(key string, value interface{}) field.Field {
return field.Any(key, value)
}

View File

@@ -1,3 +1,4 @@
//nolint:gomnd
package field
import (
@@ -103,147 +104,7 @@ func (b BaseEncoder) AppendDelimiter(dst []byte, deli byte) []byte {
return append(dst, deli)
}
func (b BaseEncoder) AppendDuration(dst []byte, d time.Duration) []byte {
return b.AppendString(dst, d.String())
}
func (b BaseEncoder) AppendTime(dst []byte, t time.Time) []byte {
return b.AppendString(dst, t.Format(b.timeFormat))
}
func AppendString(dst []byte, in string) []byte {
if needsQuoting(in) {
return strconv.AppendQuote(dst, in)
}
return append(dst, in...)
}
//nolint:cyclop
func needsQuoting(in string) bool {
if len(in) == 0 {
return true
}
for i := 0; i < len(in); {
char := in[i]
if char < utf8.RuneSelf {
// Quote anything except a backslash that would need quoting in a
// JSON string, as well as space and '='
if char != '\\' && (char == ' ' || char == '=' || !safeSet[char]) {
return true
}
i++
continue
}
decodeRune, size := utf8.DecodeRuneInString(in[i:])
if decodeRune == utf8.RuneError || unicode.IsSpace(decodeRune) || !unicode.IsPrint(decodeRune) {
return true
}
i += size
}
return false
}
func (b BaseEncoder) AppendField(dst []byte, field Field) []byte {
prefix := ""
if len(dst) != 0 {
prew := dst[len(dst)-1]
if prew != '{' && prew != '.' {
prefix = string(b.group.deli)
}
}
return b.appendField(dst, field, prefix, b.delimeter)
}
func (b BaseEncoder) AppendKey(dst []byte, key string, prefix string) []byte {
if prefix != "" {
dst = append(dst, prefix...)
}
return b.AppendString(dst, key)
}
//nolint:mnd
func (b BaseEncoder) AppendComplex(dst []byte, c complex128) []byte {
cmplx := strconv.FormatComplex(c, 'g', -1, 128)
return b.AppendString(dst, cmplx)
}
func (b BaseEncoder) AppendFloat(dst []byte, f float64, bitSize int) []byte {
return strconv.AppendFloat(dst, f, 'g', -1, bitSize)
}
//nolint:mnd
func (b BaseEncoder) AppendUint(dst []byte, u uint64) []byte {
return strconv.AppendUint(dst, u, 10)
}
func (b BaseEncoder) AppendNull(dst []byte) []byte {
return append(dst, b.nullValue...)
}
//nolint:mnd
func (b BaseEncoder) AppendInt(dst []byte, val int64) []byte {
return strconv.AppendInt(dst, val, 10)
}
func (b BaseEncoder) AppendBool(dst []byte, val bool) []byte {
return strconv.AppendBool(dst, val)
}
func (b BaseEncoder) AppendGroup(dst []byte, fields []Field) []byte {
dst = append(dst, b.group.start)
dst = b.appendGroup(dst, fields, "")
return append(dst, b.group.end)
}
func (b BaseEncoder) AppendArray(dst []byte, in []Value) []byte {
dst = append(dst, b.array.start)
if len(in) > 0 {
dst = b.appendValue(dst, in[0], "", 0)
for _, value := range in[1:] {
dst = b.appendValue(append(dst, b.array.deli), value, "", 0)
}
}
return append(dst, b.array.end)
}
func (b BaseEncoder) AppendBytes(dst, in []byte) []byte {
dst = append(dst, '"')
dst = append(dst, in...)
return append(dst, '"')
}
func (b BaseEncoder) appendGroup(dst []byte, fields []Field, prefix string) []byte {
if len(fields) > 0 {
dst = b.appendField(dst, fields[0], ".", b.delimeter)
for _, field := range fields[1:] {
dst = b.appendField(append(dst, b.group.deli), field, prefix, b.delimeter)
}
}
return dst
}
func (b BaseEncoder) appendField(dst []byte, field Field, prefix string, deli byte) []byte {
dst = b.AppendKey(dst, field.Key, prefix)
return b.appendValue(dst, field.Value, field.Key+".", deli)
}
//nolint:mnd,gocyclo,cyclop
//nolint:gocyclo,cyclop
func (b BaseEncoder) appendValue(dst []byte, val Value, prefix string, deli byte) []byte {
switch val.Kind {
case KindGroup:
@@ -282,3 +143,139 @@ func (b BaseEncoder) appendValue(dst []byte, val Value, prefix string, deli byte
return b.DefaultValue(b.AppendDelimiter(dst, deli), b, val)
}
func (b BaseEncoder) AppendDuration(dst []byte, d time.Duration) []byte {
return b.AppendString(dst, d.String())
}
func (b BaseEncoder) AppendTime(dst []byte, t time.Time) []byte {
return b.AppendString(dst, t.Format(b.timeFormat))
}
func AppendString(dst []byte, in string) []byte {
if needsQuoting(in) {
return strconv.AppendQuote(dst, in)
}
return append(dst, in...)
}
//nolint:cyclop
func needsQuoting(in string) bool {
if len(in) == 0 {
return true
}
for i := 0; i < len(in); {
char := in[i]
if char < utf8.RuneSelf {
// Quote anything except a backslash that would need quoting in a
// JSON string, as well as space and '='
if char != '\\' && (char == ' ' || char == '=' || !safeSet[char]) {
return true
}
i++
continue
}
decodeRune, size := utf8.DecodeRuneInString(in[i:])
if decodeRune == utf8.RuneError || unicode.IsSpace(decodeRune) || !unicode.IsPrint(decodeRune) {
return true
}
i += size
}
return false
}
func (b BaseEncoder) AppendField(dst []byte, field Field) []byte {
prefix := ""
if len(dst) != 0 {
prew := dst[len(dst)-1]
if prew != '{' && prew != '.' {
prefix = string(b.group.deli)
}
}
return b.appendField(dst, field, prefix, b.delimeter)
}
func (b BaseEncoder) appendField(dst []byte, field Field, prefix string, deli byte) []byte {
dst = b.AppendKey(dst, field.Key, prefix)
return b.appendValue(dst, field.Value, field.Key+".", deli)
}
func (b BaseEncoder) AppendKey(dst []byte, key string, prefix string) []byte {
if prefix != "" {
dst = append(dst, prefix...)
}
return b.AppendString(dst, key)
}
func (b BaseEncoder) AppendComplex(dst []byte, c complex128) []byte {
cmplx := strconv.FormatComplex(c, 'g', -1, 128)
return b.AppendString(dst, cmplx)
}
func (b BaseEncoder) AppendFloat(dst []byte, f float64, bitSize int) []byte {
return strconv.AppendFloat(dst, f, 'g', -1, bitSize)
}
func (b BaseEncoder) AppendUint(dst []byte, u uint64) []byte {
return strconv.AppendUint(dst, u, 10)
}
func (b BaseEncoder) AppendNull(dst []byte) []byte {
return append(dst, b.nullValue...)
}
func (b BaseEncoder) AppendInt(dst []byte, val int64) []byte {
return strconv.AppendInt(dst, val, 10)
}
func (b BaseEncoder) AppendBool(dst []byte, val bool) []byte {
return strconv.AppendBool(dst, val)
}
func (b BaseEncoder) AppendGroup(dst []byte, fields []Field) []byte {
dst = append(dst, b.group.start)
dst = b.appendGroup(dst, fields, "")
return append(dst, b.group.end)
}
func (b BaseEncoder) appendGroup(dst []byte, fields []Field, prefix string) []byte {
if len(fields) > 0 {
dst = b.appendField(dst, fields[0], ".", b.delimeter)
for _, field := range fields[1:] {
dst = b.appendField(append(dst, b.group.deli), field, prefix, b.delimeter)
}
}
return dst
}
func (b BaseEncoder) AppendArray(dst []byte, in []Value) []byte {
dst = append(dst, b.array.start)
if len(in) > 0 {
dst = b.appendValue(dst, in[0], "", 0)
for _, value := range in[1:] {
dst = b.appendValue(append(dst, b.array.deli), value, "", 0)
}
}
return append(dst, b.array.end)
}
func (b BaseEncoder) AppendBytes(dst, in []byte) []byte {
dst = append(dst, '"')
dst = append(dst, in...)
return append(dst, '"')
}

View File

@@ -15,7 +15,6 @@ func TestEncoderJSONAppendField_string(t *testing.T) {
encode := field.NewEncoderJSON()
buf := buffer.New()
defer func() {
buf.Free()
}()

View File

@@ -2,7 +2,6 @@ package field
import (
"fmt"
"slices"
"time"
)
@@ -502,7 +501,3 @@ type Field struct {
func (f Field) String() string {
return fmt.Sprintf("%s=%+v", f.Key, f.Value)
}
func (f Field) IsKey(keys ...string) bool {
return slices.Contains(keys, f.Key)
}

View File

@@ -27,7 +27,7 @@ func StringpValue(value *string) Value {
return StringValue(*value)
}
// StringsValue returns a new Value for a string.
// StringpValue returns a new Value for a string.
func StringsValue(value []string) Value {
return Value{
Kind: KindArray,
@@ -115,7 +115,7 @@ func Uint8sValue(values []uint8) Value {
}
}
// Uint64pValue returns a Value for a []uint64.
// Uint64sValue returns a Value for a []uint64.
func Uint64pValue(v *uint64) Value {
if v == nil {
return NilValue()
@@ -145,7 +145,7 @@ func Int64sValue(value []int64) Value {
}
}
// Int64pValue returns a Value for an *int64.
// Int64sValue returns a Value for an *int64.
func Int64pValue(value *int64) Value {
if value == nil {
return NilValue()
@@ -159,7 +159,7 @@ func Float64Value(v float64) Value {
return Value{num: math.Float64bits(v), Kind: KindFloat64}
}
// Float64sValue returns a Value for a floating-points number.
// Float64Value returns a Value for a floating-points number.
func Float64sValue(values []float64) Value {
return Value{
Kind: KindArray,
@@ -175,7 +175,7 @@ func Float64sValue(values []float64) Value {
}
}
// Float64pValue returns a Value for a floating-points number.
// Float64Value returns a Value for a floating-points number.
func Float64pValue(v *float64) Value {
if v == nil {
return NilValue()
@@ -208,7 +208,7 @@ func Complex128Value(v complex128) Value {
}
}
// Complex128sValue returns a Value for a []complex128.
// Complex128Value returns a Value for a []complex128.
func Complex128sValue(values []complex128) Value {
return Value{
Kind: KindArray,
@@ -224,7 +224,7 @@ func Complex128sValue(values []complex128) Value {
}
}
// Complex128pValue returns a Value for a *complex128.
// Complex128Value returns a Value for a *complex128.
func Complex128pValue(v *complex128) Value {
if v == nil {
return NilValue()
@@ -275,7 +275,7 @@ func DurationValue(v time.Duration) Value {
return Value{inum: v.Nanoseconds(), Kind: KindDuration}
}
// DurationpValue returns a Value for a *time.Duration.
// DurationValue returns a Value for a *time.Duration.
func DurationpValue(v *time.Duration) Value {
if v == nil {
return NilValue()
@@ -284,7 +284,7 @@ func DurationpValue(v *time.Duration) Value {
return DurationValue(*v)
}
// DurationsValue returns a Value for a *time.Duration.
// DurationValue returns a Value for a *time.Duration.
func DurationsValue(values []time.Duration) Value {
return Value{
Kind: KindArray,
@@ -469,6 +469,41 @@ func (v Value) String() string {
return string(v.append(buf))
}
// append appends a text representation of v to dst.
// v is formatted as with fmt.Sprint.
//
//nolint:gomnd,cyclop
func (v Value) append(dst []byte) []byte {
switch v.Kind {
case KindString:
return append(dst, v.AsString()...)
case KindInt64:
return strconv.AppendInt(dst, v.inum, 10)
case KindUint64:
return strconv.AppendUint(dst, v.num, 10)
case KindFloat64:
return strconv.AppendFloat(dst, v.AsFloat64(), 'g', -1, 64)
case KindFloat32:
return strconv.AppendFloat(dst, float64(v.AsFloat32()), 'g', -1, 32)
case KindBool:
return strconv.AppendBool(dst, v.AsBool())
case KindDuration:
return append(dst, v.AsDuration().String()...)
case KindTime:
return append(dst, v.AsTime().String()...)
case KindError:
return append(dst, v.AsError().Error()...)
case KindGroup:
return fmt.Append(dst, v.AsGroup())
case KindClosure:
return fmt.Append(dst, v.Resolve())
case KindAny:
return fmt.Append(dst, v.any)
default:
return fmt.Appendf(dst, "%+v", v.any)
}
}
// nolint: gocyclo,cyclop
func (v Value) Any() any {
switch v.Kind {
@@ -532,7 +567,6 @@ func (v Value) AsUint64() uint64 {
return v.num
}
//nolint:gosec
func (v Value) AsFloat32() float32 {
return math.Float32frombits(uint32(v.num))
}
@@ -615,38 +649,3 @@ func (v Value) AsArray() Values {
return nil
}
}
// append appends a text representation of v to dst.
// v is formatted as with fmt.Sprint.
//
//nolint:mnd,cyclop
func (v Value) append(dst []byte) []byte {
switch v.Kind {
case KindString:
return append(dst, v.AsString()...)
case KindInt64:
return strconv.AppendInt(dst, v.inum, 10)
case KindUint64:
return strconv.AppendUint(dst, v.num, 10)
case KindFloat64:
return strconv.AppendFloat(dst, v.AsFloat64(), 'g', -1, 64)
case KindFloat32:
return strconv.AppendFloat(dst, float64(v.AsFloat32()), 'g', -1, 32)
case KindBool:
return strconv.AppendBool(dst, v.AsBool())
case KindDuration:
return append(dst, v.AsDuration().String()...)
case KindTime:
return append(dst, v.AsTime().String()...)
case KindError:
return append(dst, v.AsError().Error()...)
case KindGroup:
return fmt.Append(dst, v.AsGroup())
case KindClosure:
return fmt.Append(dst, v.Resolve())
case KindAny:
return fmt.Append(dst, v.any)
default:
return fmt.Appendf(dst, "%+v", v.any)
}
}

View File

@@ -3,7 +3,6 @@ package log
import (
"context"
"io"
"time"
"gitoa.ru/go-4devs/log/field"
"gitoa.ru/go-4devs/log/level"
@@ -11,7 +10,7 @@ import (
//nolint:gochecknoglobals
var global = With(New(),
WithTime(KeyTime, time.RFC3339),
WithSource(1),
WithLevel(KeyLevel, level.Debug),
WithExit(level.Alert),
WithPanic(level.Emergency),
@@ -28,112 +27,112 @@ func Log() Logger {
}
// Emerg log by emergency level.
func Emerg(ctx context.Context, args ...any) {
func Emerg(ctx context.Context, args ...interface{}) {
global.Emerg(ctx, args...)
}
// Alert log by alert level.
func Alert(ctx context.Context, args ...any) {
func Alert(ctx context.Context, args ...interface{}) {
global.Alert(ctx, args...)
}
// Crit log by critical level.
func Crit(ctx context.Context, args ...any) {
func Crit(ctx context.Context, args ...interface{}) {
global.Crit(ctx, args...)
}
// Err log by error level.
func Err(ctx context.Context, args ...any) {
func Err(ctx context.Context, args ...interface{}) {
global.Err(ctx, args...)
}
// Warn logs by warning level.
func Warn(ctx context.Context, args ...any) {
func Warn(ctx context.Context, args ...interface{}) {
global.Warn(ctx, args...)
}
// Notice log by notice level.
func Notice(ctx context.Context, args ...any) {
func Notice(ctx context.Context, args ...interface{}) {
global.Notice(ctx, args...)
}
// Info log by info level.
func Info(ctx context.Context, args ...any) {
func Info(ctx context.Context, args ...interface{}) {
global.Info(ctx, args...)
}
// Debug log by debug level.
func Debug(ctx context.Context, args ...any) {
func Debug(ctx context.Context, args ...interface{}) {
global.Debug(ctx, args...)
}
// Print log by info level and arguments.
func Print(args ...any) {
func Print(args ...interface{}) {
global.Print(args...)
}
// Fatal log by alert level and arguments.
func Fatal(args ...any) {
func Fatal(args ...interface{}) {
global.Fatal(args...)
}
// Panic log by emergency level and arguments.
func Panic(args ...any) {
func Panic(args ...interface{}) {
global.Panic(args...)
}
// Println log by info level and arguments.
func Println(args ...any) {
func Println(args ...interface{}) {
global.Println(args...)
}
// Fatalln log by alert level and arguments.
func Fatalln(args ...any) {
func Fatalln(args ...interface{}) {
global.Fatalln(args...)
}
// Panicln log by emergency level and arguments.
func Panicln(args ...any) {
func Panicln(args ...interface{}) {
global.Panicln(args...)
}
// EmergKVs sugared log by emergency level and key-values.
func EmergKVs(ctx context.Context, msg string, args ...any) {
func EmergKVs(ctx context.Context, msg string, args ...interface{}) {
global.EmergKVs(ctx, msg, args...)
}
// AlertKVs sugared log by alert level and key-values.
func AlertKVs(ctx context.Context, msg string, args ...any) {
func AlertKVs(ctx context.Context, msg string, args ...interface{}) {
global.AlertKVs(ctx, msg, args...)
}
// CritKVs sugared log by critcal level and key-values.
func CritKVs(ctx context.Context, msg string, args ...any) {
func CritKVs(ctx context.Context, msg string, args ...interface{}) {
global.CritKVs(ctx, msg, args...)
}
// ErrKVs sugared log by error level and key-values.
func ErrKVs(ctx context.Context, msg string, args ...any) {
func ErrKVs(ctx context.Context, msg string, args ...interface{}) {
global.ErrKVs(ctx, msg, args...)
}
// WarnKVs sugared log by warning level and key-values.
func WarnKVs(ctx context.Context, msg string, args ...any) {
func WarnKVs(ctx context.Context, msg string, args ...interface{}) {
global.WarnKVs(ctx, msg, args...)
}
// NoticeKVs sugared log by notice level and key-values.
func NoticeKVs(ctx context.Context, msg string, args ...any) {
func NoticeKVs(ctx context.Context, msg string, args ...interface{}) {
global.NoticeKVs(ctx, msg, args...)
}
// InfoKVs sugared log by info level and key-values.
func InfoKVs(ctx context.Context, msg string, args ...any) {
func InfoKVs(ctx context.Context, msg string, args ...interface{}) {
global.InfoKVs(ctx, msg, args...)
}
// DebugKVs sugared log by debug level and key-values.
func DebugKVs(ctx context.Context, msg string, args ...any) {
func DebugKVs(ctx context.Context, msg string, args ...interface{}) {
global.DebugKVs(ctx, msg, args...)
}
@@ -178,57 +177,57 @@ func DebugKV(ctx context.Context, msg string, args ...field.Field) {
}
// Emergf log by emergency level by format and arguments.
func Emergf(ctx context.Context, format string, args ...any) {
func Emergf(ctx context.Context, format string, args ...interface{}) {
global.Emergf(ctx, format, args...)
}
// Alertf log by alert level by format and arguments.
func Alertf(ctx context.Context, format string, args ...any) {
func Alertf(ctx context.Context, format string, args ...interface{}) {
global.Alertf(ctx, format, args...)
}
// Critf log by critical level by format and arguments.
func Critf(ctx context.Context, format string, args ...any) {
func Critf(ctx context.Context, format string, args ...interface{}) {
global.Critf(ctx, format, args...)
}
// Errf log by error level by format and arguments.
func Errf(ctx context.Context, format string, args ...any) {
func Errf(ctx context.Context, format string, args ...interface{}) {
global.Errf(ctx, format, args...)
}
// Warnf log by warning level by format and arguments.
func Warnf(ctx context.Context, format string, args ...any) {
func Warnf(ctx context.Context, format string, args ...interface{}) {
global.Warnf(ctx, format, args...)
}
// Noticef log by notice level by format and arguments.
func Noticef(ctx context.Context, format string, args ...any) {
func Noticef(ctx context.Context, format string, args ...interface{}) {
global.Noticef(ctx, format, args...)
}
// Infof log by info level by format and arguments.
func Infof(ctx context.Context, format string, args ...any) {
func Infof(ctx context.Context, format string, args ...interface{}) {
global.Noticef(ctx, format, args...)
}
// Debugf log by debug level by format and arguments.
func Debugf(ctx context.Context, format string, args ...any) {
func Debugf(ctx context.Context, format string, args ...interface{}) {
global.Debugf(ctx, format, args...)
}
// Printf log by info level by format and arguments without context.
func Printf(format string, args ...any) {
func Printf(format string, args ...interface{}) {
global.Printf(format, args...)
}
// Fatalf log by alert level by format and arguments without context.
func Fatalf(format string, args ...any) {
func Fatalf(format string, args ...interface{}) {
global.Fatalf(format, args...)
}
// Panicf log by emergency level and arguments without context.
func Panicf(format string, args ...any) {
func Panicf(format string, args ...interface{}) {
global.Panicf(format, args...)
}

View File

@@ -2,15 +2,14 @@ package log_test
import (
"context"
"path/filepath"
"gitoa.ru/go-4devs/log"
"gitoa.ru/go-4devs/log/level"
)
func ExampleDebug() {
logger := log.New(log.WithStdout()).With(
log.WithSource(2, filepath.Base),
logger := log.With(log.New(log.WithStdout()),
log.WithSource(2),
log.WithLevel(log.KeyLevel, level.Debug),
log.WithExit(level.Alert),
log.WithPanic(level.Emergency),
@@ -21,5 +20,5 @@ func ExampleDebug() {
ctx := context.Background()
log.Debug(ctx, "debug message")
// Output:
// msg="debug message" source=global_example_test.go:22 level=debug
// msg="debug message" source=global_example_test.go:21 level=debug
}

2
go.mod
View File

@@ -1,3 +1,3 @@
module gitoa.ru/go-4devs/log
go 1.22
go 1.20

View File

@@ -11,13 +11,11 @@ import (
)
// Standard create new standart logrus handler.
// Deprecated: delete after 0.7.0
func Standard() log.Logger {
return New(logrus.StandardLogger())
}
// New create new logrus handler.
// Deprecated: delete after 0.7.0
func New(log *logrus.Logger) log.Logger {
return func(ctx context.Context, data *entry.Entry) (int, error) {
lrgFields := make(logrus.Fields, data.Fields().Len())

View File

@@ -7,7 +7,6 @@ import (
"gitoa.ru/go-4devs/log/entry"
)
// Deprecated: delete after 0.7.0
func New() log.Logger {
return func(ctx context.Context, e *entry.Entry) (int, error) {
addEvent(ctx, e)

View File

@@ -7,7 +7,6 @@ import (
"gitoa.ru/go-4devs/log/entry"
)
// Deprecated: delete after 0.7.0
func Middleware() log.Middleware {
return func(ctx context.Context, e *entry.Entry, handler log.Logger) (int, error) {
addEvent(ctx, e)

View File

@@ -10,17 +10,14 @@ import (
"go.uber.org/zap"
)
// Deprecated: delete after 0.7.0
func Nop() log.Logger {
return New(zap.NewNop())
}
// Deprecated: delete after 0.7.0
func Example(options ...zap.Option) log.Logger {
return New(zap.NewExample(options...))
}
// Deprecated: delete after 0.7.0
func Production(options ...zap.Option) log.Logger {
z, err := zap.NewProduction(options...)
if err != nil {
@@ -30,7 +27,6 @@ func Production(options ...zap.Option) log.Logger {
return New(z)
}
// Deprecated: delete after 0.7.0
func Development(options ...zap.Option) log.Logger {
z, err := zap.NewDevelopment(options...)
if err != nil {

View File

@@ -51,9 +51,7 @@ func TestUnmarshalJSON(t *testing.T) {
for expect, actuals := range levels {
for _, actual := range actuals {
var level level.Level
err := level.UnmarshalJSON([]byte(actual))
if err != nil {
if err := level.UnmarshalJSON([]byte(actual)); err != nil {
t.Errorf("%s got err: %s", level, err)
continue

177
logger.go
View File

@@ -28,118 +28,172 @@ func (l Logger) Write(in []byte) (int, error) {
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) {
data := entry.Get()
defer func() {
entry.Put(data)
}()
return l(ctx, data.SetLevel(level).SetMessage(msg).Add(fields...))
}
func (l Logger) writef(ctx context.Context, level level.Level, format string, args ...interface{}) (int, error) {
data := entry.Get()
defer func() {
entry.Put(data)
}()
return l(ctx, data.SetLevel(level).SetMessagef(format, args...))
}
func (l Logger) kv(_ context.Context, args ...interface{}) field.Fields {
kvEntry := entry.Get()
defer func() {
entry.Put(kvEntry)
}()
for i := 0; i < len(args); i++ {
if f, ok := args[i].(field.Field); ok {
kvEntry = kvEntry.Add(f)
continue
}
if i == len(args)-1 {
kvEntry = kvEntry.AddAny(badKey, args[i])
break
}
key, val := args[i], args[i+1]
if keyStr, ok := key.(string); ok {
kvEntry = kvEntry.AddAny(keyStr, val)
i++
continue
}
kvEntry = kvEntry.AddAny(badKey, args[i])
}
return kvEntry.Fields()
}
// With adds middlewares to logger.
func (l Logger) With(mw ...Middleware) Logger {
return With(l, mw...)
}
// Emerg log by emergency level.
func (l Logger) Emerg(ctx context.Context, args ...any) {
func (l Logger) Emerg(ctx context.Context, args ...interface{}) {
writeOutput(l.writef(ctx, level.Emergency, "", args...))
}
// Alert log by alert level.
func (l Logger) Alert(ctx context.Context, args ...any) {
func (l Logger) Alert(ctx context.Context, args ...interface{}) {
writeOutput(l.writef(ctx, level.Alert, "", args...))
}
// Crit log by critical level.
func (l Logger) Crit(ctx context.Context, args ...any) {
func (l Logger) Crit(ctx context.Context, args ...interface{}) {
writeOutput(l.writef(ctx, level.Critical, "", args...))
}
// Err log by error level.
func (l Logger) Err(ctx context.Context, args ...any) {
func (l Logger) Err(ctx context.Context, args ...interface{}) {
writeOutput(l.writef(ctx, level.Error, "", args...))
}
// Warn log by warning level.
func (l Logger) Warn(ctx context.Context, args ...any) {
func (l Logger) Warn(ctx context.Context, args ...interface{}) {
writeOutput(l.writef(ctx, level.Warning, "", args...))
}
// Notice log by notice level.
func (l Logger) Notice(ctx context.Context, args ...any) {
func (l Logger) Notice(ctx context.Context, args ...interface{}) {
writeOutput(l.writef(ctx, level.Notice, "", args...))
}
// Info log by info level.
func (l Logger) Info(ctx context.Context, args ...any) {
func (l Logger) Info(ctx context.Context, args ...interface{}) {
writeOutput(l.writef(ctx, level.Info, "", args...))
}
// Debug log by debug level.
func (l Logger) Debug(ctx context.Context, args ...any) {
func (l Logger) Debug(ctx context.Context, args ...interface{}) {
writeOutput(l.writef(ctx, level.Debug, "", args...))
}
// Print log by info level and arguments.
func (l Logger) Print(args ...any) {
func (l Logger) Print(args ...interface{}) {
writeOutput(l.writef(context.Background(), level.Info, "", args...))
}
// Fatal log by alert level and arguments.
func (l Logger) Fatal(args ...any) {
func (l Logger) Fatal(args ...interface{}) {
writeOutput(l.writef(context.Background(), level.Alert, "", args...))
}
// Panic log by emergency level and arguments.
func (l Logger) Panic(args ...any) {
func (l Logger) Panic(args ...interface{}) {
writeOutput(l.writef(context.Background(), level.Emergency, "", args...))
}
// Println log by info level and arguments.
func (l Logger) Println(args ...any) {
func (l Logger) Println(args ...interface{}) {
writeOutput(l.write(context.Background(), level.Info, fmt.Sprintln(args...)))
}
// Fatalln log by alert level and arguments.
func (l Logger) Fatalln(args ...any) {
func (l Logger) Fatalln(args ...interface{}) {
writeOutput(l.write(context.Background(), level.Alert, fmt.Sprintln(args...)))
}
// Panicln log by emergency level and arguments.
func (l Logger) Panicln(args ...any) {
func (l Logger) Panicln(args ...interface{}) {
writeOutput(l.write(context.Background(), level.Emergency, fmt.Sprintln(args...)))
}
// EmergKVs sugared log by emergency level and key-values.
func (l Logger) EmergKVs(ctx context.Context, msg string, args ...any) {
func (l Logger) EmergKVs(ctx context.Context, msg string, args ...interface{}) {
writeOutput(l.write(ctx, level.Emergency, msg, l.kv(ctx, args...)...))
}
// AlertKVs sugared log by alert level and key-values.
func (l Logger) AlertKVs(ctx context.Context, msg string, args ...any) {
func (l Logger) AlertKVs(ctx context.Context, msg string, args ...interface{}) {
writeOutput(l.write(ctx, level.Alert, msg, l.kv(ctx, args...)...))
}
// CritKVs sugared log by critcal level and key-values.
func (l Logger) CritKVs(ctx context.Context, msg string, args ...any) {
func (l Logger) CritKVs(ctx context.Context, msg string, args ...interface{}) {
writeOutput(l.write(ctx, level.Critical, msg, l.kv(ctx, args...)...))
}
// ErrKVs sugared log by error level and key-values.
func (l Logger) ErrKVs(ctx context.Context, msg string, args ...any) {
func (l Logger) ErrKVs(ctx context.Context, msg string, args ...interface{}) {
writeOutput(l.write(ctx, level.Error, msg, l.kv(ctx, args...)...))
}
// WarnKVs sugared log by warning level and key-values.
func (l Logger) WarnKVs(ctx context.Context, msg string, args ...any) {
func (l Logger) WarnKVs(ctx context.Context, msg string, args ...interface{}) {
writeOutput(l.write(ctx, level.Warning, msg, l.kv(ctx, args...)...))
}
// NoticeKVs sugared log by notice level and key-values.
func (l Logger) NoticeKVs(ctx context.Context, msg string, args ...any) {
func (l Logger) NoticeKVs(ctx context.Context, msg string, args ...interface{}) {
writeOutput(l.write(ctx, level.Notice, msg, l.kv(ctx, args...)...))
}
// InfoKVs sugared log by info level and key-values.
func (l Logger) InfoKVs(ctx context.Context, msg string, args ...any) {
func (l Logger) InfoKVs(ctx context.Context, msg string, args ...interface{}) {
writeOutput(l.write(ctx, level.Info, msg, l.kv(ctx, args...)...))
}
// DebugKVs sugared log by debug level and key-values.
func (l Logger) DebugKVs(ctx context.Context, msg string, args ...any) {
func (l Logger) DebugKVs(ctx context.Context, msg string, args ...interface{}) {
writeOutput(l.write(ctx, level.Debug, msg, l.kv(ctx, args...)...))
}
@@ -184,57 +238,57 @@ func (l Logger) DebugKV(ctx context.Context, msg string, args ...field.Field) {
}
// Emergf log by emergency level by format and arguments.
func (l Logger) Emergf(ctx context.Context, format string, args ...any) {
func (l Logger) Emergf(ctx context.Context, format string, args ...interface{}) {
writeOutput(l.writef(ctx, level.Emergency, format, args...))
}
// Alertf log by alert level by format and arguments.
func (l Logger) Alertf(ctx context.Context, format string, args ...any) {
func (l Logger) Alertf(ctx context.Context, format string, args ...interface{}) {
writeOutput(l.writef(ctx, level.Alert, format, args...))
}
// Critf log by critical level by format and arguments.
func (l Logger) Critf(ctx context.Context, format string, args ...any) {
func (l Logger) Critf(ctx context.Context, format string, args ...interface{}) {
writeOutput(l.writef(ctx, level.Critical, format, args...))
}
// Errf log by error level by format and arguments.
func (l Logger) Errf(ctx context.Context, format string, args ...any) {
func (l Logger) Errf(ctx context.Context, format string, args ...interface{}) {
writeOutput(l.writef(ctx, level.Error, format, args...))
}
// Warnf log by warning level by format and arguments.
func (l Logger) Warnf(ctx context.Context, format string, args ...any) {
func (l Logger) Warnf(ctx context.Context, format string, args ...interface{}) {
writeOutput(l.writef(ctx, level.Warning, format, args...))
}
// Noticef log by notice level by format and arguments.
func (l Logger) Noticef(ctx context.Context, format string, args ...any) {
func (l Logger) Noticef(ctx context.Context, format string, args ...interface{}) {
writeOutput(l.writef(ctx, level.Notice, format, args...))
}
// Infof log by info level by format and arguments.
func (l Logger) Infof(ctx context.Context, format string, args ...any) {
func (l Logger) Infof(ctx context.Context, format string, args ...interface{}) {
writeOutput(l.writef(ctx, level.Info, format, args...))
}
// Debugf log by debug level by format and arguments.
func (l Logger) Debugf(ctx context.Context, format string, args ...any) {
func (l Logger) Debugf(ctx context.Context, format string, args ...interface{}) {
writeOutput(l.writef(ctx, level.Debug, format, args...))
}
// Printf log by info level by format and arguments without context.
func (l Logger) Printf(format string, args ...any) {
func (l Logger) Printf(format string, args ...interface{}) {
writeOutput(l.writef(context.Background(), level.Info, format, args...))
}
// Fatalf log by alert level by format and arguments without context.
func (l Logger) Fatalf(format string, args ...any) {
func (l Logger) Fatalf(format string, args ...interface{}) {
writeOutput(l.writef(context.Background(), level.Alert, format, args...))
}
// Panicf log by emergency level and arguments without context.
func (l Logger) Panicf(format string, args ...any) {
func (l Logger) Panicf(format string, args ...interface{}) {
writeOutput(l.writef(context.Background(), level.Emergency, format, args...))
}
@@ -247,67 +301,12 @@ func (l Logger) Writer(ctx context.Context, level level.Level, fields ...field.F
}
}
func (l Logger) kv(_ context.Context, args ...any) field.Fields {
kvEntry := entry.Get()
defer func() {
entry.Put(kvEntry)
}()
for i := 0; i < len(args); i++ {
if f, ok := args[i].(field.Field); ok {
kvEntry = kvEntry.Add(f)
continue
}
if i == len(args)-1 {
kvEntry = kvEntry.AddAny(badKey, args[i])
break
}
key, val := args[i], args[i+1]
if keyStr, ok := key.(string); ok {
kvEntry = kvEntry.AddAny(keyStr, val)
i++
continue
}
kvEntry = kvEntry.AddAny(badKey, args[i])
}
return kvEntry.Fields()
}
func (l Logger) write(ctx context.Context, level level.Level, msg string, fields ...field.Field) (int, error) {
data := entry.Get()
defer func() {
entry.Put(data)
}()
return l(ctx, data.SetLevel(level).SetMessage(msg).Add(fields...))
}
func (l Logger) writef(ctx context.Context, level level.Level, format string, args ...any) (int, error) {
data := entry.Get()
defer func() {
entry.Put(data)
}()
return l(ctx, data.SetLevel(level).SetMessagef(format, args...))
}
//nolint:containedctx
type writer struct {
Logger
ctx context.Context
level level.Level
fields []field.Field
Logger
}
func (w writer) WithLevel(level level.Level) writer {

View File

@@ -1,23 +1,22 @@
package log_test
import (
"path/filepath"
"gitoa.ru/go-4devs/log"
"gitoa.ru/go-4devs/log/level"
)
func ExampleNew_withCaller() {
logger := log.New(log.WithStdout()).With(
log.WithLevel(log.KeyLevel, level.Debug),
log.WithSource(3, filepath.Base),
logger := log.With(
log.New(log.WithStdout()),
log.WithLevel("level", level.Debug),
log.WithSource(3),
)
logger.Err(ctx, "same error message")
logger.InfoKVs(ctx, "same info message", "api-version", 0.1)
_, _ = logger.Write([]byte("same write message"))
// Output:
// msg="same error message" level=error source=logger_example_caller_test.go:15
// msg="same info message" api-version=0.1 level=info source=logger_example_caller_test.go:16
// msg="same write message" level=info source=logger_example_caller_test.go:17
// msg="same error message" level=error source=logger_example_caller_test.go:14
// msg="same info message" api-version=0.1 level=info source=logger_example_caller_test.go:15
// msg="same write message" level=info source=logger_example_caller_test.go:16
}

View File

@@ -47,19 +47,19 @@ func ExampleNew_errf() {
}
func ExampleNew_debugKV() {
logger := log.New(log.WithStdout()).With(log.WithLevel(log.KeyLevel, level.Debug))
logger := log.New(log.WithStdout()).With(log.WithLevel("level", level.Debug))
logger.DebugKVs(ctx, "same message", "error", os.ErrNotExist)
// Output: msg="same message" error="file does not exist" level=debug
}
func ExampleNew_level() {
logger := log.New(log.WithStdout()).With(log.WithLevel(log.KeyLevel, level.Error))
logger := log.New(log.WithStdout()).With(log.WithLevel("level", level.Error))
logger.Err(ctx, "same error message")
// Output: msg="same error message" level=error
}
func ExampleNew_level_info() {
logger := log.New(log.WithStdout()).With(log.WithLevel(log.KeyLevel, level.Error))
logger := log.New(log.WithStdout()).With(log.WithLevel("level", level.Error))
logger.Info(ctx, "same message")
// Output:
}
@@ -213,13 +213,13 @@ func ExampleNew_jsonFormat() {
logger.Err(ctx, "same error message")
logger.WarnKVs(ctx, "same warn message", "obj", Obj{Name: "obj name"})
// Output:
// {"msg":"same error message","level":"error","go-version":"go1.25.5"}
// {"msg":"same warn message","obj":{"Name":"obj name","IsEnable":false},"level":"warning","go-version":"go1.25.5"}
// {"msg":"same error message","level":"error","go-version":"go1.21.5"}
// {"msg":"same warn message","obj":{"Name":"obj name","IsEnable":false},"level":"warning","go-version":"go1.21.5"}
}
func ExampleNew_textEncoding() {
logger := log.New(log.WithStdout()).
With(
logger := log.With(
log.New(log.WithStdout()),
log.WithLevel(log.KeyLevel, level.Debug),
log.GoVersion("go-version"),
)
@@ -227,8 +227,8 @@ func ExampleNew_textEncoding() {
logger.InfoKVs(ctx, "same info message", "api-version", 0.1, "obj", Obj{Name: "text value", IsEnable: true})
// Output:
// msg="same error message" level=error go-version=go1.25.5
// msg="same info message" api-version=0.1 obj={Name:text value IsEnable:true} level=info go-version=go1.25.5
// msg="same error message" level=error go-version=go1.21.5
// msg="same info message" api-version=0.1 obj={Name:text value IsEnable:true} level=info go-version=go1.21.5
}
type ctxKey string
@@ -238,33 +238,28 @@ func (c ctxKey) String() string {
}
func levelInfo(ctx context.Context, entry *entry.Entry, handler log.Logger) (int, error) {
return handler(ctx, entry.Add(field.String(log.KeyLevel, entry.Level().String())))
return handler(ctx, entry.Add(field.String("level", entry.Level().String())))
}
func ExampleWith() {
var requestID ctxKey = "requestID"
vctx := context.WithValue(ctx, requestID, "6a5fa048-7181-11ea-bc55-0242ac130003")
logger := log.New(log.WithStdout()).With(
levelInfo,
log.WithContextValue(requestID),
log.KeyValue("api", "0.1.0"),
log.GoVersion("go"),
logger := log.With(
log.New(log.WithStdout()),
levelInfo, log.WithContextValue(requestID), log.KeyValue("api", "0.1.0"), log.GoVersion("go"),
)
logger.Info(vctx, "same message")
// Output: msg="same message" level=info requestID=6a5fa048-7181-11ea-bc55-0242ac130003 api=0.1.0 go=go1.25.5
// Output: msg="same message" level=info requestID=6a5fa048-7181-11ea-bc55-0242ac130003 api=0.1.0 go=go1.21.5
}
func ExampleLogger_Print() {
logger := log.New(log.WithStdout()).With(
levelInfo,
log.KeyValue("client", "http"),
log.KeyValue("api", "0.1.0"),
log.GoVersion("go"),
logger := log.With(
log.New(log.WithStdout()),
levelInfo, log.KeyValue("client", "http"), log.KeyValue("api", "0.1.0"), log.GoVersion("go"),
)
logger.Print("same message")
// Output: msg="same message" level=info client=http api=0.1.0 go=go1.25.5
// Output: msg="same message" level=info client=http api=0.1.0 go=go1.21.5
}
func ExamplePrint() {
@@ -282,7 +277,7 @@ func Example_fieldClosureFn() {
return d
})
log := log.New(log.WithStdout()).With(log.WithLevel(log.KeyLevel, level.Info))
log := log.With(log.New(log.WithStdout()), log.WithLevel("level", level.Info))
log.DebugKVs(ctx, "debug message", "data", closure)
log.ErrKVs(ctx, "error message", "err", closure)
@@ -294,9 +289,7 @@ func Example_fieldClosureFn() {
}
func Example_withGroup() {
log := log.New(log.WithStdout()).With(
log.WithLevel(log.KeyLevel, level.Info),
)
log := log.With(log.New(log.WithStdout()), log.WithLevel(log.KeyLevel, level.Info))
log.ErrKVs(ctx, "error message",
field.Groups("grous_field",

View File

@@ -27,7 +27,7 @@ func TestFields(t *testing.T) {
ctx := context.Background()
buf := &bytes.Buffer{}
log := log.New(log.WithWriter(buf)).
With(log.WithLevel(log.KeyLevel, level.Info))
With(log.WithLevel("level", level.Info))
success := "msg=message err=\"file already exists\" version=0.1.0 obj={id:uid} closure=\"some closure data\" level=info\n"
log.InfoKVs(ctx, "message",
@@ -65,7 +65,7 @@ func TestWriter(t *testing.T) {
success := "msg=\"info message\" err=\"file already exists\" requestID=6a5fa048-7181-11ea-bc55-0242ac1311113 level=info\n"
buf := &bytes.Buffer{}
logger := log.New(log.WithWriter(buf)).With(log.WithContextValue(requestID), log.WithLevel(log.KeyLevel, level.Info))
logger := log.New(log.WithWriter(buf)).With(log.WithContextValue(requestID), log.WithLevel("level", level.Info))
_, _ = logger.Writer(
context.WithValue(ctx, requestID, "6a5fa048-7181-11ea-bc55-0242ac1311113"),
@@ -91,7 +91,7 @@ func TestLogger(t *testing.T) {
ctx := context.Background()
buf := &bytes.Buffer{}
logger := log.New(log.WithWriter(buf)).With(log.WithContextValue(requestID), log.WithLevel(log.KeyLevel, level.Info))
logger := log.New(log.WithWriter(buf)).With(log.WithContextValue(requestID), log.WithLevel("level", level.Info))
_, err := logger(ctx, nil)
if err != nil {

View File

@@ -38,7 +38,6 @@ func With(logger Logger, mw ...Middleware) Logger {
if curI == lastI {
return logger(currentCtx, currentEntry)
}
curI++
n, err := mw[curI](currentCtx, currentEntry, chainHandler)
curI--
@@ -62,7 +61,7 @@ func WithLevel(key string, lvl level.Level) Middleware {
}
// KeyValue add field by const key value.
func KeyValue(key string, value any) Middleware {
func KeyValue(key string, value interface{}) Middleware {
return func(ctx context.Context, e *entry.Entry, handler Logger) (int, error) {
return handler(ctx, e.AddAny(key, value))
}
@@ -75,7 +74,7 @@ func GoVersion(key string) Middleware {
}
}
// WithContextValue add field by context key.
// WithContext add field by context key.
func WithContextValue(keys ...fmt.Stringer) Middleware {
return func(ctx context.Context, e *entry.Entry, handler Logger) (int, error) {
for _, key := range keys {
@@ -86,14 +85,7 @@ func WithContextValue(keys ...fmt.Stringer) Middleware {
}
}
func WithName(name string) Middleware {
return func(ctx context.Context, data *entry.Entry, handler Logger) (int, error) {
return handler(ctx, data.Replace(KeyName, field.StringValue(name)))
}
}
// WithCaller adds called file.
//
// Deprecated: use WithSource.
func WithCaller(key string, depth int, full bool) Middleware {
const offset = 2

View File

@@ -5,73 +5,28 @@ import (
"fmt"
"path/filepath"
"runtime"
"strings"
"gitoa.ru/go-4devs/log/entry"
"gitoa.ru/go-4devs/log/field"
)
func WithSource(items int, trimPath func(string) string) Middleware {
const (
skip = 4
funcPrefix = "gitoa.ru/go-4devs/log.Logger"
skipHelper = "gitoa.ru/go-4devs/log."
)
items += skip
func WithSource(depth int) Middleware {
const offset = 3
return func(ctx context.Context, data *entry.Entry, handler Logger) (int, error) {
pc := make([]uintptr, items)
n := runtime.Callers(skip, pc)
if n == 0 {
return handler(ctx, data.Add(errSourceField(skip, items)))
pc, file, line, has := runtime.Caller(depth + offset)
if !has {
return handler(ctx, data.AddAny(KeyLevel, field.NilValue()))
}
pc = pc[:n] // pass only valid pcs to runtime.CallersFrames
frames := runtime.CallersFrames(pc)
prew := false
for {
frame, more := frames.Next()
has := strings.HasPrefix(frame.Function, funcPrefix)
if !has && prew {
if strings.HasPrefix(frame.Function, skipHelper) {
continue
}
fnc := runtime.FuncForPC(pc)
return handler(ctx, data.AddAny(KeySource, Source{
Func: filepath.Base(frame.Function),
Line: frame.Line,
File: trimPath(frame.File),
Func: filepath.Base(fnc.Name()),
File: filepath.Base(file),
Line: line,
}))
}
prew = has
if !more {
break
}
}
return handler(ctx, data.Add(errSourceField(skip, items)))
}
}
func TrimPath(file string) string {
idx := strings.LastIndexByte(file, '/')
if idx == -1 {
return filepath.Base(file)
}
// Find the penultimate separator.
idx = strings.LastIndexByte(file[:idx], '/')
if idx == -1 {
return filepath.Base(file)
}
return file[idx+1:]
}
// Source describes the location of a line of source code.
@@ -82,13 +37,9 @@ type Source struct {
}
func (l Source) MarshalText() ([]byte, error) {
return fmt.Appendf(nil, "%s:%d", l.File, l.Line), nil
return []byte(fmt.Sprintf("%s:%d", l.File, l.Line)), nil
}
func (l Source) MarshalJSON() ([]byte, error) {
return fmt.Appendf([]byte{}, `{"file":"%s","line":%d,"func":"%s"}`, l.File, l.Line, l.Func), nil
}
func errSourceField(skip, mframe int) field.Field {
return field.String(KeySource, fmt.Sprintf("source not found by frames[%d:%d]", skip, mframe))
}

View File

@@ -2,25 +2,24 @@ package log_test
import (
"context"
"path/filepath"
"gitoa.ru/go-4devs/log"
)
func ExampleWithSource() {
ctx := context.Background()
logger := log.New(log.WithStdout()).With(log.WithSource(1, filepath.Base))
logger := log.New(log.WithStdout()).With(log.WithSource(1))
logger.Debug(ctx, "debug message")
// Output:
// msg="debug message" source=source_example_test.go:14
// msg="debug message" source=source_example_test.go:13
}
func ExampleWithSource_json() {
ctx := context.Background()
logger := log.New(log.WithStdout(), log.WithJSONFormat()).With(log.WithSource(2, filepath.Base))
logger := log.New(log.WithStdout(), log.WithJSONFormat()).With(log.WithSource(1))
logger.Debug(ctx, "debug message")
// Output:
// {"msg":"debug message","source":{"file":"source_example_test.go","line":23,"func":"log_test.ExampleWithSource_json"}}
// {"msg":"debug message","source":{"file":"source_example_test.go","line":22,"func":"log_test.ExampleWithSource_json"}}
}

View File

@@ -1,37 +0,0 @@
package log_test
import (
"context"
"math"
"path/filepath"
"time"
"gitoa.ru/go-4devs/log"
"gitoa.ru/go-4devs/log/entry"
"gitoa.ru/go-4devs/log/field"
"gitoa.ru/go-4devs/log/level"
)
func exampleWithTime(key, format string) log.Middleware {
return func(ctx context.Context, e *entry.Entry, handler log.Logger) (int, error) {
return handler(ctx, e.Add(field.FormatTime(key, format, time.Unix(math.MaxInt32, 0).In(time.UTC))))
}
}
func ExampleFormatWithBracket() {
ctx := context.Background()
logger := log.New(log.WithFormat(log.FormatWithBracket(field.NewEncoderText())), log.WithStdout()).With(
log.WithSource(10, filepath.Base),
// log.WithTime(log.KeyTime, time.RFC3339),
exampleWithTime(log.KeyTime, time.RFC3339),
log.WithLevel(log.KeyLevel, level.Info),
)
logger.InfoKV(ctx, "imfo message", field.Int64("num", 42))
serviceLogger := logger.With(log.WithName("service_name"))
serviceLogger.Err(ctx, "error message")
// Output:
// 2038-01-19T03:14:07Z [info] writer_example_test.go:30 "imfo message" num=42
// 2038-01-19T03:14:07Z [error][service_name] writer_example_test.go:33 "error message"
}

View File

@@ -13,20 +13,18 @@ import (
// Keys for "built-in" attributes.
const (
// KeyTime is the key used by the built-in handlers for the time
// TimeKey is the key used by the built-in handlers for the time
// when the log method is called. The associated Value is a [time.Time].
KeyTime = "time"
// KeyLevel is the key used by the built-in handlers for the level
// LevelKey is the key used by the built-in handlers for the level
// of the log call. The associated value is a [Level].
KeyLevel = "level"
// KeyMessage is the key used by the built-in handlers for the
// MessageKey is the key used by the built-in handlers for the
// message of the log call. The associated value is a string.
KeyMessage = "msg"
// KeySource is the key used by the built-in handlers for the source file
// SourceKey is the key used by the built-in handlers for the source file
// and line of the log call. The associated value is a string.
KeySource = "source"
// KeyName logger name.
KeyName = "name"
)
func WithWriter(w io.Writer) func(*option) {
@@ -43,18 +41,15 @@ func WithStdout() func(*option) {
// WithStringFormat sets format as simple string.
func WithStringFormat() func(*option) {
return WithFormat(FormatString(field.NewEncoderText()))
return func(o *option) {
o.format = formatText()
}
}
// WithJSONFormat sets json output format.
func WithJSONFormat() func(*option) {
return WithFormat(FormatJSON(field.NewEncoderJSON()))
}
// WithFormat sets custom output format.
func WithFormat(format func(io.Writer, *entry.Entry) (int, error)) func(*option) {
return func(o *option) {
o.format = format
o.format = formatJSON()
}
}
@@ -66,8 +61,8 @@ type option struct {
// New creates standart logger.
func New(opts ...func(*option)) Logger {
log := option{
format: FormatString(field.NewEncoderText()),
out: os.Stderr,
format: formatText(),
out: os.Stdout,
}
for _, opt := range opts {
@@ -79,68 +74,11 @@ func New(opts ...func(*option)) Logger {
}
}
type Encoder interface {
AppendValue(dst []byte, val field.Value) []byte
AppendField(dst []byte, val field.Field) []byte
}
func formatText() func(io.Writer, *entry.Entry) (int, error) {
enc := field.NewEncoderText()
func FormatWithBracket(enc Encoder) func(io.Writer, *entry.Entry) (int, error) {
appendValue := func(buf *buffer.Buffer, data field.Fields, key, prefix, suffix string) *buffer.Buffer {
data.Fields(
func(f field.Field) bool {
if f.IsKey(key) {
_, _ = buf.WriteString(prefix)
*buf = enc.AppendValue(*buf, f.Value)
_, _ = buf.WriteString(suffix)
return false
}
return true
})
return buf
}
return func(w io.Writer, data *entry.Entry) (int, error) {
buf := buffer.New()
defer func() {
buf.Free()
}()
fields := data.Fields()
buf = appendValue(buf, fields, KeyTime, "", " ")
_, _ = buf.WriteString("[")
*buf = enc.AppendValue(*buf, field.StringValue(data.Level().String()))
_, _ = buf.WriteString("]")
buf = appendValue(buf, fields, KeyName, "[", "]")
buf = appendValue(buf, fields, KeySource, " ", " ")
*buf = enc.AppendValue(*buf, field.StringValue(data.Message()))
fields.Fields(func(f field.Field) bool {
if !f.IsKey(KeyTime, KeySource, KeyName, KeyLevel) {
*buf = enc.AppendField(*buf, f)
}
return true
})
_, _ = buf.WriteString("\n")
n, err := w.Write(*buf)
if err != nil {
return 0, fmt.Errorf("format text:%w", err)
}
return n, nil
}
}
func FormatString(enc Encoder) func(io.Writer, *entry.Entry) (int, error) {
return func(w io.Writer, entry *entry.Entry) (int, error) {
buf := buffer.New()
defer func() {
buf.Free()
}()
@@ -162,10 +100,11 @@ func FormatString(enc Encoder) func(io.Writer, *entry.Entry) (int, error) {
}
}
func FormatJSON(enc Encoder) func(w io.Writer, entry *entry.Entry) (int, error) {
func formatJSON() func(w io.Writer, entry *entry.Entry) (int, error) {
enc := field.NewEncoderJSON()
return func(w io.Writer, entry *entry.Entry) (int, error) {
buf := buffer.New()
defer func() {
buf.Free()
}()