log

package module
v8.1.2 Latest Latest
Warning

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

Go to latest
Published: Aug 17, 2023 License: MIT Imports: 14 Imported by: 2

README

log

Project status Test Coverage Status Go Report Card GoDoc License

Log is a simple, highly configurable, Structured Logging library

Why another logging library?

There's a lot of great stuff out there, but this library contains a number of unique features noted below using *.

Features

  • Logger is simple, only logic to create the log entry and send it off to the handlers, they take it from there.
  • Handlers are simple to write + easy to register + easy to remove
  • *Ability to specify which log levels get sent to each handler
  • *Handlers & Log Levels are configurable at runtime.
  • *WithError automatically extracts and adds file, line and package in error output.
  • *Convenient context helpers GetContext & SetContext
  • *Works with go-playground/errors extracting wrapped errors, types and tags when used with the WithError interface. This is the default but configurable to support more or other error libraries using SetWithErrorFn.
  • *Default logger for quick prototyping and cli applications. It is automatically removed when you register one of your own.

Installation

Use go get

go get github.com/go-playground/log/v8@latest

Usage

import the log package.

package main

import (
	"io"
	stdlog "log"

	"github.com/go-playground/errors/v5"
	"github.com/go-playground/log/v8"
)

func main() {
	log.RedirectGoStdLog(true)

	// Trace
	defer log.WithTrace().Info("time to run")

	log.Debug("debug")
	log.Info("info")
	log.Notice("notice")
	log.Warn("warn")
	log.Error("error")
	// log.Panic("panic") // this will panic
	log.Alert("alert")
	// log.Fatal("fatal") // this will call os.Exit(1)

	err := errors.New("this is the inner error").AddTags(errors.T("inner", "tag"))
	err = errors.Wrap(err, "this is the wrapping error").AddTags(errors.T("outer", "tag"))

	// logging with fields can be used with any of the above
	log.WithError(err).WithFields(log.F("key", "value")).Info("test info")

	// log unwrapped error
	log.WithError(io.EOF).Error("unwrapped error")

	// predefined global fields
	log.WithDefaultFields(log.Fields{
		log.F("program", "test"),
		log.F("version", "0.1.3"),
	}...)

	log.WithField("key", "value").Info("testing default fields")

	// or request scoped default fields
	logger := log.WithFields(
		log.F("request", "req"),
		log.F("scoped", "sco"),
	)

	logger.WithField("key", "value").Info("test")

	stdlog.Println("This was redirected from Go STD output!")
	log.RedirectGoStdLog(false)
	stdlog.Println("This was NOT redirected from Go STD output!")
}

Adding your own Handler

package main

import (
	"bytes"
	"fmt"

	"github.com/go-playground/log/v8"
)

// CustomHandler is your custom handler
type CustomHandler struct {
	// whatever properties you need
}

// Log accepts log entries to be processed
func (c *CustomHandler) Log(e log.Entry) {

	// below prints to os.Stderr but could marshal to JSON
	// and send to central logging server
	//																						       ---------
	// 				                                                                 |----------> | console |
	//                                                                               |             ---------
	// i.e. -----------------               -----------------     Unmarshal    -------------       --------
	//     | app log handler | -- json --> | central log app | --    to    -> | log handler | --> | syslog |
	//      -----------------               -----------------       Entry      -------------       --------
	//      																         |             ---------
	//                                  									         |----------> | DataDog |
	//          																	        	   ---------
	b := new(bytes.Buffer)
	b.Reset()
	b.WriteString(e.Message)

	for _, f := range e.Fields {
		_, _ = fmt.Fprintf(b, " %s=%v", f.Key, f.Value)
	}
	fmt.Println(b.String())
}

func main() {

	cLog := new(CustomHandler)
	log.AddHandler(cLog, log.AllLevels...)

	// Trace
	defer log.WithTrace().Info("took this long")

	log.Debug("debug")
	log.Info("info")
	log.Notice("notice")
	log.Warn("warn")
	log.Error("error")
	// log.Panic("panic") // this will panic
	log.Alert("alert")
	// log.Fatal("fatal") // this will call os.Exit(1)

	// logging with fields can be used with any of the above
	log.WithField("key", "value").Info("test info")
}
Go 1.21+ slog compatibility

There is a compatibility layer for slog, which allows redirecting slog to this logger and ability to output to an slog.Handler+.

type Definition
Handler This example demonstrates how to redirect the std log and slog to this logger by using it as an slog.Handler.
Redirect This example demonstrates how to redirect the std log and slog to this logger and output back out to any slog.Handler, as well as any other handler(s) registered with this logger.

Log Level Definitions
---------------------

| Level  | Description                                                                                                                                                                                               |
|--------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| Debug  | Info useful to developers for debugging the application, not useful during normal operations.                                                                                                             |
| Info   | Normal operational messages which may be harvested for reporting, measuring throughput, etc. no action required.                                                                                          |
| Notice | Normal but significant condition. Events that are unusual but not error conditions eg. might be summarized in an email to developers or admins to spot potential problems - no immediate action required. |
| Warn   | Warning messages, not an error, but indication that an error will occur if action is not taken, e.g. file system 85% full. Each item must be resolved within a given time.                                |
| Error  | Non-urgent failures, these should be relayed to developers or admins; each item must be resolved within a given time.                                                                                     |
| Panic  | A "panic" condition usually affecting multiple apps/servers/sites. At this level it would usually notify all tech staff on call.                                                                          |
| Alert  | Action must be taken immediately. Should be corrected immediately, therefore notify staff who can fix the problem. An example would be the loss of a primary ISP connection.                              |
| Fatal  | Should be corrected immediately, but indicates failure in a primary system, an example is a loss of a backup ISP connection. ( same as SYSLOG CRITICAL )                                                  |

Handlers
-------------
Pull requests for new handlers are welcome when they don't pull in dependencies, it is preferred to have a dedicated package in this case.

| Handler | Description                                                                                                                              | Docs                                                                                                                                                              |
| ------- | ---------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| json    | Allows for log messages to be sent to any wrtier in json format.                                                                         | [![GoDoc](https://godoc.org/github.com/go-playground/log/handlers/json?status.svg)](https://godoc.org/github.com/go-playground/log/handlers/json)                 |

Package Versioning
----------
This package strictly adheres to semantic versioning guidelines.

Documentation

Index

Constants

View Source
const (
	SlogDebugLevel  slog.Level = slog.LevelDebug
	SlogInfoLevel   slog.Level = slog.LevelInfo
	SlogWarnLevel   slog.Level = slog.LevelWarn
	SlogErrorLevel  slog.Level = slog.LevelError
	SlogNoticeLevel slog.Level = slog.LevelInfo + 2
	SlogPanicLevel  slog.Level = slog.LevelError + 4
	SlogAlertLevel  slog.Level = SlogPanicLevel + 4
	SlogFatalLevel  slog.Level = SlogAlertLevel + 4 // same as syslog CRITICAL
)

slog log levels.

View Source
const (
	// DefaultTimeFormat is the default time format when parsing Time values.
	// it is exposed to allow handlers to use and not have to redefine
	DefaultTimeFormat = "2006-01-02T15:04:05.000000000Z07:00" // RFC3339Nano
)

Variables

AllLevels is an array of all log levels, for easier registering of all levels to a handler

Functions

func AddHandler

func AddHandler(h Handler, levels ...Level)

AddHandler adds a new log handlers and accepts which log levels that handlers will be triggered for

func Alert

func Alert(v ...interface{})

Alert logs an alert log entry

func Alertf

func Alertf(s string, v ...interface{})

Alertf logs an alert log entry with formatting

func BytePool

func BytePool() *byteArrayPool

BytePool returns a sync.Pool of bytes that multiple handlers can use in order to reduce allocation and keep a central copy for reuse.

func Debug

func Debug(v ...interface{})

Debug logs a debug entry

func Debugf

func Debugf(s string, v ...interface{})

Debugf logs a debug entry with formatting

func Error

func Error(v ...interface{})

Error logs an error log entry

func Errorf

func Errorf(s string, v ...interface{})

Errorf logs an error log entry with formatting

func Fatal

func Fatal(v ...interface{})

Fatal logs a fatal log entry

func Fatalf

func Fatalf(s string, v ...interface{})

Fatalf logs a fatal log entry with formatting

func HandleEntry

func HandleEntry(e Entry)

HandleEntry handles the log entry and fans out to all handlers with the proper log level This is exposed to allow for centralized logging whereby the log entry is marshalled, passed to a central logging server, unmarshalled and finally fanned out from there.

func Info

func Info(v ...interface{})

Info logs a normal. information, entry

func Infof

func Infof(s string, v ...interface{})

Infof logs a normal. information, entry with formatting

func Notice

func Notice(v ...interface{})

Notice logs a notice log entry

func Noticef

func Noticef(s string, v ...interface{})

Noticef logs a notice log entry with formatting

func Panic

func Panic(v ...interface{})

Panic logs a panic log entry

func Panicf

func Panicf(s string, v ...interface{})

Panicf logs a panic log entry with formatting

func RedirectGoStdLog

func RedirectGoStdLog(redirect bool)

RedirectGoStdLog is used to redirect Go's internal std log output to this logger AND registers a handler for slog that redirects slog output to this logger.

If you intend to use this log interface with another slog handler then you should not use this function and instead register a handler with slog directly and register the slog redirect, found under the handlers package or other custom redirect handler with this logger.

func RemoveHandler

func RemoveHandler(h Handler)

RemoveHandler removes an existing handler

func SetContext

func SetContext(ctx context.Context, e Entry) context.Context

SetContext sets a log entry into the provided context

func SetExitFunc

func SetExitFunc(fn func(code int))

SetExitFunc sets the provided function as the exit function used in Fatal(), Fatalf(), Panic() and Panicf(). This is primarily used when wrapping this library, you can set this to enable testing (with coverage) of your Fatal() and Fatalf() methods.

func SetWithErrorFn

func SetWithErrorFn(fn func(Entry, error) Entry)

SetWithErrorFn sets a custom WithError function handlers

func Warn

func Warn(v ...interface{})

Warn logs a warning log entry

func Warnf

func Warnf(s string, v ...interface{})

Warnf logs a warning log entry with formatting

func WithDefaultFields

func WithDefaultFields(fields ...Field)

WithDefaultFields adds fields to the underlying logger instance that will be automatically added to ALL log entries.

Types

type Buffer

type Buffer struct {
	B []byte
}

Buffer is a mere wrapper for a byte slice. It is intended to be used by Handlers.

type ConsoleBuilder

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

ConsoleBuilder is used to create a new console logger

func NewConsoleBuilder

func NewConsoleBuilder() *ConsoleBuilder

NewConsoleBuilder creates a new ConsoleBuilder for configuring and creating a new console logger

func (*ConsoleBuilder) Build

func (b *ConsoleBuilder) Build() *Logger

func (*ConsoleBuilder) WithTimestampFormat

func (b *ConsoleBuilder) WithTimestampFormat(format string) *ConsoleBuilder

func (*ConsoleBuilder) WithWriter

func (b *ConsoleBuilder) WithWriter(writer io.Writer) *ConsoleBuilder

type Entry

type Entry struct {
	Message   string    `json:"message"`
	Timestamp time.Time `json:"timestamp"`
	Fields    []Field   `json:"fields"`
	Level     Level     `json:"level"`
	// contains filtered or unexported fields
}

Entry defines a single log entry

func GetContext

func GetContext(ctx context.Context) Entry

GetContext returns the log Entry found in the context, or a new Default log Entry if none is found

func WithError

func WithError(err error) Entry

WithError add a minimal stack trace to the log Entry

func WithField

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

WithField returns a new log entry with the supplied field.

func WithFields

func WithFields(fields ...Field) Entry

WithFields returns a new log entry with the supplied fields appended

func WithTrace

func WithTrace() Entry

WithTrace with add duration of how long the between this function call and the subsequent log

func (Entry) Alert

func (e Entry) Alert(v ...interface{})

Alert logs an alert log entry

func (Entry) Alertf

func (e Entry) Alertf(s string, v ...interface{})

Alertf logs an alert log entry with formatting

func (Entry) Debug

func (e Entry) Debug(v ...interface{})

Debug logs a debug entry

func (Entry) Debugf

func (e Entry) Debugf(s string, v ...interface{})

Debugf logs a debug entry with formatting

func (Entry) Error

func (e Entry) Error(v ...interface{})

Error logs an error log entry

func (Entry) Errorf

func (e Entry) Errorf(s string, v ...interface{})

Errorf logs an error log entry with formatting

func (Entry) Fatal

func (e Entry) Fatal(v ...interface{})

Fatal logs a fatal log entry

func (Entry) Fatalf

func (e Entry) Fatalf(s string, v ...interface{})

Fatalf logs a fatal log entry with formatting

func (Entry) Info

func (e Entry) Info(v ...interface{})

Info logs a normal. information, entry

func (Entry) Infof

func (e Entry) Infof(s string, v ...interface{})

Infof logs a normal. information, entry with formatting

func (Entry) Notice

func (e Entry) Notice(v ...interface{})

Notice logs a notice log entry

func (Entry) Noticef

func (e Entry) Noticef(s string, v ...interface{})

Noticef logs a notice log entry with formatting

func (Entry) Panic

func (e Entry) Panic(v ...interface{})

Panic logs a panic log entry

func (Entry) Panicf

func (e Entry) Panicf(s string, v ...interface{})

Panicf logs a panic log entry with formatting

func (Entry) Warn

func (e Entry) Warn(v ...interface{})

Warn logs a warning log entry

func (Entry) Warnf

func (e Entry) Warnf(s string, v ...interface{})

Warnf logs a warning log entry with formatting

func (Entry) WithError

func (e Entry) WithError(err error) Entry

WithError add a minimal stack trace to the log Entry

func (Entry) WithField

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

WithField returns a new log entry with the supplied field.

func (Entry) WithFields

func (e Entry) WithFields(fields ...Field) Entry

WithFields returns a new log entry with the supplied fields appended

func (Entry) WithTrace

func (e Entry) WithTrace() Entry

WithTrace with add duration of how long the between this function call and the subsequent log

type Field

type Field struct {
	Key   string      `json:"key"`
	Value interface{} `json:"value"`
}

Field is a single Field key and value

func F

func F(key string, value interface{}) Field

F creates a new Field using the supplied key + value. it is shorthand for defining field manually

func G added in v8.1.0

func G(key string, fields ...Field) Field

G creates a new group of fields using the supplied key as the groups name.

type Fields

type Fields []Field

Fields is the type to send to WithFields

type Handler

type Handler interface {
	Log(Entry)
}

Handler is an interface that log handlers need to comply with

type Level

type Level uint8

Level of the log

const (
	DebugLevel Level = iota
	InfoLevel
	NoticeLevel
	WarnLevel
	ErrorLevel
	PanicLevel
	AlertLevel
	FatalLevel // same as syslog CRITICAL
)

Log levels.

func ParseLevel

func ParseLevel(s string) Level

ParseLevel parses the provided strings log level or if not supported return 255

func (Level) MarshalJSON

func (l Level) MarshalJSON() ([]byte, error)

MarshalJSON implementation.

func (Level) String

func (l Level) String() string

func (*Level) UnmarshalJSON

func (l *Level) UnmarshalJSON(b []byte) error

UnmarshalJSON implementation.

type Logger

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

Logger is an instance of the console logger

func (*Logger) Log

func (c *Logger) Log(e Entry)

Log handles the log entry

Directories

Path Synopsis
_examples
handlers
json
Package json implements a JSON handler.
Package json implements a JSON handler.

Jump to

Keyboard shortcuts

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