log

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2022 License: MIT Imports: 9 Imported by: 0

README

go-log

Simplified application logger powered by zerolog

Go Reference Go Module

AboutBuilt WithPrerequisitesInstallationUsageContributingDonateLicense

About

go-log is a simplified logger package for Go applications. Using the Zero Allocation JSON Logger (zerolog) under the hood, it simplifies the logging of application-wide messages. It supports three logging modes: Default, Pretty, and JSON. Logs are directed to the console by default, but can be buffered or redirected to a log file instead.

Built With

The project uses the following core software components:

  • Zero Allocation JSON Logger - Go package providing a fast and simple logger dedicated to JSON output.
  • Testify - Go unit-testing toolkit with common assertions and mocks.

Prerequisites

go-log requires Go version 1.16 or later to be installed on your system.

Installation

go get -u go.markdumay.org/log

Usage

Import go-log into your application to start using the logger. By default, go-log writes the log messages to the console. Please refer to the package documentation for more details. The following code snippet illustrates the basic usage of go-log.

package main

import (
    "go.markdumay.org/log"
)

func main() {
    // show an info message using default formatting, expected output:
    // This is an info log
    log.Info("This is an info log")

    // show an error message using default formatting, expected output:
    // ERROR  Error message
    log.Info("Error message")

    // switch to pretty formatting
    log.InitLogger(log.Pretty)

    // show a warning using pretty formatting, expected output:
    // 2006-01-02T15:04:05Z07:00 | WARN   | Warning
    log.Warn("Warning")

    // switch to JSON formatting
    log.InitLogger(log.JSON)

    // switch to debug level as minimum level
    log.SetGlobalLevel(log.DebugLevel)

    // show a debug message using JSON formatting, expected output:
    // {"level":"debug","time":"2006-01-02T15:04:05Z07:00","message":"Testing level debug"}
    log.Debugf("Testing level %s", "debug")
}

Contributing

go-log welcomes contributions of any kind. It is recommended to create an issue to discuss your intended contribution before submitting a larger pull request though. Please consider the following guidelines when contributing:

  • Address all linting recommendations from golangci-lint run (using .golangci.yml from the repository).
  • Ensure the code is covered by one or more unit tests (using Testify when applicable).
  • Follow the recommendations from Effective Go and the Uber Go Style Guide.

The following steps decribe how to submit a Pull Request:

  1. Clone the repository and create a new branch
    $ git checkout https://github.com/markdumay/go-log.git -b name_for_new_branch
    
  2. Make and test the changes
  3. Submit a Pull Request with a comprehensive description of the changes

Donate

Buy Me A Coffee

License

The go-log codebase is released under the MIT license. The documentation (including the "README") is licensed under the Creative Commons (CC BY-NC 4.0) license.

Documentation

Overview

Package log is a simplified logger package for Go applications. Using the Zero Allocation JSON Logger (zerolog) under the hood, it simplifies the logging of application-wide messages. It supports three logging modes: Default, Pretty, and JSON. Logs are directed to the console by default, but can be buffered or redirected to a log file instead.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AppendWriter

func AppendWriter(w Writer)

AppendWriter appends a writer to the list of writers known by Logger. Logs are duplicated for each known writer.

func Bypass

func Bypass(msg string)

Bypass logs an info message using a default logging format, bypassing the current level and format. Use this function to ensure custom logs are written as-is to the standardized logging stream(s). If multiple writers are specified, the message is duplicated for all writers.

func Debug

func Debug(msg string)

Debug logs a debugging message.

func DebugE

func DebugE(e error, msg string)

DebugE logs a debugging error.

func Debugf

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

Debugf logs a formatted debugging message.

func Error

func Error(msg string)

Error logs an error message.

func ErrorE

func ErrorE(e error, msg string)

ErrorE logs an error.

func Errorf

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

Errorf logs a formatted error message.

func Fatal

func Fatal(msg string)

Fatal logs a fatal message. It exits the program with exit code 1. Fatal messages are never buffered.

func FatalE

func FatalE(e error, msg string)

FatalE logs a fatal error. It exits the program with exit code 1. Fatal messages are never buffered.

func Fatalf

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

Fatalf logs a formatted fatal error. It exits the program with exit code 1. Fatal messages are never buffered.

func Flush

func Flush()

Flush writes all buffered logs to the active logger and empties the buffer. Subsequent logs are no longer buffered.

func Hold

func Hold()

Hold instructs the active logger to buffer all incoming logs instead of writing them to current output stream. Use Flush to write the buffered logs and to empty the buffer.

func Info

func Info(msg string)

Info logs a message.

func InfoE

func InfoE(e error, msg string)

InfoE logs an error.

func Infof

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

Infof logs a formatted message.

func InitLogger

func InitLogger(format Format)

InitLogger initializes the global logger with the desired format. Output is written to STDOUT with color coding.

func InitLoggerWithWriter

func InitLoggerWithWriter(format Format, noColor bool, writer ...Writer)

InitLoggerWithWriter initializes the global logger with the desired format, writer(s), and color coding.

func Msg

func Msg(level Level, msg string)

Msg logs a message at the desired level.

func MsgE

func MsgE(level Level, e error, msg string)

MsgE logs an error at the desired level.

func Msgf

func Msgf(level Level, format string, v ...interface{})

Msgf logs a formatted message at the desired level.

func RemoveWriter

func RemoveWriter(w Writer)

RemoveWriter removes a writer from the list of writers known by Logger. The request is ignored when the writer cannot be found.

func SetFormatting

func SetFormatting(format Format, noColor bool)

SetFormatting adjusts the logging format of the current logger.

func SetGlobalLevel

func SetGlobalLevel(l Level)

SetGlobalLevel sets the logging level for all loggers.

func UpdateWriter

func UpdateWriter(old Writer, new Writer) error

UpdateWriter replaces an old writer from the list of writers known by Logger with a new writer. UpdateWriter returns an error if the old writer cannot be found.

func Warn

func Warn(msg string)

Warn logs a warning.

func WarnE

func WarnE(e error, msg string)

WarnE logs an error as warning.

func Warnf

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

Warnf logs a formatted warning.

Types

type Buffer

type Buffer []string

Buffer defines a simple buffer to store logs in memory.

func (*Buffer) Write

func (b *Buffer) Write(p []byte) (n int, err error)

Write implements the io.Writer interface for Buffer.

type BufferedWriter

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

BufferedWriter captures application logs and stores them in a local buffer. Log lines are separated by newline characters and are added one at a time.

func NewBufferedWriter

func NewBufferedWriter(format Format, noColor bool) *BufferedWriter

NewBufferedWriter creates a log writer that buffers logs in memory.

func (*BufferedWriter) Buffer

func (b *BufferedWriter) Buffer() Buffer

Buffer retrieves a copy of the local buffer managed by BufferedWriter.

func (*BufferedWriter) Reset

func (b *BufferedWriter) Reset()

Reset removes all existing logs from the local buffer.

func (*BufferedWriter) SetFormatting

func (b *BufferedWriter) SetFormatting(format Format, noColor bool)

SetFormatting updates the log format and color coding of an existing BufferedWriter.

func (*BufferedWriter) Write

func (b *BufferedWriter) Write(p []byte) (n int, err error)

Write implements the io.Writer interface for BufferedWriter.

type ConsoleWriter

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

ConsoleWriter implements a log writer that supports different styles of formatting. It uses zerolog.ConsoleWriter under the hood.

func NewConsoleWriter

func NewConsoleWriter(format Format, noColor bool, out io.Writer) *ConsoleWriter

NewConsoleWriter creates a new ConsoleWriter that supports Default formatting and Pretty formatting, next to the default JSON formatting provided by zerolog.

func (*ConsoleWriter) SetFormatting

func (w *ConsoleWriter) SetFormatting(f Format, noColor bool)

SetFormatting updates the log format and color coding of an existing ConsoleWriter.

func (*ConsoleWriter) Write

func (w *ConsoleWriter) Write(p []byte) (n int, err error)

Write implements the io.Writer interface for ConsoleWriter.

type Format

type Format int

Format defines the type of logging format to use, either Default, Pretty, or JSON.

const (
	// Default prints logs as standard console output (no timestamp and level prefixes), for example:
	// 		// Listing snapshots
	Default Format = iota

	// Pretty prints logs as semi-structured messages with a timestamp and level prefix, for example:
	// 		// 2020-12-17T07:12:57+01:00 | INFO   | Listing snapshots
	Pretty

	// JSON prints logs as JSON strings, for example:
	// 		// {"level":"info","time":"2020-12-17T07:12:57+01:00","message":"Listing snapshots"}
	JSON
)

Defines a pseudo enumeration of possible logging formats.

func ParseFormat

func ParseFormat(formatStr string) (Format, error)

ParseFormat converts a format string into a typed Format value. It returns an error if the input string does not match known values.

func (Format) MarshalText

func (f Format) MarshalText() (text []byte, err error)

MarshalText implements the TextMarshaler interface for Format.

func (Format) String

func (f Format) String() string

String converts a typed log format to it's string representation.

type Level

type Level int8

Level defines the minimum level of logs to display. Supported levels are DebugLevel, InfoLevel, WarnLevel, ErrorLevel, FatalLevel, and PanicLevel. Level is an abstraction of a type with the same name provided by the underlying zerolog package.

const (
	// DebugLevel defines the debugging log level.
	DebugLevel Level = iota

	// InfoLevel defines the info log level.
	InfoLevel

	// WarnLevel defines the warning log level.
	WarnLevel

	// ErrorLevel defines the error log level.
	ErrorLevel

	// FatalLevel defines the fatal log level.
	FatalLevel

	// PanicLevel defines the panic log level.
	PanicLevel

	// NoLevel defines an absent log level.
	NoLevel

	// Disabled disables the logger.
	Disabled

	// TraceLevel defines the trace log level.
	TraceLevel Level = -1
)

Defines a pseudo enumeration of possible logging levels, copied from zerolog to hide implementation details.

func GlobalLevel

func GlobalLevel() Level

GlobalLevel retrieves the logging level of all loggers.

func ParseLevel

func ParseLevel(levelStr string) (Level, error)

ParseLevel converts a level string into a typed Level value. It returns an error if the input string does not match known values.

func (Level) MarshalText

func (l Level) MarshalText() (text []byte, err error)

MarshalText implements the TextMarshaler interface for Level.

func (Level) String

func (l Level) String() string

String converts a typed log level to its string representation.

type Logger

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

Logger is a simplified logger that uses zerolog under the hood. It supports three logging modes, being Default, Pretty, and JSON. In default mode, all logs are printed using simplified formatting. This format omits timestamps and puts a simple keyword in front of the message to indicate the level. For Info logs, the level is omitted. Pretty mode structures the logs using a timestamp (RFC 3339) and level indicator, separated by the symbol '|'. Finally, JSON mode formats the log as a JSON message, consisting of the attributes timestamp (RFC 3339), level, and message.

A default logger is instantiated by default. The following examples illustrate how to use the package.

package main

import (
	"go.markdumay.org/log"
)

func main() {
	// show an info message using default formatting, expected output:
	// This is an info log
	log.Info("This is an info log")

	// show an error message using default formatting, expected output:
	// ERROR  Error message
	log.Info("Error message")

	// switch to pretty formatting
	log.InitLogger(log.Pretty)

	// show a warning using pretty formatting, expected output:
	// 2006-01-02T15:04:05Z07:00 | WARN   | Warning
	log.Warn("Warning")

	// switch to JSON formatting
	log.InitLogger(log.JSON)

	// switch to debug level as minimum level
	log.SetGlobalLevel(log.DebugLevel)

	// show a debug message using JSON formatting, expected output:
	// {"level":"debug","time":"2006-01-02T15:04:05Z07:00","message":"Testing level debug"}
	log.Debugf("Testing level %s", "debug")
}

func NewLogger

func NewLogger(format Format, noColor bool, writer ...Writer) *Logger

NewLogger initializes a new logger with the desired format.

func (*Logger) Write

func (l *Logger) Write(p []byte) (n int, err error)

Write implements the io.Writer interface for Logger.

type Message

type Message struct {
	Level   Level
	Time    time.Time
	Message string
	Error   string
	// contains filtered or unexported fields
}

Message defines the structure of JSON-formatted log messages produced by zerolog.

func UnmarshalLog

func UnmarshalLog(bytes []byte) (*Message, error)

UnmarshalLog converts json bytes into a Message instance.

type Writer

type Writer interface {
	io.Writer
	SetFormatting(format Format, noColor bool)
}

Writer defines the interface for writers to be compatible with Logger. It adds the SetFormatting function to ensure custom writers are synchronized with the application settings.

Jump to

Keyboard shortcuts

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