log

package module
v1.1.1 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2026 License: Apache-2.0 Imports: 17 Imported by: 4 modules, 3 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Logger

Helps your implementation to track your code activity

Why?

  • four levels debug, information, warning and error
  • tags that help messages be organized into logical groups
  • colored human readable output text
  • structural json output for machines, ie on production environment
  • structured logs with named properties, context extraction, and trace ID correlation
  • traceable will add info about file name, location, function and line number of called log
  • implements io.Writer in order to implement your own logger or just hide dependencies for external logging
  • uses Printf(format string, args ...any) function idiom, well know in go ecosystem

How to use it?

Installation and examples

Install the package:

go get github.com/sokool/log

The example below (full program in foo/main.go) shows context extraction, trace IDs, inline properties, log levels, and JSON output:

// Use a dedicated key type to avoid collisions with other packages.
type key string
type data = map[string]any
const traceID key = "trace_id"
ctx := context.WithValue(context.Background(), traceID, "1875fhsohfh08203")

// Set one global reader for contexts passed through %+v.
// The recognized trace_id becomes Message.TraceID, not an inline property.
log.SetContextData(func(ctx context.Context) data {
	return data{"trace_id": ctx.Value(traceID)}
})

// Default options include colors, properties, trace ID and source location.
lgr := log.New(os.Stdout).Tag("foo")

// %s formats ordinary text; %+v extracts data from the context.
// The trace ID appears as #1875fhso after tags, before the message.
lgr.Printf("hello %s %+v", "world", ctx)

// Prefixes add message tags and select the log level.
lgr.Printf("second:dbg: with tag name and debug level %+v", ctx)
lgr.Printf("third:err: explicit error level %v", data{"message": "it's bad", "code": 859})
lgr.Printf("fourth:wrn: warning level")

// Configuration methods return a new logger without changing the original.
// This variant omits date and trace information, and filters out INFO and DEBUG.
lgr = lgr.
	Tag("bar").
	Options(log.Levels | log.Tags | log.Time | log.Properties | log.Colors).
	Verbosity(log.WARNING)

lgr.Infof("ignored")
lgr.Debugf("ignored")

// Object properties render inline as sorted key=value pairs.
lgr.Errorf("with %+v attributes",
	log.Data{"code": 404, "message": "not found"})

// Logger implements io.Writer; message prefixes still select the level.
lgr.Write([]byte("wrn: by io.Writer method"))

// JSON preserves nested properties and includes the full trace ID.
// Verbosity remains independent of the output format.
lgr = lgr.
	Tag("ror:nik").
	Options(log.JSON).
	Verbosity(log.DEBUG)

lgr.Printf("with %+v messages %+v",
	log.Data{"wat": "hi"},
	log.Data{"qot": "there", "details": log.Data{"count": 2}})

lgr.Printf("request finished %+v", ctx)

Example output with colored text, shortened trace IDs, source locations, and JSON:

Logger output

License

Licensed under the Apache License, Version 2.0.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Default = New(os.Stdout, All)

Functions

func Debugf

func Debugf(format string, args ...any)

func Errorf

func Errorf(format string, args ...any)

func Printf

func Printf(format string, args ...any)

func SetContextData added in v1.1.0

func SetContextData(reader func(context.Context) map[string]any)

SetContextData replaces the reader used for contexts formatted with %+v. The reader must support concurrent calls. A nil reader disables extraction. Changes affect new messages only.

func SetTraceKey added in v1.1.0

func SetTraceKey(names ...string)

SetTraceKey replaces the trace ID field names, checked in the given order. With no names, it restores automatic recognition. It affects new messages only.

func Warnf added in v1.0.6

func Warnf(format string, args ...any)

Types

type Data added in v1.0.7

type Data map[string]any

func (Data) Flat added in v1.1.0

func (d Data) Flat(delim ...string) iter.Seq2[string, string]

Flat returns an iterator of flattened key-value pairs, sorted by key.

type Handler

type Handler func(Message)

func HTTP

func HTTP(url string, frequency time.Duration) Handler

type Level added in v1.0.6

type Level int
const (
	DEBUG   Level = 4
	INFO    Level = 3
	WARNING Level = 2
	ERROR   Level = 1
)

func (Level) GoString added in v1.0.6

func (l Level) GoString() string

func (Level) Render added in v1.0.6

func (l Level) Render(short, color bool) string

func (Level) String added in v1.0.6

func (l Level) String() string

type Logger

type Logger struct {
	// contains filtered or unexported fields
}

Logger support three types(levels) of logging

INF - default, when you want emphasize that something important (not negative) has happened. It should be used for informing about rare situation in your code, such as database connection has been established.

DBG - it meant to be verbose, like every few lines of code, when you decide that part of your code implementation did something important for internal state of your library/code.

ERR - when your code is a place where error is received but there is no good way of handling that situation you might log it todo

  • default attributes data added to each Message
  • log.Format option

func New

func New(w io.Writer, o ...Option) *Logger

New instance of logger

io.Writer w will receive all messages that are generated internally from strings and arguments that are passed to Logger.Printf.

Option o represents what is going to be included in strings that are passed into io.Writer

func (*Logger) Debugf added in v1.0.4

func (l *Logger) Debugf(text string, args ...any)

func (*Logger) Errorf added in v1.0.4

func (l *Logger) Errorf(text string, args ...any)

func (*Logger) Fatalf added in v1.1.0

func (l *Logger) Fatalf(text string, args ...any)

func (*Logger) Handlers

func (l *Logger) Handlers(h ...Handler) *Logger

Handlers creates new instance of Logger and all Message's are passed into Handler just after it is writer to io.Writer

func (*Logger) Infof added in v1.0.4

func (l *Logger) Infof(text string, args ...any)

func (*Logger) Options

func (l *Logger) Options(o Option) *Logger

Options create new Logger instance

func (*Logger) Printf

func (l *Logger) Printf(text string, args ...any)

Printf when text is json format and has no arguments a then it will be transformed

func (*Logger) Tag

func (l *Logger) Tag(name string) *Logger

Tags creates new instance of Logger with predefined tag name

func (*Logger) Trace added in v1.0.5

func (l *Logger) Trace(depth int) *Logger

Trace create new Logger instance

func (*Logger) Verbosity added in v1.0.7

func (l *Logger) Verbosity(m Level) *Logger

Verbosity determines what Level of logging should be delivered to io.Writer

func (*Logger) Warnf added in v1.0.6

func (l *Logger) Warnf(text string, args ...any)

func (*Logger) Write

func (l *Logger) Write(p []byte) (n int, err error)

Write tbd

func (*Logger) Writer added in v1.1.0

func (l *Logger) Writer(w io.Writer) *Logger

type Message

type Message struct {
	Tags    []string
	Level   Level
	TraceID string

	File      string
	Func      string
	Line      int
	ARGS      []any
	CreatedAt time.Time
	// contains filtered or unexported fields
}

func NewMessage

func NewMessage(text string, deep int, args ...any) Message

func (Message) Location

func (m Message) Location(colors bool) string

func (Message) MarshalJSON

func (m Message) MarshalJSON() ([]byte, error)

func (Message) MarshalText added in v1.0.4

func (m Message) MarshalText() ([]byte, error)

func (Message) Properties added in v1.1.0

func (m Message) Properties() Data

func (Message) Render

func (m Message) Render(o Option) ([]byte, error)

func (Message) String

func (m Message) String() string

func (Message) Tag

func (m Message) Tag(colors bool) string

func (Message) Text

func (m Message) Text(colors, properties bool) string

func (Message) Type

func (m Message) Type(colors bool) string

type Option

type Option int64

Option ...

const (
	// Date render Message with date in 2006/01/02 format
	Date Option = 1 << iota

	// Time render Message with time in 15:04:05.000000 format
	Time

	// Levels render Message with one of INF, DBG, ERR strings
	Levels

	// Tags render Message with tag name
	Tags

	// Trace renders the shortened trace ID after tags and the source location after the message.
	Trace

	// Properties renders structured %v and %+v data in a Message output string.
	Properties

	// Colors render Message with colors
	Colors

	// JSON makes output with json format instead text
	JSON

	All = Date | Time | Levels | Tags | Trace | Properties | Colors
)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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