log

package module
v0.5.6 Latest Latest
Warning

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

Go to latest
Published: Mar 14, 2022 License: Apache-2.0 Imports: 11 Imported by: 2

README

log

Build Status Go Report Card GoDoc

A simple, leveled, fast, zero allocation, structured logging package for Go. Designed to make logging on the hot path dirt cheap, dependency free and my life easier.

A simpler textual key/value format is also available by setting Config.Text to true

By default log entries with the same level and message within each second, will be sampled to cap CPU and I/O load under high logging activity. This behavior can be disabled by setting Config.EnableSampling to false

Usage

Default package logger
import (
    "github.com/brunotm/log"
)

func main() {
    // Simple logging
    log.Info("info message").String("key", "value").Write()
    // Text format:
    // time="2021-03-25T13:32:50.391Z" level="info" caller="_local/main.go:26" app="app1" message="info message" key="value"
    // JSON format:
    // {"time":"2021-03-25T13:33:20.547Z", "level":"info", "caller":"_local/main.go:26", "app":"app1", "message":"info message", "key":"value"}
}
New customized logger
package main

import (
    "os"

    "github.com/brunotm/log"
)

func main() {
    config := DefaultConfig
    config.Level = DEBUG
    config.Format = FormatText // Enable text logging

    // New logger with added context
    l := New(os.Stdout, config).
        With(func(e Entry) {
            e.String("app", "app1")
        })

    // Simple logging
    l.Info("info message").String("key", "value").Write()
    // Text format:
    // time="2021-03-25T13:32:50.391Z" level="info" caller="_local/main.go:26" app="app1" message="info message" key="value"
    // JSON format:
    // {"time":"2021-03-25T13:33:20.547Z", "level":"info", "caller":"_local/main.go:26", "app":"app1", "message":"info message", "key":"value"}

    l.Warn("warn message").Bool("flag", false).Write()
    // Text format:
    // time="2021-03-25T13:32:50.391Z" level="warn" caller="_local/main.go:29" app="app1" message="warn message" flag=false
    // JSON format:
    // {"time":"2021-03-25T13:33:20.547Z", "level":"warn", "caller":"_local/main.go:29", "app":"app1", "message":"warn message", "flag":false}

    l.Error("caught an error").String("error", "request error").Write()
    // Text format:
    // time="2021-03-25T13:32:50.391Z" level="error" caller="_local/main.go:32" app="app1" message="caught an error" error="request error"
    // JSON format:
    // {"time":"2021-03-25T13:33:20.547Z", "level":"error", "caller":"_local/main.go:32", "app":"app1", "message":"caught an error", "error":"request error"}

    l.Fatal("caught an unrecoverable error").Error("error", errors.New("some error")).Write()
    // Text format:
    // time="2021-03-25T13:32:50.391Z" level="fatal" caller="_local/main.go:35" app="app1" message="caught an unrecoverable error" error="some error"
    // JSON format:
    // {"time":"2021-03-25T13:33:20.547Z", "level":"fatal", "caller":"_local/main.go:35", "app":"app1", "message":"caught an unrecoverable error", "error":"some error"}
}

Performance on a 2,3 GHz Intel Core i5, 2017 13-inch Macbook Pro

Message: {"level":"info","time":"2019-01-30T20:54:07.029Z","message":"informational message","string value":"text","int value":8,"float":722727272.0099,"int":8,"float value":722727272.0099}

pkg: github.com/brunotm/log
BenchmarkLogNoSampling-8         1672147               704 ns/op               0 B/op          0 allocs/op
BenchmarkLogWithSampling-8      10266382               111 ns/op               0 B/op          0 allocs/op
BenchmarkLogNoLevel-8           340966922                3.46 ns/op            0 B/op          0 allocs/op

Contact

Bruno Moura brunotm@gmail.com

License

log source code is available under the Apache Version 2.0 License

Documentation

Overview

Package log provides a simple, leveled, fast, zero allocation, json structured logging package for Go

Example
config := DefaultConfig
config.Level = DEBUG
config.Format = FormatText // Enable text logging

// New logger with added context
l := New(os.Stdout, config).
	With(func(e Entry) {
		e.String("app", "app1")
	})

// Simple logging
l.Info("info message").String("key", "value").Write()
// Text format:
// time="2021-03-25T13:32:50.391Z" level="info" caller="_local/main.go:26" app="app1" message="info message" key="value"
// JSON format:
// {"time":"2021-03-25T13:33:20.547Z", "level":"info", "caller":"_local/main.go:26", "app":"app1", "message":"info message", "key":"value"}

l.Warn("warn message").Bool("flag", false).Write()
// Text format:
// time="2021-03-25T13:32:50.391Z" level="warn" caller="_local/main.go:29" app="app1" message="warn message" flag=false
// JSON format:
// {"time":"2021-03-25T13:33:20.547Z", "level":"warn", "caller":"_local/main.go:29", "app":"app1", "message":"warn message", "flag":false}

l.Error("caught an error").String("error", "request error").Write()
// Text format:
// time="2021-03-25T13:32:50.391Z" level="error" caller="_local/main.go:32" app="app1" message="caught an error" error="request error"
// JSON format:
// {"time":"2021-03-25T13:33:20.547Z", "level":"error", "caller":"_local/main.go:32", "app":"app1", "message":"caught an error", "error":"request error"}

l.Fatal("caught an unrecoverable error").Error("error", errors.New("some error")).Write()
// Text format:
// time="2021-03-25T13:32:50.391Z" level="fatal" caller="_local/main.go:35" app="app1" message="caught an unrecoverable error" error="some error"
// JSON format:
// {"time":"2021-03-25T13:33:20.547Z", "level":"fatal", "caller":"_local/main.go:35", "app":"app1", "message":"caught an unrecoverable error", "error":"some error"}

Index

Examples

Constants

View Source
const (
	// DEBUG log level
	DEBUG = Level(1)
	// INFO log level
	INFO = Level(2)
	// WARN log level
	WARN = Level(3)
	// ERROR log level
	ERROR = Level(4)
	// FATAL log level
	FATAL = Level(5)
)
View Source
const (
	// ISO8601 time format
	ISO8601 = "2006-01-02T15:04:05.999Z07:00"
	// Unix time in seconds
	Unix = "unix"
	// UnixMilli time in milliseconds
	UnixMilli = "unix_milli"
	// UnixNano time in nanoseconds
	UnixNano = "unix_nano"
)

Variables

View Source
var (

	// DefaultConfig for logger
	DefaultConfig = Config{
		Format:         FormatJSON,
		Level:          INFO,
		EnableCaller:   true,
		CallerSkip:     0,
		EnableTime:     true,
		TimeField:      "time",
		TimeFormat:     ISO8601,
		MessageField:   "message",
		LevelField:     "level",
		EnableSampling: true,
		SamplingTick:   time.Second,
		SamplingStart:  100,
		SamplingFactor: 100,
	}
)

Functions

func SetFormat added in v0.5.1

func SetFormat(f Format)

SetFormat sets the logging format for the default package logger

func SetLevel added in v0.5.1

func SetLevel(l Level)

SetLevel sets the logging level for the default package logger

Types

type Array added in v0.0.2

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

Array value

func (Array) AppendBool added in v0.0.2

func (a Array) AppendBool(value bool) (array Array)

AppendBool value to array

func (Array) AppendFloat added in v0.0.2

func (a Array) AppendFloat(value float64) (array Array)

AppendFloat value to array

func (Array) AppendInt added in v0.0.2

func (a Array) AppendInt(value int64) (array Array)

AppendInt value to array

func (Array) AppendNull added in v0.1.1

func (a Array) AppendNull() (array Array)

AppendNull value to array

func (Array) AppendString added in v0.0.2

func (a Array) AppendString(value string) (array Array)

AppendString value to array

func (Array) AppendUint added in v0.0.2

func (a Array) AppendUint(value uint64) (array Array)

AppendUint value to array

func (Array) Array added in v0.0.2

func (a Array) Array(key string, fn func(Array)) (array Array)

Array creates a json array

func (Array) Object added in v0.0.2

func (a Array) Object(fn func(Object)) (array Array)

Object creates a json object

type Config

type Config struct {
	Format         Format        // Log format
	Level          Level         // Log level
	EnableCaller   bool          // Enable caller info
	CallerSkip     int           // Skip level of callers, useful if wrapping the logger
	EnableTime     bool          // Enable log timestamps
	TimeField      string        // Field name for the log timestamp
	TimeFormat     string        // Time Format for log timestamp
	MessageField   string        // Field name for the log message
	LevelField     string        // Field name for the log level
	EnableSampling bool          // Enable log sampling to reduce CPU and I/O load
	SamplingTick   time.Duration // Resolution at which entries will be sampled
	SamplingStart  int           // Start sampling after this number of similar entries within SamplingTick
	SamplingFactor int           // Reduction factor when sampling
}

Config type for logger

type Entry

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

Entry is a structured log entry. A entry is not safe for concurrent use. A entry must be logged by calling Log(), and cannot be reused after.

func Debug added in v0.2.3

func Debug(message string) (entry Entry)

Debug creates a new log entry with the given message with the default package logger.

func Error added in v0.2.3

func Error(message string) (entry Entry)

Error creates a new log entry with the given message with the default package logger.

func Fatal added in v0.5.1

func Fatal(message string) (entry Entry)

Fatal creates a new log entry with the given message with the default package logger. After write, Fatal calls os.Exit(1) terminating the running program

func Info added in v0.2.3

func Info(message string) (entry Entry)

Info creates a new log entry with the given message with the default package logger.

func Warn added in v0.2.3

func Warn(message string) (entry Entry)

Warn creates a new log entry with the given message with the default package logger.

func (Entry) Bool

func (e Entry) Bool(key string, value bool) (entry Entry)

Bool adds the given bool key/value

func (Entry) Bytes

func (e Entry) Bytes() (data []byte)

Bytes return the current entry bytes. This is intended to be used in hooks That will be applied after calling Log(). The returned []byte is not a copy and must not be modified directly.

func (Entry) Duration added in v0.5.5

func (e Entry) Duration(key string, value time.Duration) (entry Entry)

Duration adds the given duration key/value as a string

func (Entry) Error

func (e Entry) Error(key string, value error) (entry Entry)

Error adds the given error key/value

func (Entry) Float32 added in v0.5.0

func (e Entry) Float32(key string, value float32) (entry Entry)

Float32 adds the given float32 key/value

func (Entry) Float64 added in v0.5.0

func (e Entry) Float64(key string, value float64) (entry Entry)

Float64 adds the given float64 key/value

func (Entry) Int

func (e Entry) Int(key string, value int) (entry Entry)

Int adds the given int key/value

func (Entry) Int16 added in v0.5.0

func (e Entry) Int16(key string, value int16) (entry Entry)

Int16 adds the given int16 key/value

func (Entry) Int32 added in v0.5.0

func (e Entry) Int32(key string, value int32) (entry Entry)

Int32 adds the given int32 key/value

func (Entry) Int64 added in v0.5.0

func (e Entry) Int64(key string, value int64) (entry Entry)

Int64 adds the given int64 key/value

func (Entry) Int8 added in v0.5.0

func (e Entry) Int8(key string, value int8) (entry Entry)

Int8 adds the given int8 key/value

func (Entry) Level

func (e Entry) Level() (level Level)

Level returns the log level of current entry.

func (Entry) Null added in v0.1.1

func (e Entry) Null(key string) (entry Entry)

Null adds a null value for the given key

func (Entry) Printf added in v0.5.4

func (e Entry) Printf(key, format string, args ...interface{}) (entry Entry)

Printf parses the format and args adding it as a key/string value in the log entry. This method is helpful to avoid allocations and extra work when logging with a lower log level than the logger is working with.

func (Entry) String

func (e Entry) String(key string, value string) (entry Entry)

String adds the given string key/value

func (Entry) Time added in v0.5.5

func (e Entry) Time(key string, value time.Time) (entry Entry)

Time adds the given time key/value as an ISO8601 string

func (Entry) Uint

func (e Entry) Uint(key string, value uint) (entry Entry)

Uint adds the given uint16 key/value

func (Entry) Uint16 added in v0.5.0

func (e Entry) Uint16(key string, value uint16) (entry Entry)

Uint16 adds the given uint16 key/value

func (Entry) Uint32 added in v0.5.0

func (e Entry) Uint32(key string, value uint32) (entry Entry)

Uint32 adds the given uint32 key/value

func (Entry) Uint64 added in v0.5.0

func (e Entry) Uint64(key string, value uint64) (entry Entry)

Uint64 adds the given uint key/value

func (Entry) Uint8 added in v0.5.0

func (e Entry) Uint8(key string, value uint8) (entry Entry)

Uint8 adds the given uint8 key/value

func (Entry) Write added in v0.4.0

func (e Entry) Write()

Write logs the current entry. An entry must not be used after calling Write().

type Format added in v0.5.1

type Format uint32

Format is the logging format

var (
	// FormatJSON tells the logger to write json structured messages
	FormatJSON Format = 1

	// FormatText tells the logger to write text structured key=value pairs messages
	FormatText Format = 2
)

func ParseFormat added in v0.5.2

func ParseFormat(fmt string) (f Format, err error)

ParseFormat parses the log format from a string

func (Format) String added in v0.5.2

func (l Format) String() (level string)

type Level

type Level uint32

Level represents the supported log levels

func ParseLevel added in v0.3.0

func ParseLevel(level string) (l Level, err error)

ParseLevel parses the log level from a string

func (Level) String

func (l Level) String() (level string)

type Logger

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

Logger type

func New

func New(writer io.Writer, config Config) (logger *Logger)

New creates a new logger with the give config and writer. A nill writer will be set to ioutil.Discard.

func (*Logger) Debug

func (l *Logger) Debug(message string) (entry Entry)

Debug creates a new log entry with the given message.

func (*Logger) Error

func (l *Logger) Error(message string) (entry Entry)

Error creates a new log entry with the given message.

func (*Logger) Fatal added in v0.4.0

func (l *Logger) Fatal(message string) (entry Entry)

Fatal creates a new log entry with the given message. After write, Fatal calls os.Exit(1) terminating the running program

func (*Logger) Hooks

func (l *Logger) Hooks(f ...func(Entry)) (logger *Logger)

Hooks creates a new logger with functions to apply after the entry is written. Hooks are cumulative and useful for shipping log data to other systems.

func (*Logger) Info

func (l *Logger) Info(message string) (entry Entry)

Info creates a new log entry with the given message.

func (*Logger) SetFormat added in v0.5.1

func (l *Logger) SetFormat(f Format)

SetFormat atomically sets the new log format

func (*Logger) SetLevel added in v0.5.1

func (l *Logger) SetLevel(lv Level)

SetLevel atomically sets the new log level

func (*Logger) Warn

func (l *Logger) Warn(message string) (entry Entry)

Warn creates a new log entry with the given message.

func (*Logger) With

func (l *Logger) With(f ...func(Entry)) (logger *Logger)

With creates a new logger with functions to apply context to the log entries. With functions are cumulative and applied before all other log data.

type Object added in v0.0.2

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

Object value

func (Object) Bool added in v0.0.2

func (o Object) Bool(key string, value bool) (object Object)

Bool adds the given bool key/value

func (Object) Error added in v0.3.2

func (o Object) Error(key string, err error) (object Object)

Error adds a error value for the given key

func (Object) Float64 added in v0.5.0

func (o Object) Float64(key string, value float64) (object Object)

Float64 adds the given float key/value

func (Object) Int64 added in v0.5.0

func (o Object) Int64(key string, value int64) (object Object)

Int64 adds the given int key/value

func (Object) Null added in v0.1.1

func (o Object) Null(key string) (object Object)

Null adds a null value for the given key

func (Object) String added in v0.0.2

func (o Object) String(key string, value string) (object Object)

String adds the given string key/value

func (Object) Uint64 added in v0.5.0

func (o Object) Uint64(key string, value uint64) (object Object)

Uint64 adds the given uint key/value

Jump to

Keyboard shortcuts

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