lumberjack

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Jun 19, 2020 License: BSD-3-Clause Imports: 10 Imported by: 2

README

lumberjack

Simple/Stupid Multi-Backend Logger for Go

Named Lumberjack for obvious punny reasons. (Get it.. Logger... Lumberjack... GET IT?!)

Deal With It

Why

Because I like my logs formatted a certain way, and was tired of duplicating my efforts to setup the boilerplate to log in a particular way. So I made this project for my own purposes to have a quick and easy way to set up logging with levels, formatting, runtime information, and multiple backends.

State of the Project

It is currently in an early state with very basic console printing backend. It's not intended for use in production, but I probably will use it anyway because I'm a masochist.

What's Planned

More Backends!
  • BSON
  • SMTP
  • Syslog
  • Who knows?
Custom Formatting!
  • Using Go's Templating Engine
  • COLOR!! (Who doesn't like color?)

How to use this garbage?

    import "github.com/btnmasher/lumberjack"

    ...

    //Setup the logger instance
    logger = lumberjack.NewLoggerWithDefaults()

    //Add a level (defaults included: INFO, WARN, ERROR, CRITICAL, FATAL)
    logger.AddLevel(lumberjack.DEBUG)

    logger.Info("Holy Shit!")
    logger.Debugf("%s did a thing.", "thing")

With the defaults, the verbosity level of the print backend is set to print extra information (the file and line number) on ERROR or higher

The output looks like this:

    2015/08/17 12:23:57 (INFO) @ main.main(): Holy Shit!
    2015/08/17 12:23:57 (DEBUG) @ main.main() main.go:10: thing did a thing.

In the future, to add Backends, they simply need to implement the interface:

lumberjack.Backend

with the requiremed method:

Log(*LogEntry)

then add to the logger:

    /* Specifying the name allows you to have
    multiple copies of the same backend with
    different settings */
    logger.AddBackend("somename", &SomeBackend{})
Http Backend?

You can specify a basic HTTP backend to POST log entries formatted in JSON. Implemented in the backend, is a buffering mechanism to buffer an arbitrarily defined number of log entries for a given time period. The buffer will be sent via HTTP POST as a JSON array either when the buffer is filled, or the time interval elapses (whichever occurs first).

    /* Add an HTTP JSON POST backend with a message
    buffer of 10 per 5sec */
    hb := lumberjack.NewHttpClientBackend(
    "http://www.example.com:1234", 10, time.Second*5)

    //Don't forget to add the backend!
    logger.AddBackend("http", hb)

    //Defer the closing of the HTTP Backend's goroutine.
    defer close(hb.Stop)

So given the above example, once 10 log entries are sent to the backend, it will HTTP POST them to the specified URL. Or, if 5 seconds elapses, whatever is currently in the buffer will be sent without waiting to fill.

Want to Contribute?

Send me a pull request, I'll probably merge it. But let's be honest, who's going to use this drivel? :P

Documentation

Overview

Package lumberjack is a simple leveled logger that provides the means to send structured log messages on a number of various backends. New backends can be added to the package by implementing the Backend interface.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Backend

type Backend interface {
	Log(*LogEntry)
}

Backend is an interface that must be implemented in order to be utilized by an instance of Logger.

type HttpClientBackend

type HttpClientBackend struct {
	Stop chan struct{}
	// contains filtered or unexported fields
}

HttpClientBackend is an object that holds the configuration data to be used for implementing an instance of an HTTP POST logging backend that sends LogEntry messages via JSON to a specified URL.

The exported Stop channel should be used during cleanup code to close down the internal Goroutine of the HttpClientBackend.

func NewHttpClientBackend

func NewHttpClientBackend(url string, bufsize int, interval time.Duration) *HttpClientBackend

NewHttpClientBackend is a function that accepts the url string, LogEntry buffer size and interval time.Duration to be used to configure and start a new instnace of HttpClientBackend with the given arguments. It will start a Goroutine that will act as a method of decoupling the blocking nature of HTTP requests from any application that sends a LogEntry to this Backend.

It also implements a method of buffering LogEntry messages to pipeline in single HTTP POST requests. The buffer will empty into an HTTP POST request when it is full, or when the specified time.Duration interval passes on a time.Ticker. This will keep slowly moving logs from sitting too long in the buffer. If no interval is specified, a default of 1 second will be chosen. If no bufsize is specified, each LogEntry will be sent via HTTP POST individually.

func (*HttpClientBackend) Log

func (h *HttpClientBackend) Log(entry *LogEntry)

Log implements the Backend interface's requirements and will send LogEntry object references to the channel on the current HttpClientBackend to be buffered then sent via HTTP POST as JSON.

type LogEntry

type LogEntry struct {
	Level   LogLevel `json:"level"`
	Caller  string   `json:"caller"`
	Path    string   `json:"path"`
	File    string   `json:"file"`
	Line    int      `json:"line"`
	Message string   `json:"message"`
}

LogEntry is the object used to contain the relevant information for a particular log event.

type LogLevel

type LogLevel byte
const (
	INFO LogLevel = iota
	WARN
	ERROR
	CRITICAL
	FATAL
	DEBUG
)

Constants used to define the various LogLevels

func (LogLevel) MarshalJSON

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

MarshalJSON satisfies json.Marshaler.

func (LogLevel) String

func (l LogLevel) String() string

String satisfies fmt.Stringer interface fo use in Marshalling a LogLevel to JSON or for console printing.

func (*LogLevel) UnmarshalJSON

func (l *LogLevel) UnmarshalJSON(data []byte) error

UnmarshalJSON satisfies json.Unmarshaler.

type Logger

type Logger struct {
	sync.Mutex
	// contains filtered or unexported fields
}

Logger holds the configuration for LogLevel state and references to in-use backends.

func NewLogger

func NewLogger() *Logger

NewLogger returns an empty instance of Logger.

func NewLoggerWithDefaults

func NewLoggerWithDefaults() *Logger

NewLoggerWithDefaults returns an instance of Logger with sensible defaults and a print backend.

func (*Logger) AddBackend

func (l *Logger) AddBackend(name string, backend Backend) error

AddBackend adds an object implementing the Backend interface to the current Logger. A name must be specified to add the Backend to the collection as to differentiate it from other Backends. This allows multiple instances of the same Backend object to be added to the collection with different configurations.

func (*Logger) AddLevel

func (l *Logger) AddLevel(level LogLevel) error

AddLevel adds a LogLevel to the current Logger.

func (*Logger) Critical

func (l *Logger) Critical(args ...interface{})

Critical logs a string built from the specified args to all added Backend objects aded to the current Logger if the CRITICAL LogLevel currently added to the Logger.

func (*Logger) Criticalf

func (l *Logger) Criticalf(format string, args ...interface{})

Criticalf logs a formatted string built from the specified args to all added Backend objects aded to the current Logger if the CRITICAL LogLevel currently added to the Logger.

func (*Logger) Debug

func (l *Logger) Debug(args ...interface{})

Debug logs a string built from the specified args to all added Backend objects aded to the current Logger if the DEBUG LogLevel currently added to the Logger.

func (*Logger) Debugf

func (l *Logger) Debugf(format string, args ...interface{})

Debugf logs a formatted string built from the specified args to all added Backend objects aded to the current Logger if the DEBUG LogLevel currently added to the Logger.

func (*Logger) Error

func (l *Logger) Error(args ...interface{})

Error logs a string built from the specified args to all added Backend objects aded to the current Logger if the WARN LogLevel currently added to the Logger.

func (*Logger) Errorf

func (l *Logger) Errorf(format string, args ...interface{})

Errorf logs a formatted string built from the specified args to all added Backend objects aded to the current Logger if the ERROR LogLevel currently added to the Logger.

func (*Logger) Fatal

func (l *Logger) Fatal(args ...interface{})

Fatal logs a string built from the specified args to all added Backend objects aded to the current Logger if the FATAL LogLevel currently added to the Logger, then it will cause the application to os.Exit with status 1.

func (*Logger) Fatalf

func (l *Logger) Fatalf(format string, args ...interface{})

Fatalf logs a formatted string built from the specified args to all added Backend objects aded to the current Logger if the FATAL LogLevel currently added to the Logger, then it will cause the application to os.Exit with status 1

func (*Logger) GetBackend

func (l *Logger) GetBackend(name string) (*Backend, error)

GetBackend returns a reference to an object implementing the Backend interface associated with the current Logger. The reference is retrieved from a map collection with the name of the Backend as the key that was Specified when adding the Backend to the collection.

func (*Logger) Info

func (l *Logger) Info(args ...interface{})

Info logs a string built from the specified args to all added Backend objects aded to the current Logger if the INFO LogLevel currently added to the Logger.

func (*Logger) Infof

func (l *Logger) Infof(format string, args ...interface{})

Infof logs a formatted string built from the specified args to all added Backend objects aded to the current Logger if the DEBUG LogLevel currently added to the Logger.

func (*Logger) RemoveBackend

func (l *Logger) RemoveBackend(name string, backend Backend) error

RemoveBackend removes a specified object implementing the Backend interface from the current Logger. The name is used to specify which reference to be removed from the collection.

func (*Logger) RemoveLevel

func (l *Logger) RemoveLevel(level LogLevel) error

RemoveLevel removes a LogLevel from the current Logger.

func (*Logger) Warn

func (l *Logger) Warn(args ...interface{})

Warn logs a string built from the specified args to all added Backend objects aded to the current Logger if the WARN LogLevel currently added to the Logger.

func (*Logger) Warnf

func (l *Logger) Warnf(format string, args ...interface{})

Warnf logs a formatted string built from the specified args to all added Backend objects aded to the current Logger if the WARN LogLevel currently added to the Logger.

type PrintBackend

type PrintBackend struct {
	Verbosity LogLevel
}

PrintBackend implements a console printing Backend that currently offers two predefined formats based on the Verbosity specified.

func (*PrintBackend) Log

func (b *PrintBackend) Log(entry *LogEntry)

Log satisfies the Backend interfaces requirements used for accepting LogEntry objects to print out to the console.

Jump to

Keyboard shortcuts

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