logf

package module
v0.3.2 Latest Latest
Warning

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

Go to latest
Published: Jul 1, 2022 License: MIT Imports: 10 Imported by: 0

README

logf

Go Reference Go Report Card GitHub Actions

logf is a high performance logging library for Go applications with a minimal API overhead. It emits structured logs (logfmt style) in human readable and machine friendly way. logf aims to be customisable without providing an overwhelming amount of things to configure.

Example

package main

import (
	"errors"
	"time"

	"github.com/mr-karan/logf"
)

func main() {
	logger := logf.New()
	// Basic log.
	logger.Info("starting app")

	// Change verbosity on the fly.
	logger.SetLevel(logf.DebugLevel)
	logger.Debug("meant for debugging app")

	// Add extra keys to the log.
	logger.WithFields(logf.Fields{
		"component": "api",
		"user":      "karan",
	}).Info("logging with some extra metadata")

	// Log with error key.
	logger.WithError(errors.New("this is a dummy error")).Error("error fetching details")

	// Enable `caller` field in the log and specify the number of frames to skip to get the caller. 
	logger.SetCallerFrame(true, 3)
	// Change the default timestamp format.
	logger.SetTimestampFormat(time.RFC3339Nano)

	// Create a logger and add fields which will be logged in every line.
	requestLogger := logger.WithFields(logf.Fields{"request_id": "3MG91VKP", "ip": "1.1.1.1", "method": "GET"})
	requestLogger.Info("request success")
	requestLogger.Warn("this isn't supposed to happen")

	// Log the error and set exit code as 1.
	logger.Fatal("goodbye world")
}
Text Output
timestamp=2022-06-26T11:56:46+05:30 level=info message=starting app caller=/home/karan/Code/Personal/logf/examples/main.go:13
timestamp=2022-06-26T11:56:46+05:30 level=debug message=meant for debugging app caller=/home/karan/Code/Personal/logf/examples/main.go:17 level=debug message=meant for debugging app timestamp=2022-06-26T11:56:46+05:30 caller=/home/karan/Code/Personal/logf/examples/main.go:17
timestamp=2022-06-26T11:56:46+05:30 level=info message=logging with some extra metadata component=api user=karan caller=/home/karan/Code/Personal/logf/examples/main.go:23
timestamp=2022-06-26T11:56:46+05:30 level=error message=error fetching details error=this is a dummy error caller=/home/karan/Code/Personal/logf/examples/main.go:26
timestamp=2022-06-26T11:56:46.412189111+05:30 level=info message=request success ip=1.1.1.1 method=GET request_id=3MG91VKP
timestamp=2022-06-26T11:56:46.412204619+05:30 level=warn message=this isn't supposed to happen ip=1.1.1.1 level=warn message=this isn't supposed to happen method=GET request_id=3MG91VKP timestamp=2022-06-26T11:56:46.412204619+05:30
timestamp=2022-06-26T11:56:46.412218628+05:30 level=fatal message=goodbye world ip=1.1.1.1 level=fatal message=goodbye world method=GET request_id=3MG91VKP timestamp=2022-06-26T11:56:46.412218628+05:30
Console Output

Why another lib

Agreed there are many logging libraries out there but I was dissatisfied with the current options.

logf satisfies my constraints of:

  • Clean API
  • Minimal Dependencies
  • Structured logging but human readable (logfmt!)
  • Sane defaults out of the box

Benchmarks

You can run benchmarks with make bench.

No Colors (Default)
BenchmarkNoField-8                       6167684               196.8 ns/op            64 B/op          3 allocs/op
BenchmarkOneField-8                      4113402               282.4 ns/op           400 B/op          5 allocs/op
BenchmarkThreeFields-8                   3596408               339.3 ns/op           408 B/op          6 allocs/op
BenchmarkErrorField-8                    3658911               327.7 ns/op           432 B/op          7 allocs/op
BenchmarkHugePayload-8                   1420556               852.4 ns/op          1192 B/op         12 allocs/op
BenchmarkThreeFields_WithCaller-8        1682295               730.0 ns/op           776 B/op         12 allocs/op
With Colors
BenchmarkNoField_WithColor-8             4359175               310.6 ns/op            64 B/op          3 allocs/op
BenchmarkOneField_WithColor-8            2322146               528.3 ns/op           400 B/op          5 allocs/op
BenchmarkThreeFields_WithColor-8         1863465               667.4 ns/op           408 B/op          6 allocs/op
BenchmarkErrorField_WithColor-8          2062276               545.7 ns/op           432 B/op          7 allocs/op
BenchmarkHugePayload_WithColor-8          746208              1488 ns/op            1192 B/op         12 allocs/op

For a comparison with existing popular libs, visit uber-go/zap#performance.

Contributors

LICENSE

LICENSE

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type FieldLogger added in v0.3.1

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

func (*FieldLogger) Debug added in v0.3.1

func (l *FieldLogger) Debug(msg string)

func (*FieldLogger) Error added in v0.3.1

func (l *FieldLogger) Error(msg string)

Error emits an error log line.

func (*FieldLogger) Fatal added in v0.3.2

func (l *FieldLogger) Fatal(msg string)

Fatal emits a fatal level log line. It aborts the current program with an exit code of 1.

func (*FieldLogger) Info added in v0.3.1

func (l *FieldLogger) Info(msg string)

Info emits a info log line.

func (*FieldLogger) Warn added in v0.3.1

func (l *FieldLogger) Warn(msg string)

Warn emits a warning log line.

type Fields

type Fields map[string]any

Fields is a map of arbitrary KV pairs which will be used in logfmt representation of the log.

type Level

type Level int

Severity level of the log.

const (
	DebugLevel Level = iota // 0
	InfoLevel               // 1
	WarnLevel               // 2
	ErrorLevel              // 3
	FatalLevel              // 4
)

func (Level) String

func (l Level) String() string

String representation of the log severity.

type Logger

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

Logger is the interface for all log operations related to emitting logs.

func New

func New() *Logger

New instantiates a logger object. It writes to `stderr` as the default and it's non configurable.

func (*Logger) Debug

func (l *Logger) Debug(msg string)

Debug emits a debug log line.

func (*Logger) Error

func (l *Logger) Error(msg string)

Error emits an error log line.

func (*Logger) Fatal

func (l *Logger) Fatal(msg string)

Fatal emits a fatal level log line. It aborts the current program with an exit code of 1.

func (*Logger) Info

func (l *Logger) Info(msg string)

Info emits a info log line.

func (*Logger) SetCallerFrame

func (l *Logger) SetCallerFrame(caller bool, depth int)

SetCallerFrame enables/disables the caller source in the log line.

func (*Logger) SetColorOutput

func (l *Logger) SetColorOutput(color bool)

SetColorOutput enables/disables colored output.

func (*Logger) SetLevel

func (l *Logger) SetLevel(lvl Level)

SetLevel sets the verbosity for logger. Verbosity can be dynamically changed by the caller.

func (*Logger) SetTimestampFormat

func (l *Logger) SetTimestampFormat(f string)

SetTimestampFormat sets the timestamp format for the `timestamp` key.

func (*Logger) SetWriter

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

SetWriter sets the output writer for the logger

func (*Logger) Warn

func (l *Logger) Warn(msg string)

Warn emits a warning log line.

func (*Logger) WithError

func (l *Logger) WithError(err error) *FieldLogger

WithError returns a Logger with the "error" key set to `err`.

func (*Logger) WithFields

func (l *Logger) WithFields(fields Fields) *FieldLogger

WithFields returns a new entry with `fields` set.

type Opts

type Opts struct {
	Writer          io.Writer
	Lvl             Level
	TimestampFormat string
	EnableColor     bool
	EnableCaller    bool
	// CallerSkipFrameCount is the count of the number of frames to skip when computing the file name and line number
	CallerSkipFrameCount int
}

Opts represents various properties to configure logger.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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