log

package module
v0.0.0-...-9f23d81 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2015 License: MIT Imports: 11 Imported by: 0

README

Log

Build Status

A log package based on PHP's excellent Monolog library.

WARNING

The API is not yet STABLE. Some things WILL change. Please wait for a 1.0 release if you're not kin to update your code from time to time.

Why?

I felt really limited by the implementation of log and log/syslog packages. Coming from the PHP world, I used to work with monolog which is really good and based upon the python logbook package itself. I decided to port it to go and enjoy.

Documentation

Documentation is available at godoc.org

Acknowledgements

This package is heavily inspired by Jordi Boggiano's monolog library.

License

The Log code is free to use and distribute, under the MIT license.

Documentation

Overview

Package log implements logging in a similar fashion than monolog/logbook

Usage:

import (
    "github.com/marcw/log"
)

// Will log to stdout every message where severity >= DEBUG
h1 := log.NewStdoutLogger(DEBUG)
// Will log to stderr every message where severity >= ERROR
h2 := log.NewStderrLogger(ERR)

logger := log.NewLogger("channel_name")

// Will add to log lines some informations about the go runtime
logger.PushProcessor(log.RuntimeProcessor)

// Will output to stdout "This is debug"
logger.Debug("This is debug")

// Will output to both stdout and stderr "This is critical"
logger.Critical("This is critical")

Index

Examples

Constants

View Source
const (
	LineFormatSimple  string = "[%datetime%] %channel%.%level_name%: %message% %context% %extra%\n"
	LineFormatMinimal string = "%channel%.%level_name%: %message%\n"
)

Variables

View Source
var DefaultLogger = &Logger{Name: "", handlers: []HandlerInterface{stdHandler}, processors: []Processor{}}
View Source
var RuntimeProcessor = NewProcessor(runtimeProcessor)

RuntimeProcessor adds some information about the current go runtime to a log record

View Source
var Severities = map[Severity]string{
	DEBUG:     "DEBUG",
	INFO:      "INFO",
	NOTICE:    "NOTICE",
	WARNING:   "WARNING",
	ERROR:     "ERROR",
	CRITICAL:  "CRITICAL",
	ALERT:     "ALERT",
	EMERGENCY: "EMERGENCY"}

Textual translation of severities

Functions

func Fatal

func Fatal(v ...interface{})

Fatal is equivalent to a call to Print followed by a call to os.Exit(1)

func Fatalf

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

Fatal is equivalent to a call to Printf followed by a call to os.Exit(1)

func Fatalln

func Fatalln(v ...interface{})

Fatalln is equivalent to a call to Println followed by a call to os.Exit(1)

func Marshal

func Marshal(data interface{}) ([]byte, error)

Marshal will encode any structure or map in a k=v format

func MarshalString

func MarshalString(data interface{}) string

MarshalString is a proxy method for Marshal that drops any error and always return a string

func Panic

func Panic(v ...interface{})

Panic is equivalent to a call to Print followed by a call to panic

func Panicf

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

Panicf is equivalent to a call to Printf followed by a call to panic

func Panicln

func Panicln(v ...interface{})

Panicln is equivalent to a call to Println followed by a call to panic

func Print

func Print(v ...interface{})

Print calls Debug in an instance of Logger where the only handler outputs to Stderr

func Printf

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

Printf calls Debug in an instance of Logger where the only handler outputs to Stderr Arguments are handled in the manner of fmt.Printf.

func Println

func Println(v ...interface{})

Arguments are handled in the manner of fmt.Println.

Types

type Formatter

type Formatter interface {
	Format(*Record)
}

A formatter formats the record before being sent to a Handler The result of the formatting MUST be in Record.Formatted

func NewMinimalLineFormatter

func NewMinimalLineFormatter() Formatter

Instantiates a new LineFormatter with the LineFormatMinimal format

func NewSimpleLineFormatter

func NewSimpleLineFormatter() Formatter

Instantiates a new LineFormatter with the LineFormatSimple format

type Handler

type Handler struct {
	Level      Severity
	Formatter  Formatter
	Processors []Processor
}

Handler is a somewhat a "abstract" type you can embed in your own handler. It provides easiness in writing your own handlers

func (*Handler) GetFormatter

func (h *Handler) GetFormatter() Formatter

func (*Handler) PopProcessor

func (h *Handler) PopProcessor()

func (*Handler) Prepare

func (h *Handler) Prepare(r *Record)

func (*Handler) Process

func (h *Handler) Process(r *Record)

func (*Handler) PushProcessor

func (h *Handler) PushProcessor(p Processor)

func (*Handler) S

func (h *Handler) S(level Severity) bool

func (*Handler) SetFormatter

func (h *Handler) SetFormatter(f Formatter)

func (*Handler) SetSeverity

func (h *Handler) SetSeverity(level Severity)

func (*Handler) Write

func (h *Handler) Write()

type HandlerInterface

type HandlerInterface interface {
	S(Severity) bool         // Returns true if the handler accepts this severity
	SetSeverity(Severity)    // Changes the severity threshold of the handler
	Handle(Record)           // Handle the log record
	PushProcessor(Processor) // Push a new processor to the handler's stack
	PopProcessor()           // Removes a processor from the handler's stack
	SetFormatter(Formatter)  // Set the formatter for this handler
	GetFormatter() Formatter // Returns the formatter used by this handler
	Close()                  // Close the handler
}

HandlerInterface represents a type that sends log to a destination

func NewBufferHandler

func NewBufferHandler(buffer *bytes.Buffer, level Severity) HandlerInterface

Instantiates a new handler that will keep logs in memory

func NewStderrHandler

func NewStderrHandler(level Severity) HandlerInterface

Instantiates a new Handler which will write on Stderr when level is reached.

func NewStdoutHandler

func NewStdoutHandler(level Severity) HandlerInterface

Instantiates a new Handler which will write on Stdout when level is reached.

func NewSyslogHandler

func NewSyslogHandler(sw *syslog.Writer, level Severity) HandlerInterface

Instantiates a new Handler which will write on syslog when level is reached.

func NewWriteCloserHandler

func NewWriteCloserHandler(wc io.WriteCloser, level Severity) HandlerInterface

Instantiates a new Handler which will write on wc when level is reached.

type LineFormatter

type LineFormatter struct {
	LineFormat string
	TimeFormat string // Time format that will be used. Default is time.RFC3339Nano
}

A line formatter formats a Record into a line of text. Available formats are LINE_FORMAT_SIMPLE, LINE_FORMAT_MINIMAL or you can make your own with these fields: %datetime%: Record's creation date in the time.RFC3339Nano format $channel%: logger.Name %level_name%: Severity's name (DEBUG, WARNING, ...) %message%: Message text %extra%: All extra values, generally added by Processors

func (*LineFormatter) Format

func (f *LineFormatter) Format(r *Record)

Format the Record r with f.LineFormat

type Logger

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

A logger will log records transformed by the default processors to a collection of handlers

Example
// Will outputs to Stdout all messages where severity is >= WARNING
handler := NewStdoutHandler(WARNING)

// Use the LINE_FORMAT_MINIMAL format
handler.SetFormatter(NewMinimalLineFormatter())

// Instantiates a new logger with "example" as name
logger := NewLogger("example")
logger.PushHandler(handler)

// Start logging
logger.Debug("Debug message that won't be displayed")
logger.Warning("I sense a disturbance in the force")
logger.Error("This is an error")
Output:

example.WARNING: I sense a disturbance in the force
example.ERROR: This is an error

func NewLogger

func NewLogger(name string) *Logger

Instanciates a new logger with specified name, handlers and processors

func (*Logger) AddAlert

func (l *Logger) AddAlert(message string, context interface{})

Log string with the ALERT level

func (*Logger) AddCritical

func (l *Logger) AddCritical(message string, context interface{})

Log string with the CRITICAL level

func (*Logger) AddDebug

func (l *Logger) AddDebug(message string, context interface{})

Log string with the DEBUG level

func (*Logger) AddEmergency

func (l *Logger) AddEmergency(message string, context interface{})

Log string with the EMERGENCY level

func (*Logger) AddError

func (l *Logger) AddError(message string, context interface{})

Log string with the ERROR level

func (*Logger) AddInfo

func (l *Logger) AddInfo(message string, context interface{})

Log string with the INFO level

func (*Logger) AddNotice

func (l *Logger) AddNotice(message string, context interface{})

Log string with the NOTICE level

func (*Logger) AddRecord

func (l *Logger) AddRecord(level Severity, message string, context interface{})

Log string with specified severity

func (*Logger) AddWarning

func (l *Logger) AddWarning(message string, context interface{})

Log string with the WARNING level

func (*Logger) Alert

func (l *Logger) Alert(v ...interface{})

Log parameters with the ALERT level

func (*Logger) Alertf

func (l *Logger) Alertf(format string, v ...interface{})

func (*Logger) Alertln

func (l *Logger) Alertln(v ...interface{})

func (*Logger) Critical

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

Log parameters with the CRITICAL level

func (*Logger) Criticalf

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

func (*Logger) Criticalln

func (l *Logger) Criticalln(v ...interface{})

func (*Logger) Debug

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

Log parameters with the DEBUG level

func (*Logger) Debugf

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

func (*Logger) Debugln

func (l *Logger) Debugln(v ...interface{})

func (*Logger) Emergency

func (l *Logger) Emergency(v ...interface{})

Log parameters with the EMERGENCY level

func (*Logger) Emergencyf

func (l *Logger) Emergencyf(format string, v ...interface{})

func (*Logger) Emergencyln

func (l *Logger) Emergencyln(v ...interface{})

func (*Logger) Error

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

Log parameters with the ERROR level

func (*Logger) Errorf

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

func (*Logger) Errorln

func (l *Logger) Errorln(v ...interface{})

func (*Logger) Info

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

Log parameters with the INFO level

func (*Logger) Infof

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

func (*Logger) Infoln

func (l *Logger) Infoln(v ...interface{})

func (*Logger) Notice

func (l *Logger) Notice(v ...interface{})

Log parameters with the NOTICE level

func (*Logger) Noticef

func (l *Logger) Noticef(format string, v ...interface{})

func (*Logger) Noticeln

func (l *Logger) Noticeln(v ...interface{})

func (*Logger) PopHandler

func (l *Logger) PopHandler()

Pop a handler from the handlers stack

func (*Logger) PopProcessor

func (l *Logger) PopProcessor()

Pop a processor from the processor stack

func (*Logger) PushHandler

func (l *Logger) PushHandler(h HandlerInterface)

Push a handler to the handlers stack

func (*Logger) PushProcessor

func (l *Logger) PushProcessor(p Processor)

Push a processor to the processor stack

func (*Logger) S

func (l *Logger) S(level Severity) bool

Returns true if a Handler can handle this severity level

func (*Logger) Warning

func (l *Logger) Warning(v ...interface{})

Log parameters with the WARNING level

func (*Logger) Warningf

func (l *Logger) Warningf(format string, v ...interface{})

func (*Logger) Warningln

func (l *Logger) Warningln(v ...interface{})

type Processor

type Processor interface {
	Process(*Record)
}

A processor transforms a log records in whatever way it wants. It is usefull to add extra information to a log record

func NewProcessor

func NewProcessor(f func(*Record)) Processor

NewProcessor wraps a function to a Processor

type Record

type Record struct {
	Message   string                 // Text message of the log
	Formatted string                 // Formatted version of the log (once all processors and formatters have done their jobs)
	Level     Severity               // Severity level
	LevelName string                 // Severity name
	Channel   string                 // Logger's name
	Time      time.Time              // Creation date
	Context   interface{}            // Context set by logger's caller
	Extra     map[string]interface{} // Extra values that can be added by Processors
}

A record is a log message at a given time

type Severity

type Severity int
const (
	// From /usr/include/sys/syslog.h. and RFC5424
	EMERGENCY Severity = iota // Emergency: system is unusable
	ALERT                     // Alert: action must be taken immediately
	CRITICAL                  // Critical: critical conditions
	ERROR                     // Error: error conditions
	WARNING                   // Warning: warning conditions
	NOTICE                    // Notice: normal but significant condition
	INFO                      // Informational: informational messages
	DEBUG                     // Debug: debug-level messages
)

Jump to

Keyboard shortcuts

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