logging

package module
v1.6.0 Latest Latest
Warning

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

Go to latest
Published: Sep 9, 2025 License: EUPL-1.2 Imports: 12 Imported by: 2

README

go-logging

Go-Logging is intended as a simple-to-use SDK for high-performance logging in GCP and locally. It supports caller location identification, optional stacktraces, colorful logging and more.

Quickstart

Install
go get github.com/entur/go-logging
go mod tidy
Basic Usage
import (
  "github.com/entur/go-logging"
)

func main() {
  // Global logger
  logging.Warn().Msg("Starting up my application")

  // Formatted logging
  logging.Warn().Msgf("Starting my %s", "application")

  // Local logger
  logger := logging.New()
  logger.Warn().Msg("Starting up my application")

  // Local logger with custom level
  logger = logging.New(
    logging.WithLevel(logging.DebugLevel)
  )
  logger.Debug().Msg("Starting up my application")
}

Overview

Log Levels

The default log level will be derived from the LOG_LEVEL environment variable if defined, or set to the warning level if not as per Entur's Architecture Descision Record.

Valid environment variable values for log levels are:

  • fatal ftl
  • panic pnc
  • error err
  • warning wrn
  • info inf
  • debug dbg
  • trace trc

Log levels can also be specified for on logger instance creation like so:

func main() {
  // New logger with its own level
  logger = logging.New(
    logging.WithLevel(logging.DebugLevel)
  )

  // Child logger with its own level again
  additionalLogger := logger.Level(logging.TraceLevel)
}
Stack Traces

The Go-Logging SDK supports logging of errors with stacktraces. To do so, simply create a new or wrap an existing error using the logging.NewStackTraceError() before you dispatch it for logging.

import (
  "fmt"

  "github.com/entur/go-logging"
)

func newErr() error {
  err := logging.NewStackTraceError("called newErr()")
  return err
}

func wrappedErr() error {
  existingErr := fmt.Errorf("called wrappedErr()")
  err := logging.NewStackTraceError("%w", existingErr) // Stack traces will be retrieved at the point NewStackTraceError is called
  return err
}

func main() {
  err := newErr()
  logging.Error().Err(err).Msg("An internal error occurred")

  err = wrappedErr()
  logging.Error().Err(err).Msg("An internal error occurred")
}
Calling Location Info

The Go-Logging SDK will automatically include the caller info when you use the global logging functions, or create a new instanced logger. If you want to disable the feature, you can prove the WithNoCaller() option to the logging constructor.

import (
  "github.com/entur/go-logging"
)

func main() {
  // Disable caller info in child logger
  logger := logging.New(
    logging.WithNoCaller()
  )

  logger.Debug().Msg("This log won't include caller info")

  // You can still include caller info individually, even if it is disabled by default
  logger.Debug().Caller("This log will include caller info")
}

Tests

This project makes use of Example tests. To run them, simply use use the following command

go test ./...

Examples

Interested in seeing how Go-Logging is used in practice at Entur? Take a look at the following repositories:

Documentation

Overview

Example
// Default global logger
// logging.Info().Msg("Hello from the global logger!")

// New child logger
// logger := logging.New()
// err := fmt.Errorf("oh no, an error")
// logger.Error().Err(err).Msg("An internal error occurred")

// New child logger with stacktraced error
// logger := logging.New()
// err := logging.NewStackTraceError("oh no, an error")
// logger.Error().Stack().Err(err).Msg("An internal error occurred!")

// Child logger with custom writer
w := logging.NewConsoleWriter(logging.WithNoColor(), logging.WithNoTimestamp())

logger := logging.New(logging.WithWriter(w), logging.WithLevel(logging.InfoLevel), logging.WithNoCaller())
logger.Warn().Msg("Hello from my new child logger!")

// Child logger with custom writer and level which won't be logged due to info < warning
logger = logging.New(logging.WithWriter(w), logging.WithLevel(logging.WarnLevel), logging.WithNoCaller())
logger.Info().Msg("Hello from my new custom child logger!")

// Slog logger with zerolog handler. Inefficient, so should only be used sparingly
// if some other SDK is able to take a custom slog handler.
h := logging.NewSlogHandler(logging.WithWriter(w))
slogger := slog.New(h)
slogger = slogger.With(
	slog.Int("some_int", 1),
	slog.String("some_string", "huh"),
	slog.Group("some_group",
		slog.Int("some_nested_int", 3),
		slog.Group("some_nested_group",
			slog.Float64("some_nested_nested_float", 100.0),
		),
	),
)
slogger.Warn("Hello from my new custom slog handler")
Output:

WRN Hello from my new child logger!
WRN Hello from my new custom slog handler some_group={"some_nested_group":{"some_nested_nested_float":100},"some_nested_int":3} some_int=1 some_string=huh

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// Functions
	Fatal = log.Fatal
	Panic = log.Panic
	Error = log.Error
	Warn  = log.Warn
	Info  = log.Info
	Debug = log.Debug
	Trace = log.Trace
	Ctx   = zerolog.Ctx
	// Levels
	FatalLevel = zerolog.FatalLevel
	PanicLevel = zerolog.PanicLevel
	ErrorLevel = zerolog.ErrorLevel
	WarnLevel  = zerolog.WarnLevel
	InfoLevel  = zerolog.InfoLevel
	DebugLevel = zerolog.DebugLevel
	TraceLevel = zerolog.TraceLevel
	NoLevel    = zerolog.NoLevel
	Disabled   = zerolog.Disabled
)

Functions

func NewSlogHandler added in v1.5.0

func NewSlogHandler(opts ...Option) slog.Handler

func NewStackTraceError added in v1.2.0

func NewStackTraceError(format string, a ...any) error

Types

type Config

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

type ConsoleWriter added in v1.6.0

type ConsoleWriter = zerolog.ConsoleWriter

Types

func NewConsoleWriter added in v1.4.0

func NewConsoleWriter(opts ...Option) ConsoleWriter

type Level added in v1.6.0

type Level = zerolog.Level

type Logger added in v1.6.0

type Logger = zerolog.Logger

func New

func New(opts ...Option) Logger

type Option

type Option func(*Config)

func WithExcludeFields added in v1.4.0

func WithExcludeFields(fields ...string) Option

func WithLevel

func WithLevel(level Level) Option

func WithNoCaller added in v1.6.0

func WithNoCaller() Option

func WithNoColor added in v1.4.0

func WithNoColor() Option

func WithNoStackTrace added in v1.6.0

func WithNoStackTrace() Option

func WithNoTimestamp added in v1.4.0

func WithNoTimestamp() Option

func WithWriter

func WithWriter(writers ...io.Writer) Option

type SLogHandler added in v1.5.0

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

func (*SLogHandler) Enabled added in v1.5.0

func (h *SLogHandler) Enabled(_ context.Context, level slog.Level) bool

func (*SLogHandler) Handle added in v1.5.0

func (h *SLogHandler) Handle(ctx context.Context, record slog.Record) error

func (*SLogHandler) WithAttrs added in v1.5.0

func (h *SLogHandler) WithAttrs(as []slog.Attr) slog.Handler

func (*SLogHandler) WithGroup added in v1.5.0

func (h *SLogHandler) WithGroup(name string) slog.Handler

type StackTrace added in v1.2.0

type StackTrace struct {
	Frames []runtime.Frame
}

func NewStackTrace added in v1.2.0

func NewStackTrace(skip int) StackTrace

func (*StackTrace) String added in v1.2.0

func (s *StackTrace) String() string

type StackTraceError added in v1.2.0

type StackTraceError struct {
	Stack StackTrace
	// contains filtered or unexported fields
}

func (StackTraceError) Error added in v1.2.0

func (e StackTraceError) Error() string

func (StackTraceError) Unwrap added in v1.2.0

func (e StackTraceError) Unwrap() error

Jump to

Keyboard shortcuts

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