logbuch

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Feb 27, 2021 License: MIT Imports: 8 Imported by: 32

README

Logbuch

Go Reference CircleCI Go Report Card Chat on Discord

Simple Go logging library with support for different output channels (io.Writer) for each log level. A formatter can be provided to change the log output formatting.

Installation

To install logbuch, run go get within your project:

go get github.com/emvi/logbuch

Usage

Here is a quick example on how to use the basic functionality of logbuch:

package main

import (
    "os"
    "github.com/emvi/logbuch"
)

func main() {
    // use the default logger (logging to stdout and stderr)
    logbuch.Debug("Hello %s!", "World")
    logbuch.Info("Info")
    logbuch.Warn("Warning")
    logbuch.Error("Error")

    // logging cannot be disabled for errors except you use the DiscardFormatter
    logbuch.SetLevel(logbuch.LevelInfo)
    logbuch.Debug("Don't log this anymore!")

    // create your own logger
    l := logbuch.NewLogger(os.Stdout, os.Stderr)
    l.Debug("Just like the default logger...")
    l.SetFormatter(logbuch.NewDiscardFormatter())
    l.Error("This error will be dropped!")
    
    // or to panic...
    l.Fatal("We are going down! Error code: %d", 123)
}

Formatters

To use formatters you can either implement your own or use one provided by logbuch. There are three kind of formatters provided right now:

StandardFormatter

This is the default. The log output looks like this:

2019-09-19T17:39:02.4326139+02:00 [DEBUG] This is a debug message.
2019-09-19T17:39:02.4326139+02:00 [INFO ] Hello World!
2019-09-19T17:39:02.4326139+02:00 [WARN ] Some formatted message 123.
2019-09-19T17:39:02.4326139+02:00 [ERROR] An error occurred: 123
FieldFormatter

The FieldFormatter prints the log parameters in a structured way. To have a nice logging output, use the logbuch.Fields type together with this:

formatter := logbuch.NewFieldFormatter(logbuch.StandardTimeFormat, "\t\t\t")
logbuch.SetFormatter(formatter)
logbuch.Debug("Debug message", logbuch.Fields{"some": "value", "code": 123})

The log output looks like this:

2019-09-19T17:45:26.6635897+02:00 [DEBUG] Debug message				 some=value code=123
DiscardFormatter

The DiscardFormatter simply drops all log messages (including errors) and can be used to do just that.

Persistent logs

If you want to persist log data, you can use any io.Writer to do so. logbuch comes with a rolling file appender which can be used to store log output into rolling log files. Here is a quick example of it:

package main

import (
    "fmt"
    "github.com/emvi/logbuch"
)

// create a naming schema for log files
type NameSchema struct {
    name string
    counter int
}

func (schema *NameSchema) Name() string {
    schema.counter++
    return fmt.Sprintf("%d_%s.log", schema.counter, schema.name)
}

func main() {
    stdNameSchema := &NameSchema{name: "std"}
    errNameSchema := &NameSchema{name: "err"}

    // create rolling file appenders for stdout and stderr
    // using a maximum of 5 files, 5 MB per file and a buffer of 4 KB
    stdout, _ := logbuch.NewRollingFileAppender(5, 1024*1024*5, 1024*4, "logs", stdNameSchema)
    stderr, _ := logbuch.NewRollingFileAppender(5, 1024*1024*5, 1024*4, "logs", errNameSchema)

    // this is important!
    defer stdout.Close()
    defer stderr.Close()

    // create your logger
    l := logbuch.NewLogger(stdout, stderr)
    l.Info("Log to standard output files...")
    l.Error("Log to standard error files...")
}

This example will create a directory called logs and writes all standard output to files called 1_std.log and all error output to files called 1_err.log for up to 5 files before starting rolling over. Note that you must close the rolling file appenders.

Contribute

See CONTRIBUTING.md

License

MIT

Documentation

Index

Constants

View Source
const (
	// LevelDebug log all messages.
	LevelDebug = iota

	// LevelInfo log info, warning and error messages.
	LevelInfo

	// LevelWarning log warning and error messages.
	LevelWarning

	// LevelError log error messages only.
	LevelError
)
View Source
const (
	// StandardTimeFormat is a synonym for time.RFC3339Nano.
	StandardTimeFormat = time.RFC3339Nano
)

Variables

This section is empty.

Functions

func Debug

func Debug(msg string, params ...interface{})

Debug logs a formatted debug message.

func Error

func Error(msg string, params ...interface{})

Error logs a formatted error message.

func Fatal

func Fatal(msg string, params ...interface{})

Fatal logs a formatted error message and panics.

func Info

func Info(msg string, params ...interface{})

Info logs a formatted info message.

func SetFormatter

func SetFormatter(formatter Formatter)

SetFormatter sets the formatter of the default logger.

func SetLevel

func SetLevel(level int)

SetLevel sets the logging level.

func SetOutput

func SetOutput(stdout, stderr io.Writer)

SetOutput sets the output channels for the default logger. The first parameter is used for debug, info and warning levels. The second one for error level.

func Warn

func Warn(msg string, params ...interface{})

Warn logs a formatted warning message.

Types

type DiscardFormatter

type DiscardFormatter struct{}

DiscardFormatter drops all messages.

func NewDiscardFormatter

func NewDiscardFormatter() *DiscardFormatter

NewDiscardFormatter creates a new DiscardFormatter.

func (*DiscardFormatter) Fmt

func (formatter *DiscardFormatter) Fmt(buffer *[]byte, level int, t time.Time, msg string, params []interface{})

Fmt drops the message.

func (*DiscardFormatter) Pnc

func (formatter *DiscardFormatter) Pnc(msg string, params []interface{})

Pnc formats the given message and panics.

type FieldFormatter

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

FieldFormatter adds fields to the output as key value pairs. The message won't be formatted. It prints log messages starting with the timestamp, followed by the log level, the message and key value pairs. To make this work the first and only parameter must be of type Fields.

Example:

logbuch.Debug("Hello World!", logbuch.Fields{"integer": 123, "string": "test"})

If there is more than one parameter or the type of the parameter is different, all parameters will be appended after the message.

func NewFieldFormatter

func NewFieldFormatter(timeFormat, separator string) *FieldFormatter

NewFieldFormatter creates a new FieldFormatter with given timestamp format and separator between message and key value pairs. The timestamp can be disabled by passing an empty string.

func (*FieldFormatter) Fmt

func (formatter *FieldFormatter) Fmt(buffer *[]byte, level int, t time.Time, msg string, params []interface{})

Fmt formats the message as described for the FieldFormatter.

func (*FieldFormatter) Pnc

func (formatter *FieldFormatter) Pnc(msg string, params []interface{})

Pnc formats the given message and panics.

type Fields

type Fields map[string]interface{}

Fields is used together with the FieldFormatter.

type Formatter

type Formatter interface {
	// Fmt formats a logger message and writes the result into the buffer.
	Fmt(*[]byte, int, time.Time, string, []interface{})

	// Pnc formats the given message and panics.
	Pnc(string, []interface{})
}

Formatter is an interface to format log messages.

type Logger

type Logger struct {

	// PanicOnErr enables panics if the logger cannot write to log output.
	PanicOnErr bool
	// contains filtered or unexported fields
}

Logger writes messages to different io.Writers depending on the log level by using a Formatter.

func NewLogger

func NewLogger(stdout, stderr io.Writer) *Logger

NewLogger creates a new logger using the StandardFormatter for given io.Writers.

func (*Logger) Debug

func (log *Logger) Debug(msg string, params ...interface{})

Debug logs a formatted debug message.

func (*Logger) Error

func (log *Logger) Error(msg string, params ...interface{})

Error logs a formatted error message.

func (*Logger) Fatal

func (log *Logger) Fatal(msg string, params ...interface{})

Fatal logs a formatted error message and panics.

func (*Logger) GetFormatter

func (log *Logger) GetFormatter() Formatter

GetFormatter returns the formatter.

func (*Logger) GetLevel

func (log *Logger) GetLevel() int

GetLevel returns the log level.

func (*Logger) GetOut

func (log *Logger) GetOut(level int) io.Writer

GetOut returns the io.Writer for given level.

func (*Logger) Info

func (log *Logger) Info(msg string, params ...interface{})

Info logs a formatted info message.

func (*Logger) SetFormatter

func (log *Logger) SetFormatter(formatter Formatter)

SetFormatter sets the formatter.

func (*Logger) SetLevel

func (log *Logger) SetLevel(level int)

SetLevel sets the log level.

func (*Logger) SetOut

func (log *Logger) SetOut(level int, out io.Writer)

SetOut sets the io.Writer for given level.

func (*Logger) Warn

func (log *Logger) Warn(msg string, params ...interface{})

Warn logs a formatted warning message.

type NameSchema

type NameSchema interface {
	// Name returns the next file name used to store log data.
	Name() string
}

NameSchema is an interface to generate log file names. If you implement this interface, make sure the Name() method returns unique file names.

type RollingFileAppender

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

RollingFileAppender is a manager for rolling log files. It needs to be closed using the Close() method.

func NewRollingFileAppender

func NewRollingFileAppender(files, size, bufferSize int, dir string, filename NameSchema) (*RollingFileAppender, error)

NewRollingFileAppender creates a new RollingFileAppender. If you pass values below or equal to 0 for files, size or bufferSize, default values will be used. The file output directory is created if required and can be left empty to use the current directory. The filename schema is required. Note that the rolling file appender uses the filename schema you provide, so if it returns the same name on each call, it will overwrite the existing log file. The RollingFileAppender won't clean the log directory on startup. Old log files will stay in place.

func (*RollingFileAppender) Close

func (appender *RollingFileAppender) Close() error

Close flushes the log data and closes all open file handlers.

func (*RollingFileAppender) Flush

func (appender *RollingFileAppender) Flush() error

Flush writes all log data currently in buffer into the currently active log file.

func (*RollingFileAppender) Write

func (appender *RollingFileAppender) Write(p []byte) (n int, err error)

Write writes given data to the rolling log files. This might not happen immediately as the RollingFileAppender uses a buffer. If you want the data to be persisted, call Flush().

type StandardFormatter

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

StandardFormatter is the default formatter. It prints log messages starting with the timestamp, followed by the log level and the formatted message.

func NewStandardFormatter

func NewStandardFormatter(timeFormat string) *StandardFormatter

NewStandardFormatter creates a new StandardFormatter with given timestamp format. The timestamp can be disabled by passing an empty string.

func (*StandardFormatter) Fmt

func (formatter *StandardFormatter) Fmt(buffer *[]byte, level int, t time.Time, msg string, params []interface{})

Fmt formats the message as described for the StandardFormatter.

func (*StandardFormatter) Pnc

func (formatter *StandardFormatter) Pnc(msg string, params []interface{})

Pnc formats the given message and panics.

Jump to

Keyboard shortcuts

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