logging

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Apr 9, 2025 License: Apache-2.0 Imports: 11 Imported by: 0

README

logging

semantic-release Release license release Go Report Card

What Is It

A modern, structured logging library for Go applications built on top of the standard library's log/slog package. This library provides a flexible and powerful logging solution with support for:

  • Structured logging with key-value pairs
  • Context-aware logging
  • HTTP request and response logging middleware
  • Conditional logging with OnError
  • Multiple output formats (JSON, text)
  • Custom field mapping
  • Caller information

Getting Started

package main

import (
    "github.com/Circle-Protocol/logging"
)

func main() {
    // Simple logging
    logging.Info("Hello, world!")
    
    // Structured logging with fields
    logging.WithFields("user", "john", "action", "login").Info("User logged in")
    
    // Conditional logging (only logs if err is not nil)
    err := someOperation()
    logging.OnError(err).Error("Operation failed")
}

Supported Go Versions

For security reasons, we only support and recommend the use of one of the latest two Go versions (✅).

Version Supported
<1.23
1.23
1.24

License

This library is licensed under the Apache License 2.0. See the LICENSE file for details.

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Documentation

Index

Constants

View Source
const (
	FormatterText = "text"
	FormatterJSON = "json"
)

Format constants

View Source
const (
	OutputStdout = "stdout"
	OutputStderr = "stderr"
	OutputFile   = "file"
)

Default output destinations

Variables

View Source
var ErrNilClient = &clientError{"nil client provided"}

ErrNilClient is returned when a nil client is provided to EnableHTTPClient

Functions

func Debug

func Debug(args ...interface{})

Debug logs a debug message

func Debugf

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

Debugf logs a formatted debug message

func Debugln

func Debugln(args ...interface{})

Debugln logs a debug message with a newline

func EnableHTTPClient

func EnableHTTPClient(c *http.Client, opts ...ClientLoggerOption) error

EnableHTTPClient adds slog functionality to the HTTP client. It attempts to obtain a logger with WithContext. If no logger is in the context, it tries to use a fallback logger, which might be set by WithFallbackLogger. If no logger was found finally, the Transport is executed without logging.

func Error

func Error(args ...interface{})

Error logs an error message

func Errorf

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

Errorf logs a formatted error message

func Errorln

func Errorln(args ...interface{})

Errorln logs an error message with a newline

func Fatal

func Fatal(args ...interface{})

Fatal logs a fatal message and exits with status code 1

func Fatalf

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

Fatalf logs a formatted fatal message and exits with status code 1

func Fatalln

func Fatalln(args ...interface{})

Fatalln logs a fatal message with a newline and exits with status code 1

func FromContext

func FromContext(ctx context.Context) (logger *slog.Logger, ok bool)

FromContext takes a Logger from the context, if it was previously set by ToContext

func GetLogger

func GetLogger() *slog.Logger

GetLogger returns the default logger instance

func Info

func Info(args ...interface{})

Info logs an info message

func Infof

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

Infof logs a formatted info message

func Infoln

func Infoln(args ...interface{})

Infoln logs an info message with a newline

func Logf

func Logf(level slog.Level, format string, args ...interface{})

Logf logs a formatted message with the specified level

func Logln

func Logln(level slog.Level, args ...interface{})

Logln logs a message with a newline and the specified level

func Middleware

func Middleware(options ...MiddlewareOption) func(http.Handler) http.Handler

Middleware enables request logging and sets a logger to the request context. Use FromContext to obtain the logger anywhere in the request lifetime.

The default logger is slog.Default(), with the request's URL and Method as preset attributes. When the request terminates, an INFO line with the Status Code and amount written to the client is printed. This behavior can be modified with options.

func Panic

func Panic(args ...interface{})

Panic logs a panic message and panics

func Panicf

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

Panicf logs a formatted panic message and panics

func Panicln

func Panicln(args ...interface{})

Panicln logs a panic message with a newline and panics

func RequestToAttr

func RequestToAttr(req *http.Request) slog.Attr

RequestToAttr converts an HTTP request to a structured slog attribute containing method and URL information

func ResponseToAttr

func ResponseToAttr(resp *http.Response) slog.Attr

ResponseToAttr converts an HTTP response to a structured slog attribute containing status and content length information

func SetIDKey

func SetIDKey(key string)

SetIDKey sets the key used for log entry IDs

func SetLevel

func SetLevel(level slog.Level)

SetLevel configures the minimum log level for the default logger while preserving the existing output writer

func SetOutput

func SetOutput(out io.Writer)

SetOutput configures the output destination for the default logger while preserving the existing log level

func StringerValuer

func StringerValuer(s fmt.Stringer) slog.LogValuer

StringerValuer returns a Valuer that forces the logger to use the type's String method, even in json output mode. By wrapping the type we defer String being called to the point we actually log.

func ToContext

func ToContext(ctx context.Context, logger *slog.Logger) context.Context

ToContext sets a Logger to the context. If ctx is nil, a new background context is created. If logger is nil, the default logger is used.

func Warn

func Warn(args ...interface{})

Warn logs a warning message

func Warnf

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

Warnf logs a formatted warning message

func Warning

func Warning(args ...interface{})

Warning is an alias for Warn (maintained for backward compatibility)

func Warningf

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

Warningf is an alias for Warnf (maintained for backward compatibility)

func Warningln

func Warningln(args ...interface{})

Warningln is an alias for Warnln (maintained for backward compatibility)

func Warnln

func Warnln(args ...interface{})

Warnln logs a warning message with a newline

func WithAttrs

func WithAttrs(attrs ...slog.Attr) *slog.Logger

WithAttrs returns a new logger with the specified attributes

func WithContext

func WithContext(ctx context.Context) *slog.Logger

WithContext returns a logger from the context if present, otherwise returns the default logger

func WithGroup

func WithGroup(name string) *slog.Logger

WithGroup returns a new logger with the specified group name

Types

type ClientLoggerOption

type ClientLoggerOption func(*logRoundTripper)

ClientLoggerOption is a function that configures a logRoundTripper

func WithClientDurationFunc

func WithClientDurationFunc(df func(time.Time) time.Duration) ClientLoggerOption

WithClientDurationFunc allows overriding the request duration for testing.

func WithClientGroup

func WithClientGroup(name string) ClientLoggerOption

WithClientGroup groups the log attributes produced by the client.

func WithClientRequestAttr

func WithClientRequestAttr(requestToAttr func(*http.Request) slog.Attr) ClientLoggerOption

WithClientRequestAttr allows customizing the information used from a request as request attributes.

func WithClientResponseAttr

func WithClientResponseAttr(responseToAttr func(*http.Response) slog.Attr) ClientLoggerOption

WithClientResponseAttr allows customizing the information used from a response as response attributes.

func WithFallbackLogger

func WithFallbackLogger(logger *slog.Logger) ClientLoggerOption

WithFallbackLogger uses the passed logger if none was found in the context.

type Config

type Config struct {
	// Level sets the minimum log level (debug, info, warn, error)
	Level string `json:"level" yaml:"level"`

	// Formatter configures the log output format and options
	Formatter Formatter `json:"formatter" yaml:"formatter"`

	// AddSource adds source code information to log entries
	AddSource bool `json:"addSource" yaml:"addSource"`

	// Output specifies where logs should be written (default: stderr)
	Output string `json:"output" yaml:"output"`
}

Config defines the configuration for the logging system

func NewConfig

func NewConfig(opts ...ConfigOption) *Config

NewConfig creates a new Config with default values

func (*Config) Apply

func (c *Config) Apply() error

Apply applies the configuration to create a new logger

func (*Config) CreateLogger

func (c *Config) CreateLogger() (*slog.Logger, error)

CreateLogger creates a new logger based on the configuration

func (*Config) UnmarshalJSON

func (c *Config) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface

func (*Config) UnmarshalYAML

func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error

UnmarshalYAML implements the yaml.Unmarshaler interface

type ConfigOption

type ConfigOption func(*Config)

ConfigOption is a function that modifies a Config

func WithAddSource

func WithAddSource(enable bool) ConfigOption

WithAddSource enables source code information in logs

func WithFormatterData

func WithFormatterData(key string, value interface{}) ConfigOption

WithFormatterData adds custom data to the formatter

func WithJSONFormatter

func WithJSONFormatter() ConfigOption

WithJSONFormatter sets the formatter to JSON

func WithLevel

func WithLevel(level string) ConfigOption

WithLevel sets the log level

func WithOutput

func WithOutput(output string) ConfigOption

WithOutput sets the output destination

func WithTextFormatter

func WithTextFormatter() ConfigOption

WithTextFormatter sets the formatter to text

type Entry

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

Entry represents a log entry with additional functionality for conditional logging and field management

func EntryWithContext

func EntryWithContext(ctx context.Context) *Entry

EntryWithContext creates a new entry with the given context

func Log

func Log(id string) *Entry

Log creates a new entry with an ID (maintained for backward compatibility)

func LogWithFields

func LogWithFields(id string, fields ...interface{}) *Entry

LogWithFields creates a new entry with an ID and the given fields (maintained for backward compatibility)

func New

func New() *Entry

New instantiates a new entry with the default logger

func NewWithContext

func NewWithContext(ctx context.Context) *Entry

NewWithContext instantiates a new entry with the default logger and context

func OnError

func OnError(err error) *Entry

OnError sets the error. The log will only be printed if err is not nil

func WithError

func WithError(err error) *Entry

WithError creates a new entry with the given error

func WithFields

func WithFields(fields ...interface{}) *Entry

WithFields creates a new entry with the given fields

func (*Entry) Debug

func (e *Entry) Debug(args ...interface{})

Debug logs a debug message

func (*Entry) Debugf

func (e *Entry) Debugf(format string, args ...interface{})

Debugf logs a formatted debug message

func (*Entry) Debugln

func (e *Entry) Debugln(args ...interface{})

Debugln logs a debug message with a newline

func (*Entry) Error

func (e *Entry) Error(args ...interface{})

Error logs an error message

func (*Entry) Errorf

func (e *Entry) Errorf(format string, args ...interface{})

Errorf logs a formatted error message

func (*Entry) Errorln

func (e *Entry) Errorln(args ...interface{})

Errorln logs an error message with a newline

func (*Entry) Fatal

func (e *Entry) Fatal(args ...interface{})

Fatal logs a fatal message and exits with status code 1

func (*Entry) Fatalf

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

Fatalf logs a formatted fatal message and exits with status code 1

func (*Entry) Fatalln

func (e *Entry) Fatalln(args ...interface{})

Fatalln logs a fatal message with a newline and exits with status code 1

func (*Entry) Info

func (e *Entry) Info(args ...interface{})

Info logs an info message

func (*Entry) Infof

func (e *Entry) Infof(format string, args ...interface{})

Infof logs a formatted info message

func (*Entry) Infoln

func (e *Entry) Infoln(args ...interface{})

Infoln logs an info message with a newline

func (*Entry) Log

func (e *Entry) Log(level slog.Level, args ...interface{})

Log logs a message with the specified level

func (*Entry) Logf

func (e *Entry) Logf(level slog.Level, format string, args ...interface{})

Logf logs a formatted message with the specified level

func (*Entry) Logln

func (e *Entry) Logln(level slog.Level, args ...interface{})

Logln logs a message with a newline and the specified level

func (*Entry) OnError

func (e *Entry) OnError(err error) *Entry

OnError sets the error. The log will only be printed if err is not nil

func (*Entry) Panic

func (e *Entry) Panic(args ...interface{})

Panic logs a panic message and panics

func (*Entry) Panicf

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

Panicf logs a formatted panic message and panics

func (*Entry) Panicln

func (e *Entry) Panicln(args ...interface{})

Panicln logs a panic message with a newline and panics

func (*Entry) SetFields

func (e *Entry) SetFields(fields ...interface{}) *Entry

SetFields sets the given fields on the entry It panics if the length of fields is odd

func (*Entry) Warn

func (e *Entry) Warn(args ...interface{})

Warn logs a warning message

func (*Entry) Warnf

func (e *Entry) Warnf(format string, args ...interface{})

Warnf logs a formatted warning message

func (*Entry) Warning

func (e *Entry) Warning(args ...interface{})

Warning is an alias for Warn (maintained for backward compatibility)

func (*Entry) Warningf

func (e *Entry) Warningf(format string, args ...interface{})

Warningf is an alias for Warnf (maintained for backward compatibility)

func (*Entry) Warningln

func (e *Entry) Warningln(args ...interface{})

Warningln is an alias for Warnln (maintained for backward compatibility)

func (*Entry) Warnln

func (e *Entry) Warnln(args ...interface{})

Warnln logs a warning message with a newline

func (*Entry) WithContext

func (e *Entry) WithContext(ctx context.Context) *Entry

WithContext sets the context for the entry

func (*Entry) WithError

func (e *Entry) WithError(err error) *Entry

WithError adds an error field to the entry

func (*Entry) WithField

func (e *Entry) WithField(key string, value interface{}) *Entry

WithField adds a field to the entry

func (*Entry) WithFields

func (e *Entry) WithFields(fields map[string]interface{}) *Entry

WithFields adds multiple fields to the entry

func (*Entry) WithTime

func (e *Entry) WithTime(t time.Time) *Entry

WithTime adds a time field to the entry

type Formatter

type Formatter struct {
	// Format specifies the output format (json or text)
	Format string `json:"format" yaml:"format"`

	// Data contains additional formatter-specific options
	Data map[string]interface{} `json:"data" yaml:"data"`
}

Formatter defines the log format configuration

type LoggedWriter

type LoggedWriter interface {
	http.ResponseWriter

	// Attr is called after the next handler in the Middleware returns and
	// the complete response should have been written.
	//
	// The returned Attribute should be a [slog.Group]
	// containing response Attributes.
	Attr() slog.Attr

	// Err is called by the middleware to check if the underlying writer
	// returned an error. If so, the middleware will print an ERROR line.
	Err() error
}

LoggedWriter stores information regarding the HTTP response. This might be status code, amount of data written or headers.

type MiddlewareOption

type MiddlewareOption func(*middleware)

MiddlewareOption is a function that configures a middleware instance

func WithDurationFunc

func WithDurationFunc(df func(time.Time) time.Duration) MiddlewareOption

WithDurationFunc allows overriding the request duration for testing.

func WithIDFunc

func WithIDFunc(nextID func() slog.Attr) MiddlewareOption

WithIDFunc enables the creation of request IDs in the middleware, which are then attached to the logger.

func WithLoggedWriter

func WithLoggedWriter(wrap func(w http.ResponseWriter) LoggedWriter) MiddlewareOption

WithLoggedWriter allows customizing the writer from which post-request attributes are taken.

func WithMiddlewareGroup

func WithMiddlewareGroup(name string) MiddlewareOption

WithMiddlewareGroup groups the log attributes produced by the middleware.

func WithMiddlewareLogger

func WithMiddlewareLogger(logger *slog.Logger) MiddlewareOption

WithLogger sets the passed logger with request attributes into the Request's context.

func WithRequestAttr

func WithRequestAttr(requestToAttr func(*http.Request) slog.Attr) MiddlewareOption

WithRequestAttr allows customizing the information used from a request as request attributes.

Jump to

Keyboard shortcuts

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