log

package module
v0.5.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 4, 2024 License: MIT Imports: 12 Imported by: 4

README

log

Build Status Go Report Card GoDoc

Documentation

Overview

Package log logged data by handler and use processor, exposes eight methods to write logs to the eight RFC 5424 levels.

Example (FieldClosureFn)
package main

import (
	"context"
	"fmt"
	"sync/atomic"

	"gitoa.ru/go-4devs/log"
	"gitoa.ru/go-4devs/log/field"
	"gitoa.ru/go-4devs/log/level"
)

var ctx = context.Background()

func main() {
	cnt := int32(0)
	closure := field.ClosureFn(func() any {
		d := fmt.Sprintf("additional error data: %d", cnt)
		atomic.AddInt32(&cnt, 1)

		return d
	})

	log := log.New(log.WithStdout()).With(log.WithLevel(log.KeyLevel, level.Info))

	log.DebugKVs(ctx, "debug message", "data", closure)
	log.ErrKVs(ctx, "error message", "err", closure)
	log.WarnKVs(ctx, "warn message", "warn", closure)

}
Output:

msg="error message" err="additional error data: 0" level=error
msg="warn message" warn="additional error data: 1" level=warning
Example (WithGroup)
package main

import (
	"context"
	"math"
	"os"

	"gitoa.ru/go-4devs/log"
	"gitoa.ru/go-4devs/log/field"
	"gitoa.ru/go-4devs/log/level"
)

var ctx = context.Background()

func main() {
	log := log.New(log.WithStdout()).With(
		log.WithLevel(log.KeyLevel, level.Info),
	)

	log.ErrKVs(ctx, "error message",
		field.Groups("grous_field",
			field.Error("err", os.ErrDeadlineExceeded),
			field.Bool("bool", false),
		),
	)
	log.WarnKV(ctx, "error message", field.ValuerFn("valuer_field", func() any {
		return field.Fields{
			field.Int("int_value", math.MaxInt),
			field.Uint8("uint8_value", math.MaxUint8),
		}
	}))

}
Output:

msg="error message" grous_field.err="i/o timeout" grous_field.bool=false level=error
msg="error message" valuer_field.int_value=9223372036854775807 valuer_field.uint8_value=255 level=warning

Index

Examples

Constants

View Source
const (
	// 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"
	// 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"
	// 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"
	// 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"
)

Keys for "built-in" attributes.

Variables

This section is empty.

Functions

func Alert

func Alert(ctx context.Context, args ...interface{})

Alert log by alert level.

func AlertKV

func AlertKV(ctx context.Context, msg string, args ...field.Field)

AlertKV log by alert level and key-values.

func AlertKVs added in v0.3.0

func AlertKVs(ctx context.Context, msg string, args ...interface{})

AlertKVs sugared log by alert level and key-values.

func Alertf

func Alertf(ctx context.Context, format string, args ...interface{})

Alertf log by alert level by format and arguments.

func Crit

func Crit(ctx context.Context, args ...interface{})

Crit log by critical level.

func CritKV

func CritKV(ctx context.Context, msg string, args ...field.Field)

CritKV log by critcal level and key-values.

func CritKVs added in v0.3.0

func CritKVs(ctx context.Context, msg string, args ...interface{})

CritKVs sugared log by critcal level and key-values.

func Critf

func Critf(ctx context.Context, format string, args ...interface{})

Critf log by critical level by format and arguments.

func Debug

func Debug(ctx context.Context, args ...interface{})

Debug log by debug level.

Example
package main

import (
	"context"
	"path/filepath"

	"gitoa.ru/go-4devs/log"
	"gitoa.ru/go-4devs/log/level"
)

func main() {
	logger := log.New(log.WithStdout()).With(
		log.WithSource(2, filepath.Base),
		log.WithLevel(log.KeyLevel, level.Debug),
		log.WithExit(level.Alert),
		log.WithPanic(level.Emergency),
	)

	log.SetLogger(logger)

	ctx := context.Background()
	log.Debug(ctx, "debug message")
}
Output:

msg="debug message" source=global_example_test.go:22 level=debug

func DebugKV

func DebugKV(ctx context.Context, msg string, args ...field.Field)

DebugKV log by debug level and key-values.

func DebugKVs added in v0.3.0

func DebugKVs(ctx context.Context, msg string, args ...interface{})

DebugKVs sugared log by debug level and key-values.

func Debugf

func Debugf(ctx context.Context, format string, args ...interface{})

Debugf log by debug level by format and arguments.

func Emerg

func Emerg(ctx context.Context, args ...interface{})

Emerg log by emergency level.

func EmergKV

func EmergKV(ctx context.Context, msg string, args ...field.Field)

EmergKV log by emergency level and key-values.

func EmergKVs added in v0.3.0

func EmergKVs(ctx context.Context, msg string, args ...interface{})

EmergKVs sugared log by emergency level and key-values.

func Emergf

func Emergf(ctx context.Context, format string, args ...interface{})

Emergf log by emergency level by format and arguments.

func Err

func Err(ctx context.Context, args ...interface{})

Err log by error level.

func ErrKV

func ErrKV(ctx context.Context, msg string, args ...field.Field)

ErrKV log by error level and key-values.

Example
package main

import (
	"context"

	"gitoa.ru/go-4devs/log"
	"gitoa.ru/go-4devs/log/level"
)

var ctx = context.Background()

func setStdout() {

	log.SetLogger(log.New(log.WithStdout()).With(log.WithLevel(log.KeyLevel, level.Debug)))
}

func main() {
	setStdout()
	log.ErrKVs(ctx, "same message", "key", "addition value")
}
Output:

msg="same message" key="addition value" level=error

func ErrKVs added in v0.3.0

func ErrKVs(ctx context.Context, msg string, args ...interface{})

ErrKVs sugared log by error level and key-values.

func Errf

func Errf(ctx context.Context, format string, args ...interface{})

Errf log by error level by format and arguments.

func Fatal added in v0.2.0

func Fatal(args ...interface{})

Fatal log by alert level and arguments.

func Fatalf added in v0.2.0

func Fatalf(format string, args ...interface{})

Fatalf log by alert level by format and arguments without context.

func Fatalln added in v0.2.0

func Fatalln(args ...interface{})

Fatalln log by alert level and arguments.

func Field

func Field(key string, value interface{}) field.Field

Field create field.

func FieldError added in v0.1.0

func FieldError(err error) field.Field

FieldError new errors field with key error.

func FormatJSON added in v0.5.4

func FormatJSON(enc Encoder) func(w io.Writer, entry *entry.Entry) (int, error)

func FormatString added in v0.5.4

func FormatString(enc Encoder) func(io.Writer, *entry.Entry) (int, error)

func FormatWithBracket added in v0.5.3

func FormatWithBracket(enc Encoder) func(io.Writer, *entry.Entry) (int, error)
Example
package main

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 main() {
	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"

func Info

func Info(ctx context.Context, args ...interface{})

Info log by info level.

Example
package main

import (
	"context"

	"gitoa.ru/go-4devs/log"
	"gitoa.ru/go-4devs/log/level"
)

var ctx = context.Background()

func setStdout() {

	log.SetLogger(log.New(log.WithStdout()).With(log.WithLevel(log.KeyLevel, level.Debug)))
}

func main() {
	setStdout()
	log.Info(ctx, "same message")
}
Output:

msg="same message" level=info

func InfoKV

func InfoKV(ctx context.Context, msg string, args ...field.Field)

InfoKV log by info level and key-values.

func InfoKVs added in v0.3.0

func InfoKVs(ctx context.Context, msg string, args ...interface{})

InfoKVs sugared log by info level and key-values.

func Infof

func Infof(ctx context.Context, format string, args ...interface{})

Infof log by info level by format and arguments.

func Notice

func Notice(ctx context.Context, args ...interface{})

Notice log by notice level.

func NoticeKV

func NoticeKV(ctx context.Context, msg string, args ...field.Field)

NoticeKV log by notice level and key-values.

func NoticeKVs added in v0.3.0

func NoticeKVs(ctx context.Context, msg string, args ...interface{})

NoticeKVs sugared log by notice level and key-values.

func Noticef

func Noticef(ctx context.Context, format string, args ...interface{})

Noticef log by notice level by format and arguments.

func Panic added in v0.2.0

func Panic(args ...interface{})

Panic log by emergency level and arguments.

func Panicf added in v0.2.0

func Panicf(format string, args ...interface{})

Panicf log by emergency level and arguments without context.

func Panicln added in v0.2.0

func Panicln(args ...interface{})

Panicln log by emergency level and arguments.

func Print added in v0.2.0

func Print(args ...interface{})

Print log by info level and arguments.

Example
package main

import (
	"gitoa.ru/go-4devs/log"
	"gitoa.ru/go-4devs/log/level"
)

func setStdout() {

	log.SetLogger(log.New(log.WithStdout()).With(log.WithLevel(log.KeyLevel, level.Debug)))
}

func main() {
	setStdout()
	log.Print("same message")
}
Output:

msg="same message" level=info

func Printf added in v0.2.0

func Printf(format string, args ...interface{})

Printf log by info level by format and arguments without context.

func Println added in v0.2.0

func Println(args ...interface{})

Println log by info level and arguments.

func SetLogger

func SetLogger(l Logger)

SetLogger sets global used logger. This function is not thread-safe.

func TrimPath added in v0.5.3

func TrimPath(file string) string

func Warn

func Warn(ctx context.Context, args ...interface{})

Warn logs by warning level.

func WarnKV

func WarnKV(ctx context.Context, msg string, args ...field.Field)

WarnKV log by warning level and key-values.

func WarnKVs added in v0.3.0

func WarnKVs(ctx context.Context, msg string, args ...interface{})

WarnKVs sugared log by warning level and key-values.

func Warnf

func Warnf(ctx context.Context, format string, args ...interface{})

Warnf log by warning level by format and arguments.

func WithFormat added in v0.1.0

func WithFormat(format func(io.Writer, *entry.Entry) (int, error)) func(*option)

WithFormat sets custom output format.

func WithJSONFormat added in v0.1.0

func WithJSONFormat() func(*option)

WithJSONFormat sets json output format.

func WithStdout added in v0.1.0

func WithStdout() func(*option)

func WithStringFormat added in v0.1.0

func WithStringFormat() func(*option)

WithStringFormat sets format as simple string.

func WithWriter added in v0.1.0

func WithWriter(w io.Writer) func(*option)

func Writer added in v0.3.0

func Writer(ctx context.Context, level level.Level) io.Writer

Types

type Encoder added in v0.5.4

type Encoder interface {
	AppendValue(dst []byte, val field.Value) []byte
	AppendField(dst []byte, val field.Field) []byte
}

type Logger

type Logger func(ctx context.Context, entry *entry.Entry) (int, error)

Logger logged message.

func Log added in v0.3.0

func Log() Logger

Log return global logger.

func New

func New(opts ...func(*option)) Logger

New creates standart logger.

Example
package main

import (
	"context"

	"gitoa.ru/go-4devs/log"
)

var ctx = context.Background()

func main() {
	logger := log.New(log.WithStdout())
	logger.Info(ctx, "same message")
}
Output:

msg="same message"
Example (AnyField)
package main

import (
	"context"
	"errors"
	"math"
	"time"

	"gitoa.ru/go-4devs/log"
	"gitoa.ru/go-4devs/log/field"
)

var ctx = context.Background()

type Obj struct {
	Name     string
	IsEnable bool
}

var (
	obj = Obj{
		Name: "test obj",
	}

	intVal = int(math.MaxInt)

	uintVal = uint(math.MaxUint)

	float64Val = float64(math.MaxFloat64)

	timeVal = time.Unix(0, math.MaxInt32).In(time.UTC)
)

func main() {
	logger := log.New(log.WithStdout(), log.WithJSONFormat())
	logger.InfoKV(ctx, "any info message",
		field.Any("obj", Obj{Name: "obj name"}),
		field.Any("obj", &obj),
		field.Any("int", intVal),
		field.Any("uint", uintVal),
		field.Any("float", float64Val),
		field.Any("time", timeVal),
		field.Any("duration", time.Hour),
		field.Any("error", errors.New("error")),
	)
}
Output:

{"msg":"any info message","obj":{"Name":"obj name","IsEnable":false},"obj":{"Name":"test obj","IsEnable":false},"int":9223372036854775807,"uint":18446744073709551615,"float":1.7976931348623157e+308,"time":"1970-01-01T00:00:02Z","duration":"1h0m0s","error":"error"}
Example (ArrayField)
package main

import (
	"context"
	"errors"
	"math"
	"time"

	"gitoa.ru/go-4devs/log"
	"gitoa.ru/go-4devs/log/field"
)

var ctx = context.Background()

type Obj struct {
	Name     string
	IsEnable bool
}

var (
	str = "test str"

	uint8Val = uint8(math.MaxUint8)
)

func main() {
	logger := log.New(log.WithStdout(), log.WithJSONFormat())
	logger.InfoKV(ctx, "array info message",
		field.Strings("strings", "string", str),
		field.Bools("bools", true, false),
		field.Ints("ints", 42, 24),
		field.Int8s("int8s", 42, 24),
		field.Int16s("int16s", 42, 24),
		field.Int32s("int32s", 42, 24),
		field.Int64s("int64s", 42, 24),
		field.Uint8s("uint8s", uint8Val, 0),
		field.Uint16s("uint16s", 42, 24),
		field.Uint32s("uint32s", 42, 24),
		field.Uint64s("uint64s", 42, 24),
		field.Float32s("float32s", 42, 24),
		field.Float64s("float64s", 42, 24),
		field.Complex64s("complex64s", 42, 24),
		field.Complex128s("complex128s", 42, 24),
		field.Durations("durations", time.Minute, time.Second),
		field.Times("times", time.Unix(0, 42).In(time.UTC), time.Unix(0, 24).In(time.UTC)),
		field.Errors("errors", errors.New("error"), errors.New("error2")),
	)
}
Output:

{"msg":"array info message","strings":["string","test str"],"bools":[true,false],"ints":[42,24],"int8s":[42,24],"int16s":[42,24],"int32s":[42,24],"int64s":[42,24],"uint8s":[255,0],"uint16s":[42,24],"uint32s":[42,24],"uint64s":[42,24],"float32s":[42,24],"float64s":[42,24],"complex64s":["(42+0i)","(24+0i)"],"complex128s":["(42+0i)","(24+0i)"],"durations":["1m0s","1s"],"times":["1970-01-01T00:00:00Z","1970-01-01T00:00:00Z"],"errors":["error","error2"]}
Example (DebugKV)
package main

import (
	"context"
	"os"

	"gitoa.ru/go-4devs/log"
	"gitoa.ru/go-4devs/log/level"
)

var ctx = context.Background()

func main() {
	logger := log.New(log.WithStdout()).With(log.WithLevel(log.KeyLevel, level.Debug))
	logger.DebugKVs(ctx, "same message", "error", os.ErrNotExist)
}
Output:

msg="same message" error="file does not exist" level=debug
Example (Errf)
package main

import (
	"context"

	"gitoa.ru/go-4devs/log"
)

var ctx = context.Background()

func main() {
	logger := log.New(log.WithStdout())
	logger.Errf(ctx, "same message %d", 1)
}
Output:

msg="same message 1"
Example (Fields)
package main

import (
	"context"
	"errors"
	"math"
	"time"

	"gitoa.ru/go-4devs/log"
	"gitoa.ru/go-4devs/log/field"
)

var ctx = context.Background()

type Obj struct {
	Name     string
	IsEnable bool
}

var (
	str = "test str"

	uint8Val = uint8(math.MaxUint8)

	timeVal = time.Unix(0, math.MaxInt32).In(time.UTC)
)

func main() {
	logger := log.New(log.WithStdout(), log.WithJSONFormat())
	logger.InfoKV(ctx, "info message",
		field.String("string", str),
		field.Bool("bool", true),
		field.Int("int", 42),
		field.Int8("int8", 42),
		field.Int16("int16", 42),
		field.Int32("int32", 42),
		field.Int64("int64", 42),
		field.Uint8("uint8", uint8Val),
		field.Uint16("uint16", 42),
		field.Uint32("uint32", 42),
		field.Uint64("uint64", 42),
		field.Float32("float32", 42),
		field.Float64("float64", 42),
		field.Complex64("complex16", 42),
		field.Complex128("complex128", 42),
		field.Duration("duration", time.Minute),
		field.Time("time", timeVal),
		field.FormatTime("format_time", time.UnixDate, timeVal),
		field.Error("error", errors.New("error")),
	)
}
Output:

{"msg":"info message","string":"test str","bool":true,"int":42,"int8":42,"int16":42,"int32":42,"int64":42,"uint8":255,"uint16":42,"uint32":42,"uint64":42,"float32":42,"float64":42,"complex16":"(42+0i)","complex128":"(42+0i)","duration":"1m0s","time":"1970-01-01T00:00:02Z","format_time":"Thu Jan  1 00:00:02 UTC 1970","error":"error"}
Example (JsonFormat)
package main

import (
	"context"

	"gitoa.ru/go-4devs/log"
	"gitoa.ru/go-4devs/log/level"
)

var ctx = context.Background()

type Obj struct {
	Name     string
	IsEnable bool
}

func main() {
	logger := log.New(log.WithStdout(), log.WithJSONFormat()).
		With(
			log.WithLevel(log.KeyLevel, level.Debug),
			log.GoVersion("go-version"),
		)
	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.22.2"}
{"msg":"same warn message","obj":{"Name":"obj name","IsEnable":false},"level":"warning","go-version":"go1.22.2"}
Example (Level)
package main

import (
	"context"

	"gitoa.ru/go-4devs/log"
	"gitoa.ru/go-4devs/log/level"
)

var ctx = context.Background()

func main() {
	logger := log.New(log.WithStdout()).With(log.WithLevel(log.KeyLevel, level.Error))
	logger.Err(ctx, "same error message")
}
Output:

msg="same error message" level=error
Example (Level_info)
package main

import (
	"context"

	"gitoa.ru/go-4devs/log"
	"gitoa.ru/go-4devs/log/level"
)

var ctx = context.Background()

func main() {
	logger := log.New(log.WithStdout()).With(log.WithLevel(log.KeyLevel, level.Error))
	logger.Info(ctx, "same message")
}
Output:

Example (PointerField)
package main

import (
	"context"
	"math"
	"time"

	"gitoa.ru/go-4devs/log"
	"gitoa.ru/go-4devs/log/field"
)

var ctx = context.Background()

type Obj struct {
	Name     string
	IsEnable bool
}

var (
	str      = "test str"
	boolsVal = true
	intVal   = int(math.MaxInt)
	int8Val  = int8(math.MaxInt8)
	int16Val = int16(math.MaxInt16)
	int32Val = int32(math.MaxInt32)
	int64Val = int64(math.MaxInt64)

	uintVal   = uint(math.MaxUint)
	uint8Val  = uint8(math.MaxUint8)
	uint16Val = uint16(math.MaxInt16)
	uint32Val = uint32(math.MaxInt32)
	uint64Val = uint64(math.MaxInt64)

	float32Val = float32(math.MaxFloat32)
	float64Val = float64(math.MaxFloat64)

	minute  = time.Minute
	timeVal = time.Unix(0, math.MaxInt32).In(time.UTC)
)

func main() {
	logger := log.New(log.WithStdout(), log.WithJSONFormat())
	logger.InfoKV(ctx, "pointer info message",
		field.Stringp("stringp", &str),
		field.Stringp("stringp", nil),
		field.Boolp("boolp", &boolsVal),
		field.Boolp("boolp", nil),
		field.Intp("intp", &intVal),
		field.Intp("intp", nil),
		field.Int8p("int8p", &int8Val),
		field.Int8p("int8p", nil),
		field.Int16p("int16p", &int16Val),
		field.Int16p("int16p", nil),
		field.Int32p("int32p", &int32Val),
		field.Int32p("int32p", nil),
		field.Int64p("int64p", &int64Val),
		field.Int64p("int64p", nil),
		field.Uintp("uintp", &uintVal),
		field.Uintp("uintp", nil),
		field.Uint8p("uint8p", &uint8Val),
		field.Uint8p("uint8p", nil),
		field.Uint16p("uint16p", &uint16Val),
		field.Uint16p("uint16p", nil),
		field.Uint32p("uint32p", &uint32Val),
		field.Uint32p("uint32p", nil),
		field.Uint64p("uint64p", &uint64Val),
		field.Uint64p("uint64p", nil),
		field.Float32p("float32p", &float32Val),
		field.Float32p("float32p", nil),
		field.Float64p("float64p", &float64Val),
		field.Float64p("float64p", nil),
		field.Durationp("durationp", &minute),
		field.Durationp("durationp", nil),
		field.Timep("timep", &timeVal),
		field.Timep("timep", nil),
	)
}
Output:

{"msg":"pointer info message","stringp":"test str","stringp":null,"boolp":true,"boolp":null,"intp":9223372036854775807,"intp":null,"int8p":127,"int8p":null,"int16p":32767,"int16p":null,"int32p":2147483647,"int32p":null,"int64p":9223372036854775807,"int64p":null,"uintp":18446744073709551615,"uintp":null,"uint8p":255,"uint8p":null,"uint16p":32767,"uint16p":null,"uint32p":2147483647,"uint32p":null,"uint64p":9223372036854775807,"uint64p":null,"float32p":3.4028235e+38,"float32p":null,"float64p":1.7976931348623157e+308,"float64p":null,"durationp":"1m0s","durationp":null,"timep":"1970-01-01T00:00:02Z","timep":null}
Example (TextEncoding)
package main

import (
	"context"

	"gitoa.ru/go-4devs/log"
	"gitoa.ru/go-4devs/log/level"
)

var ctx = context.Background()

type Obj struct {
	Name     string
	IsEnable bool
}

func main() {
	logger := log.New(log.WithStdout()).
		With(
			log.WithLevel(log.KeyLevel, level.Debug),
			log.GoVersion("go-version"),
		)
	logger.Err(ctx, "same error message")
	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.22.2
msg="same info message" api-version=0.1 obj={Name:text value IsEnable:true} level=info go-version=go1.22.2
Example (WithCaller)
logger := log.New(log.WithStdout()).With(
	log.WithLevel(log.KeyLevel, level.Debug),
	log.WithSource(3, filepath.Base),
)
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

func With added in v0.1.0

func With(logger Logger, mw ...Middleware) Logger

With add middleware to logger.

Example
package main

import (
	"context"

	"gitoa.ru/go-4devs/log"
	"gitoa.ru/go-4devs/log/entry"
	"gitoa.ru/go-4devs/log/field"
)

var ctx = context.Background()

type ctxKey string

func (c ctxKey) String() string {
	return string(c)
}

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

func main() {
	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.Info(vctx, "same message")
}
Output:

msg="same message" level=info requestID=6a5fa048-7181-11ea-bc55-0242ac130003 api=0.1.0 go=go1.22.2

func (Logger) Alert

func (l Logger) Alert(ctx context.Context, args ...interface{})

Alert log by alert level.

func (Logger) AlertKV

func (l Logger) AlertKV(ctx context.Context, msg string, args ...field.Field)

AlertKV log by alert level and key-values.

func (Logger) AlertKVs added in v0.3.0

func (l Logger) AlertKVs(ctx context.Context, msg string, args ...interface{})

AlertKVs sugared log by alert level and key-values.

func (Logger) Alertf

func (l Logger) Alertf(ctx context.Context, format string, args ...interface{})

Alertf log by alert level by format and arguments.

func (Logger) Crit

func (l Logger) Crit(ctx context.Context, args ...interface{})

Crit log by critical level.

func (Logger) CritKV

func (l Logger) CritKV(ctx context.Context, msg string, args ...field.Field)

CritKV log by critcal level and key-values.

func (Logger) CritKVs added in v0.3.0

func (l Logger) CritKVs(ctx context.Context, msg string, args ...interface{})

CritKVs sugared log by critcal level and key-values.

func (Logger) Critf

func (l Logger) Critf(ctx context.Context, format string, args ...interface{})

Critf log by critical level by format and arguments.

func (Logger) Debug

func (l Logger) Debug(ctx context.Context, args ...interface{})

Debug log by debug level.

func (Logger) DebugKV

func (l Logger) DebugKV(ctx context.Context, msg string, args ...field.Field)

DebugKV log by debug level and key-values.

func (Logger) DebugKVs added in v0.3.0

func (l Logger) DebugKVs(ctx context.Context, msg string, args ...interface{})

DebugKVs sugared log by debug level and key-values.

func (Logger) Debugf

func (l Logger) Debugf(ctx context.Context, format string, args ...interface{})

Debugf log by debug level by format and arguments.

func (Logger) Emerg

func (l Logger) Emerg(ctx context.Context, args ...interface{})

Emerg log by emergency level.

func (Logger) EmergKV

func (l Logger) EmergKV(ctx context.Context, msg string, args ...field.Field)

EmergKV log by emergency level and key-values.

func (Logger) EmergKVs added in v0.3.0

func (l Logger) EmergKVs(ctx context.Context, msg string, args ...interface{})

EmergKVs sugared log by emergency level and key-values.

func (Logger) Emergf

func (l Logger) Emergf(ctx context.Context, format string, args ...interface{})

Emergf log by emergency level by format and arguments.

func (Logger) Err

func (l Logger) Err(ctx context.Context, args ...interface{})

Err log by error level.

func (Logger) ErrKV

func (l Logger) ErrKV(ctx context.Context, msg string, args ...field.Field)

ErrKV log by error level and key-values.

func (Logger) ErrKVs added in v0.3.0

func (l Logger) ErrKVs(ctx context.Context, msg string, args ...interface{})

ErrKVs sugared log by error level and key-values.

func (Logger) Errf

func (l Logger) Errf(ctx context.Context, format string, args ...interface{})

Errf log by error level by format and arguments.

func (Logger) Fatal added in v0.2.0

func (l Logger) Fatal(args ...interface{})

Fatal log by alert level and arguments.

func (Logger) Fatalf added in v0.2.0

func (l Logger) Fatalf(format string, args ...interface{})

Fatalf log by alert level by format and arguments without context.

func (Logger) Fatalln added in v0.2.0

func (l Logger) Fatalln(args ...interface{})

Fatalln log by alert level and arguments.

func (Logger) Info

func (l Logger) Info(ctx context.Context, args ...interface{})

Info log by info level.

func (Logger) InfoKV

func (l Logger) InfoKV(ctx context.Context, msg string, args ...field.Field)

InfoKV log by info level and key-values.

func (Logger) InfoKVs added in v0.3.0

func (l Logger) InfoKVs(ctx context.Context, msg string, args ...interface{})

InfoKVs sugared log by info level and key-values.

func (Logger) Infof

func (l Logger) Infof(ctx context.Context, format string, args ...interface{})

Infof log by info level by format and arguments.

func (Logger) Notice

func (l Logger) Notice(ctx context.Context, args ...interface{})

Notice log by notice level.

func (Logger) NoticeKV

func (l Logger) NoticeKV(ctx context.Context, msg string, args ...field.Field)

NoticeKV log by notice level and key-values.

func (Logger) NoticeKVs added in v0.3.0

func (l Logger) NoticeKVs(ctx context.Context, msg string, args ...interface{})

NoticeKVs sugared log by notice level and key-values.

func (Logger) Noticef

func (l Logger) Noticef(ctx context.Context, format string, args ...interface{})

Noticef log by notice level by format and arguments.

func (Logger) Panic added in v0.2.0

func (l Logger) Panic(args ...interface{})

Panic log by emergency level and arguments.

func (Logger) Panicf added in v0.2.0

func (l Logger) Panicf(format string, args ...interface{})

Panicf log by emergency level and arguments without context.

func (Logger) Panicln added in v0.2.0

func (l Logger) Panicln(args ...interface{})

Panicln log by emergency level and arguments.

func (Logger) Print added in v0.2.0

func (l Logger) Print(args ...interface{})

Print log by info level and arguments.

Example
package main

import (
	"context"

	"gitoa.ru/go-4devs/log"
	"gitoa.ru/go-4devs/log/entry"
	"gitoa.ru/go-4devs/log/field"
)

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

func main() {
	logger := log.New(log.WithStdout()).With(
		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.22.2

func (Logger) Printf added in v0.2.0

func (l Logger) Printf(format string, args ...interface{})

Printf log by info level by format and arguments without context.

func (Logger) Println added in v0.2.0

func (l Logger) Println(args ...interface{})

Println log by info level and arguments.

func (Logger) Warn

func (l Logger) Warn(ctx context.Context, args ...interface{})

Warn log by warning level.

func (Logger) WarnKV

func (l Logger) WarnKV(ctx context.Context, msg string, args ...field.Field)

WarnKV log by warning level and key-values.

func (Logger) WarnKVs added in v0.3.0

func (l Logger) WarnKVs(ctx context.Context, msg string, args ...interface{})

WarnKVs sugared log by warning level and key-values.

func (Logger) Warnf

func (l Logger) Warnf(ctx context.Context, format string, args ...interface{})

Warnf log by warning level by format and arguments.

func (Logger) With added in v0.0.2

func (l Logger) With(mw ...Middleware) Logger

With adds middlewares to logger.

func (Logger) Write added in v0.3.0

func (l Logger) Write(in []byte) (int, error)

func (Logger) Writer added in v0.3.0

func (l Logger) Writer(ctx context.Context, level level.Level, fields ...field.Field) io.Writer

type Middleware

type Middleware func(ctx context.Context, e *entry.Entry, handler Logger) (int, error)

Middleware handle.

func GoVersion added in v0.1.0

func GoVersion(key string) Middleware

GoVersion add field by go version.

func KeyValue added in v0.1.0

func KeyValue(key string, value interface{}) Middleware

KeyValue add field by const key value.

func WithCaller added in v0.1.0

func WithCaller(key string, depth int, full bool) Middleware

WithCaller adds called file. Deprecated: use WithSource.

func WithContextValue added in v0.1.0

func WithContextValue(keys ...fmt.Stringer) Middleware

WithContext add field by context key.

func WithExit added in v0.3.0

func WithExit(level level.Level) Middleware

WithExit exit by level.

func WithLevel added in v0.1.0

func WithLevel(key string, lvl level.Level) Middleware

WithLevel sets log level.

func WithMetrics added in v0.1.0

func WithMetrics(metrics func(level level.Level)) Middleware

WithMetrics adds handle metrics.

func WithName added in v0.5.3

func WithName(name string) Middleware

func WithPanic added in v0.3.0

func WithPanic(level level.Level) Middleware

WithPanic panic by level.

func WithSource added in v0.5.2

func WithSource(items int, trimPath func(string) string) Middleware
Example
package main

import (
	"context"
	"path/filepath"

	"gitoa.ru/go-4devs/log"
)

func main() {
	ctx := context.Background()
	logger := log.New(log.WithStdout()).With(log.WithSource(1, filepath.Base))

	logger.Debug(ctx, "debug message")
}
Output:

msg="debug message" source=source_example_test.go:14
Example (Json)
package main

import (
	"context"
	"path/filepath"

	"gitoa.ru/go-4devs/log"
)

func main() {
	ctx := context.Background()
	logger := log.New(log.WithStdout(), log.WithJSONFormat()).With(log.WithSource(2, filepath.Base))

	logger.Debug(ctx, "debug message")
}
Output:

{"msg":"debug message","source":{"file":"source_example_test.go","line":23,"func":"log_test.ExampleWithSource_json"}}

func WithTime added in v0.1.0

func WithTime(key, format string) Middleware

WithTime adds time.

type Source added in v0.5.2

type Source struct {
	Func string `json:"func"`
	File string `json:"file"`
	Line int    `json:"line"`
}

Source describes the location of a line of source code.

func (Source) MarshalJSON added in v0.5.2

func (l Source) MarshalJSON() ([]byte, error)

func (Source) MarshalText added in v0.5.2

func (l Source) MarshalText() ([]byte, error)

Directories

Path Synopsis
nolint: exhaustruct
nolint: exhaustruct
handler
logrus Module
internal
logrus module
otel module
zap module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL