log

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Apr 5, 2025 License: MIT Imports: 13 Imported by: 0

README

log

License Go Reference Go Report Card GitHub CI codecov

Simple, fast, opinionated logging for command line applications 🪵

demo

Project Description

log is a tiny and incredibly simple logging library designed to output nicely presented, human readable, levelled log messages. Ideal for command line applications ✨

There are many great logging libraries for Go out there, but so many of them are IMO too flexible and too complicated. I wanted a small, minimal dependency, opinionated logger I could use everywhere across all my Go projects (which are mostly command line applications). So I made one 🚀

Installation

go get github.com/FollowTheProcess/log@latest

Quickstart

package main

import (
    "fmt"
    "os"

    "github.com/FollowTheProcess/log"
)

func main() {
    logger := log.New(os.Stderr)

    logger.Debug("Debug me") // By default this one won't show up, default log level is INFO
    logger.Info("Some information here", "really", true)
    logger.Warn("Uh oh!")
    logger.Error("Goodbye")
}

Usage Guide

Make a new logger

logger := log.New(os.Stderr)
Levels

log provides a levelled logger with the normal levels you'd expect:

log.LevelDebug
log.LevelInfo
log.LevelWarn
log.LevelError

You write log lines at these levels with the corresponding methods on the Logger:

logger.Debug("...") // log.LevelDebug
logger.Info("...")  // log.LevelInfo
logger.Warn("...")  // log.LevelWarn
logger.Error("...") // log.LevelError

And you can configure a Logger to display logs at or higher than a particular level with the WithLevel option...

logger := log.New(os.Stderr, log.WithLevel(log.LevelDebug))
Key Value Pairs

log provides "semi structured" logs in that the message is free form text but you can attach arbitrary key value pairs to any of the log methods

logger.Info("Doing something", "cache", true, "duration", 30 * time.Second, "number", 42)

You can also create a "sub logger" with persistent key value pairs applied to every message

sub := logger.With("sub", true)

sub.Info("Hello from the sub logger", "subkey", "yes") // They can have their own per-method keys too!

demo

Prefixes

log lets you apply a "prefix" to your logger, either as an option to log.New or by creating a "sub logger" with that prefix!

logger := log.New(os.Stderr, log.Prefix("http"))

Or...

logger := log.New(os.Stderr)
prefixed := logger.Prefixed("http")

demo

Documentation

Overview

Package log provides a Logger primarily intended for terminal based command line programs.

The logs it produces are semi-structured with key value pairs being formatted as key=value but are primarily intended to be human readable and easy on the eye with a good choice of colours, ideal for command line applications that have a --debug or --verbose flag that enables extra logging.

log emphasis simplicity and efficiency so there aren't too many knobs to twiddle, you just get a consistent, easy to use, simple logger with minimal overhead.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func WithContext added in v0.2.0

func WithContext(ctx context.Context, logger *Logger) context.Context

WithContext stores the given logger in a context.Context.

The logger may be retrieved from the context with FromContext.

Types

type Level

type Level int

Level is a log level.

const (
	// LevelDebug is the debug log level, intended for verbose logging modes or internal debugging.
	LevelDebug Level = -4

	// LevelInfo is the info log level, this is the default level, intended for progress updates
	// and other informational messages.
	LevelInfo Level = 0

	// LevelWarn is the warning log level, intended for raising recoverable issues to the user. Warning
	// logs should refer to events that are worth flagging to the user but the program can easily
	// recover from such as a missing configuration file when the application can fall back to defaults.
	LevelWarn Level = 4

	// LevelError is the error log level. This is the highest log level provided by log and is intended
	// for signalling non-recoverable errors to the user. Typically followed by an actual go error and
	// possibly program exit.
	LevelError Level = 8
)

type Logger

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

Logger is a command line logger. It is safe to use across concurrently executing goroutines.

func FromContext added in v0.2.0

func FromContext(ctx context.Context) *Logger

FromContext returns the Logger from a context.Context.

If the context does not contain a logger, a default logger is returned.

func New

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

New returns a new Logger configured to write to w.

The logger can be configured by passing a number of functional options to set things like level, prefix etc.

func (*Logger) Debug

func (l *Logger) Debug(msg string, kv ...any)

Debug writes a debug level log line.

func (*Logger) Error

func (l *Logger) Error(msg string, kv ...any)

Error writes an error level log line.

func (*Logger) Info

func (l *Logger) Info(msg string, kv ...any)

Info writes an info level log line.

func (*Logger) Prefixed

func (l *Logger) Prefixed(prefix string) *Logger

Prefixed returns a new Logger with the given prefix.

The returned logger is otherwise an exact clone of the caller.

func (*Logger) Warn

func (l *Logger) Warn(msg string, kv ...any)

Warn writes a warning level log line.

func (*Logger) With

func (l *Logger) With(kv ...any) *Logger

With returns a new Logger with the given persistent key value pairs.

The returned logger is otherwise an exact clone of the caller.

type Option

type Option func(*Logger)

Option is a functional option for configuring a Logger.

func Prefix

func Prefix(prefix string) Option

Prefix sets a prefix for the logger.

If set to a non-empty string, the prefix is shown on every log line prior to the message and any key value pairs.

func TimeFormat

func TimeFormat(format string) Option

TimeFormat sets the format of the time information.

The layout is the standard Go time.Format and defaults to time.RFC3339.

func TimeFunc

func TimeFunc(fn func() time.Time) Option

TimeFunc sets the mechanism by which the logger knows the current time.

Most usage will not set this option, but it's handy if you want to provide a deterministic time for your logs such as during testing etc.

The Logger will default to time.Now (with UTC) if this option is not set.

func WithLevel

func WithLevel(level Level) Option

WithLevel sets the log level, that is; the minimum level of logs that will show up.

Directories

Path Synopsis
examples
demo command
keys command
prefix command

Jump to

Keyboard shortcuts

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