log

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: May 12, 2026 License: MIT Imports: 27 Imported by: 0

Documentation

Index

Constants

View Source
const DefaultMaxSize = 1024

DefaultMaxSize is the default maximum size of a single log message or value in bytes. It's also the maximum number of elements in a slice value.

View Source
const NameKey = "log"

NameKey is the key used to log the name of the logger.

Variables

View Source
var (
	TraceIDKey      = "trace_id"
	SpanIDKey       = "span_id"
	RequestIDKey    = "request_id"
	MessageKey      = "msg"
	ErrorMessageKey = "err"
	TimestampKey    = "time"
	SeverityKey     = "level"
	HTTPMethodKey   = "http.method"
	HTTPURLKey      = "http.url"
	HTTPFromKey     = "http.remote_addr"
	HTTPStatusKey   = "http.status"
	HTTPDurationKey = "http.time_ms"
	HTTPBytesKey    = "http.bytes"
	HTTPBodyKey     = "http.body"
	GRPCServiceKey  = "grpc.service"
	GRPCMethodKey   = "grpc.method"
	GRPCCodeKey     = "grpc.code"
	GRPCStatusKey   = "grpc.status"
	GRPCDurationKey = "grpc.time_ms"
	LoomServiceKey  = "loom.service"
	LoomMethodKey   = "loom.method"
)
View Source
var (
	ColorSeverityDebug = "\033[37m"
	ColorSeverityInfo  = "\033[34m"
	ColorSeverityWarn  = "\033[33m"
	ColorSeverityError = "\033[1;31m"
)

Export color codes

View Source
var TimestampFormatLayout = time.RFC3339

TimestampFormatLayout is used to set the layout for our TimestampKey (default "time") values. Default format is time.RFC3339.

Functions

func Client

Client wraps the given roundtripper and log requests and responses using the clue logger stored in the request context.

func Context

func Context(ctx context.Context, opts ...LogOption) context.Context

Context initializes a context for logging.

func Debug

func Debug(ctx context.Context, keyvals ...Fielder)

Debug writes the key/value pairs to the log output if the log context is configured to log debug messages (via WithDebug).

func DebugEnabled

func DebugEnabled(ctx context.Context) bool

DebugEnabled returns true if the given context has debug logging enabled.

func Debugf

func Debugf(ctx context.Context, format string, v ...any)

Debugf sets the key MessageKey (default "msg") and calls Debug. Arguments are handled in the manner of fmt.Printf.

func Endpoint

func Endpoint(e loom.Endpoint) loom.Endpoint

Endpoint is a Loom endpoint middleware that adds the service and method names to the logged key/value pairs.

func Error

func Error(ctx context.Context, err error, keyvals ...Fielder)

Error flushes the log buffer and disables buffering if not already disabled. Error then sets the ErrorMessageKey (default "err") key with the given error and writes the key/value pairs to the log output.

func Errorf

func Errorf(ctx context.Context, err error, format string, v ...any)

Errorf sets the key MessageKey (default "msg") and calls Error. Arguments are handled in the manner of fmt.Printf.

func Fatal

func Fatal(ctx context.Context, err error, keyvals ...Fielder)

Fatal is equivalent to Error followed by a call to os.Exit(1)

func Fatalf

func Fatalf(ctx context.Context, err error, format string, v ...any)

Fatalf is equivalent to Errorf followed by a call to os.Exit(1)

func FlushAndDisableBuffering

func FlushAndDisableBuffering(ctx context.Context)

FlushAndDisableBuffering flushes the log entries to the writer and stops buffering the given context.

func FormatJSON

func FormatJSON(e *Entry) []byte

FormatJSON is a log formatter that prints entries using JSON. Entries are formatted as follows:

{
  "time": "TIMESTAMP", // UTC timestamp in RFC3339 format
  "level": "SEVERITY", // one of DEBUG, INFO or ERROR
  "key1": "val1",      // entry key/value pairs
  "key2": "val2",
  ...
}

note: the implementation avoids using reflection (and thus the json package) for efficiency.

Output can be customised with log.TimestampKey, log.TimestampFormatLayout, and log.SeverityKey.

func FormatTerminal

func FormatTerminal(e *Entry) []byte

FormatTerminal is a log formatter that prints entries suitable for terminal that supports colors. It prints entries in the following format:

SEVERITY[seconds] key=val key=val ...

Where SEVERITY is one of DEBG, INFO or ERRO, seconds is the number of seconds since the application started, message is the log message, and key=val are the entry key/value pairs. The severity and keys are colored according to the severity (gray for debug entries, blue for info entries and red for errors).

func FormatText

func FormatText(e *Entry) []byte

FormatText is the default log formatter when not running in a terminal, it prints entries using the logfmt format:

time=TIME level=SEVERITY KEY=VAL KEY=VAL ...

Where TIME is the UTC timestamp in RFC3339 format, SEVERITY is one of "debug", "info" or "error", and KEY=VAL are the entry key/value pairs. Values are quoted and escaped according to the logfmt specification.

Output can be customised with log.TimestampKey, log.TimestampFormatLayout, and log.SeverityKey.

func HTTP

func HTTP(logCtx context.Context, opts ...HTTPLogOption) func(http.Handler) http.Handler

HTTP returns a HTTP middleware that performs two tasks:

  1. Enriches the request context with the logger specified in logCtx.
  2. Logs HTTP request details, except when WithDisableRequestLogging is set or URL path matches a WithPathFilter regex.

HTTP panics if logCtx was not created with Context.

func Info

func Info(ctx context.Context, keyvals ...Fielder)

Info writes the key/value pairs to the log buffer or output if buffering is disabled.

func Infof

func Infof(ctx context.Context, format string, v ...any)

Infof sets the key MessageKey (default "msg") and calls Info. Arguments are handled in the manner of fmt.Printf.

func IsTerminal

func IsTerminal() bool

IsTerminal returns true if the process is running in a terminal.

func IsTracing

func IsTracing(ctx context.Context) bool

IsTracing returns true if the context contains a trace created via the go.opentelemetry.io/otel/trace package. It is the default DisableBufferingFunc used by newly created loggers.

func MustContainLogger

func MustContainLogger(logCtx context.Context)

MustContainLogger will panic if the given context is missing the logger.

It can be used during server initialisation when you have a function or middleware that you want to ensure receives a context with a logger.

func Print

func Print(ctx context.Context, keyvals ...Fielder)

Print writes the key/value pairs to the log output ignoring buffering.

func Printf

func Printf(ctx context.Context, format string, v ...any)

Printf sets the key MessageKey (default "msg") and calls Print. Arguments are handled in the manner of fmt.Printf.

func StreamClientInterceptor

func StreamClientInterceptor(opts ...GRPCLogOption) grpc.StreamClientInterceptor

StreamClientInterceptor returns a stream interceptor that logs the request with the logger contained in the request context if any.

func StreamServerInterceptor

func StreamServerInterceptor(logCtx context.Context, opts ...GRPCLogOption) grpc.StreamServerInterceptor

StreamServerInterceptor returns a stream interceptor that performs two tasks: 1. Enriches the request context with the logger specified in logCtx. 2. Logs details of the stream call, unless the WithDisableCallLogging option is provided. StreamServerInterceptor panics if logCtx was not created with Context.

func UnaryClientInterceptor

func UnaryClientInterceptor(opts ...GRPCLogOption) grpc.UnaryClientInterceptor

UnaryClientInterceptor returns a unary interceptor that logs the request with the logger contained in the request context if any.

func UnaryServerInterceptor

func UnaryServerInterceptor(logCtx context.Context, opts ...GRPCLogOption) grpc.UnaryServerInterceptor

UnaryServerInterceptor returns a unary interceptor that performs two tasks: 1. Enriches the request context with the logger specified in logCtx. 2. Logs details of the unary call, unless the WithDisableCallLogging option is provided. UnaryServerInterceptor panics if logCtx was not created with Context.

func Warn

func Warn(ctx context.Context, keyvals ...Fielder)

Warn writes the key/value pairs to the log buffer or output if buffering is disabled, with SeverityWarn.

func Warnf

func Warnf(ctx context.Context, format string, v ...any)

Warnf sets the key MessageKey (default "msg") and calls Warn. Arguments are handled in the manner of fmt.Printf.

func With

func With(ctx context.Context, keyvals ...Fielder) context.Context

With creates a copy of the given log context and appends the given key/value pairs to it. Values must be strings, numbers, booleans, nil or a slice of these types.

func WithContext

func WithContext(parentCtx, logCtx context.Context) context.Context

WithContext will inject the second context in the given one.

It is useful when building middleware handlers such as log.HTTP

Types

type AWSLogger

type AWSLogger struct {
	context.Context
}

AWSLogger returns an AWS SDK compatible logger.

func AsAWSLogger

func AsAWSLogger(ctx context.Context) *AWSLogger

AsAWSLogger returns an AWS SDK compatible logger.

Usage:

import "github.com/aws/aws-sdk-go-v2/config"
import "github.com/CaliLuke/loom/clue/log"

ctx := log.Context(context.Background())
httpc := &http.Client{Transport: otelhttp.NewTransport(http.DefaultTransport)}
cfg, err := config.LoadDefaultConfig(ctx,
    config.WithHTTPClient(httpc),
    config.WithLogger(log.AsAWSLogger(ctx)))

func (*AWSLogger) Logf

func (l *AWSLogger) Logf(classification logging.Classification, format string, v ...any)

func (*AWSLogger) WithContext

func (l *AWSLogger) WithContext(ctx context.Context) logging.Logger

type DisableBufferingFunc

type DisableBufferingFunc func(context.Context) bool

DisableBufferingFunc is a function that returns true if the logger should disable buffering for the given context.

type Entry

type Entry struct {
	Time     time.Time
	Severity Severity
	KeyVals  kvList
}

Log entry

type Fielder

type Fielder interface {
	LogFields() []KV
}

Fielder is an interface that will return a slice of KV

type Fields

type Fields map[string]any

Fields allows to quickly define fields for cases where you are OK with non-deterministic order of the fields

func (Fields) LogFields

func (f Fields) LogFields() []KV

type FormatFunc

type FormatFunc func(e *Entry) []byte

FormatFunc is a function that formats a log entry.

type GRPCClientLogOption deprecated

type GRPCClientLogOption = GRPCLogOption

GRPCClientLogOption is a function that applies a configuration option to a GRPC client interceptor logger.

Deprecated: Use GRPCLogOption instead.

type GRPCLogOption

type GRPCLogOption func(*grpcOptions)

GRPCLogOption is a function that applies a configuration option to a GRPC interceptor logger.

func WithCallLogFunc

func WithCallLogFunc(logFunc func(ctx context.Context, keyvals ...Fielder)) GRPCLogOption

WithCallLogFunc returns a GRPC logger option that configures the logger to use the given log function instead of log.Print() as default.

func WithDisableCallID

func WithDisableCallID() GRPCLogOption

WithDisableCallID returns a GRPC logger option that disables the generation of request IDs.

func WithDisableCallLogging

func WithDisableCallLogging() GRPCLogOption

WithDisableCallLogging returns a GRPC logger option that disables call logging.

func WithErrorFunc

func WithErrorFunc(iserr func(codes.Code) bool) GRPCLogOption

WithErrorFunc returns a GRPC logger option that configures the logger to consider the given function to determine if a GRPC status code is an error.

type HTTPClientLogOption

type HTTPClientLogOption func(*httpClientOptions)

HTTPClientLogOption is a function that applies a configuration option to a HTTP client logger.

func WithErrorStatus

func WithErrorStatus(status int) HTTPClientLogOption

WithErrorStatus returns a HTTP client logger option that configures the logger to log errors for responses with the given status code.

func WithLogBodyOnError

func WithLogBodyOnError() HTTPClientLogOption

WithLogBodyOnError returns a HTTP client logger option that configures the logger to log the response body when the response status code is an error.

type HTTPLogOption

type HTTPLogOption func(*httpLogOptions)

HTTPLogOption is a function that applies a configuration option to log HTTP middleware.

func WithDisableRequestID

func WithDisableRequestID() HTTPLogOption

WithDisableRequestID returns a HTTP middleware option that disables the generation of request IDs.

func WithDisableRequestLogging

func WithDisableRequestLogging() HTTPLogOption

WithDisableRequestLogging returns a HTTP middleware option that disables logging of HTTP requests.

func WithPathFilter

func WithPathFilter(filter *regexp.Regexp) HTTPLogOption

WithPathFilter adds a path filter to the HTTP middleware. Requests whose path match the filter are not logged. WithPathFilter can be called multiple times to add multiple filters.

func WithRequestLogFunc

func WithRequestLogFunc(logFunc func(ctx context.Context, keyvals ...Fielder)) HTTPLogOption

WithRequestLogFunc returns a HTTP middleware option that configures the logger to use the given log function instead of log.Print() as default.

type KV

type KV struct {
	K string
	V any
}

KV represents a key/value pair. Values must be strings, numbers, booleans, nil or a slice of these types.

func Span

func Span(ctx context.Context) (kvs []KV)

Span is a log key/value pair generator function that can be used to log trace and span IDs. Usage:

ctx := log.Context(ctx, WithFunc(log.Span))
log.Printf(ctx, "message")

Output: trace_id=<trace id> span_id=<span id> message

func (KV) LogFields

func (kv KV) LogFields() []KV

type LogOption

type LogOption func(*options)

LogOption is a function that applies a configuration option to a logger.

func WithDebug

func WithDebug() LogOption

WithDebug enables debug logging and disables buffering.

func WithDisableBuffering

func WithDisableBuffering(fn DisableBufferingFunc) LogOption

WithDisableBuffering sets the DisableBufferingFunc called to assess whether buffering should be disabled.

func WithFileLocation

func WithFileLocation() LogOption

WithFileLocation adds the "file" key to each log entry with the parent directory, file and line number of the caller: "file=dir/file.go:123".

func WithFormat

func WithFormat(fn FormatFunc) LogOption

WithFormat sets the log format.

This option exists for backward compatibility. When used in conjunction with WithOutputs, it updates the first output format.

func WithFunc

func WithFunc(fn func(context.Context) []KV) LogOption

WithFunc sets a key/value pair generator function to be called with every log entry. The generated key/value pairs are added to the log entry.

func WithMaxSize

func WithMaxSize(n int) LogOption

WithMaxSize sets the maximum size of a single log message or value.

func WithNoDebug

func WithNoDebug() LogOption

WithNoDebug disables debug logging.

func WithOutput

func WithOutput(w io.Writer) LogOption

WithOutput sets the log output.

This option exists for backward compatibility. When used in conjunction with WithOutputs, it updates the first output writer.

func WithOutputs

func WithOutputs(outputs ...Output) LogOption

WithOutputs sets the log outputs.

Each output formats the entry then writes it to its writer. This makes it possible to log to multiple destinations with independent formats (e.g. terminal colors on stdout and JSON to a file).

type LogrSink

type LogrSink struct {
	context.Context
	// contains filtered or unexported fields
}

LogrSink returns a logr LogSink compatible logger.

func ToLogrSink

func ToLogrSink(ctx context.Context) *LogrSink

ToLogrSink returns a logr.LogSink.

Usage:

import "github.com/CaliLuke/loom/clue/log"

ctx := log.Context(context.Background())
sink := log.ToLogrSink(ctx)
logger := logr.New(sink)

func (*LogrSink) Enabled

func (l *LogrSink) Enabled(level int) bool

func (*LogrSink) Error

func (l *LogrSink) Error(err error, msg string, keysAndValues ...any)

func (*LogrSink) Info

func (l *LogrSink) Info(level int, msg string, keysAndValues ...any)

func (*LogrSink) Init

func (l *LogrSink) Init(info logr.RuntimeInfo)

func (*LogrSink) WithName

func (l *LogrSink) WithName(name string) logr.LogSink

func (*LogrSink) WithValues

func (l *LogrSink) WithValues(keysAndValues ...any) logr.LogSink

type MiddlewareLogger

type MiddlewareLogger interface {
	Log(keyvals ...any) error
}

MiddlewareLogger is the minimal structured logger interface used by Loom middleware adapters.

func AsLoomMiddlewareLogger

func AsLoomMiddlewareLogger(ctx context.Context) MiddlewareLogger

AsLoomMiddlewareLogger creates a middleware-compatible logger that can be used when configuring generated HTTP or gRPC servers.

Usage:

// HTTP server:
import loomhttp "github.com/CaliLuke/loom/http"
import httpmdlwr "github.com/CaliLuke/loom/http/middleware"
...
mux := loomhttp.NewMuxer()
handler := httpmdlwr.LogContext(log.AsLoomMiddlewareLogger)(mux)

// gRPC server:
import "google.golang.org/grpc"
import grpcmiddleware "github.com/grpc-ecosystem/go-grpc-middleware"
import grpcmdlwr "github.com/CaliLuke/loom/grpc/middleware"
...
srv := grpc.NewServer(
    grpcmiddleware.WithUnaryServerChain(grpcmdlwr.UnaryServerLogContext(log.AsLoomMiddlewareLogger)),
)

type Output

type Output struct {
	// Writer receives the formatted log bytes.
	Writer io.Writer
	// Format turns a log entry into bytes suitable for Writer.
	Format FormatFunc
}

Output configures where log entries are written and how they are formatted.

Output is the unit of configuration for "fanout" logging: a single log entry can be written to multiple outputs, each with its own formatting.

Writer and Format must be non-nil.

type Severity

type Severity int

Log severity enum

const (
	SeverityDebug Severity = iota + 1
	SeverityInfo
	SeverityWarn
	SeverityError
)

func (Severity) Code

func (l Severity) Code() string

Code returns a 4-character code for the log severity.

func (Severity) Color

func (l Severity) Color() string

Color returns an escape sequence that colors the output for the given severity.

func (Severity) String

func (l Severity) String() string

String returns a string representation of the log severity.

type StdLogger

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

StdLogger implements an interface compatible with the stdlib log package.

func AsStdLogger

func AsStdLogger(ctx context.Context) *StdLogger

AsStdLogger adapts a Loom logger to a stdlib compatible logger.

func (*StdLogger) Fatal

func (l *StdLogger) Fatal(v ...any)

Fatal is equivalent to l.Print() followed by a call to os.Exit(1).

func (*StdLogger) Fatalf

func (l *StdLogger) Fatalf(format string, v ...any)

Fatalf is equivalent to l.Printf() followed by a call to os.Exit(1).

func (*StdLogger) Fatalln

func (l *StdLogger) Fatalln(v ...any)

Fatalln is equivalent to l.Println() followed by a call to os.Exit(1).

func (*StdLogger) Panic

func (l *StdLogger) Panic(v ...any)

Panic is equivalent to l.Print() followed by a call to panic().

func (*StdLogger) Panicf

func (l *StdLogger) Panicf(format string, v ...any)

Panicf is equivalent to l.Printf() followed by a call to panic().

func (*StdLogger) Panicln

func (l *StdLogger) Panicln(v ...any)

Panicln is equivalent to l.Println() followed by a call to panic().

func (*StdLogger) Print

func (l *StdLogger) Print(v ...any)

Print print to the logger. Arguments are handled in the manner of fmt.Print.

func (*StdLogger) Printf

func (l *StdLogger) Printf(format string, v ...any)

Printf prints to the logger. Arguments are handled in the manner of fmt.Printf.

func (*StdLogger) Println

func (l *StdLogger) Println(v ...any)

Println prints to the logger. Arguments are handled in the manner of fmt.Println.

Jump to

Keyboard shortcuts

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