log: github.com/marcw/log Index | Examples | Files

package log

import "github.com/marcw/log"

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

Package Files

compat.go doc.go formatter.go handler.go handler_buffer.go handler_syslog.go handler_writecloser.go kv.go log.go logger.go processor.go

Constants

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

Variables

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

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

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

func Fatal Uses

func Fatal(v ...interface{})

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

func Fatalf Uses

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

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

func Fatalln Uses

func Fatalln(v ...interface{})

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

func Marshal Uses

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

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

func MarshalString Uses

func MarshalString(data interface{}) string

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

func Panic Uses

func Panic(v ...interface{})

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

func Panicf Uses

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

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

func Panicln Uses

func Panicln(v ...interface{})

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

func Print Uses

func Print(v ...interface{})

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

func Printf Uses

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 Uses

func Println(v ...interface{})

Arguments are handled in the manner of fmt.Println.

type Formatter Uses

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 Uses

func NewMinimalLineFormatter() Formatter

Instantiates a new LineFormatter with the LineFormatMinimal format

func NewSimpleLineFormatter Uses

func NewSimpleLineFormatter() Formatter

Instantiates a new LineFormatter with the LineFormatSimple format

type Handler Uses

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 Uses

func (h *Handler) GetFormatter() Formatter

func (*Handler) PopProcessor Uses

func (h *Handler) PopProcessor()

func (*Handler) Prepare Uses

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

func (*Handler) Process Uses

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

func (*Handler) PushProcessor Uses

func (h *Handler) PushProcessor(p Processor)

func (*Handler) S Uses

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

func (*Handler) SetFormatter Uses

func (h *Handler) SetFormatter(f Formatter)

func (*Handler) SetSeverity Uses

func (h *Handler) SetSeverity(level Severity)

func (*Handler) Write Uses

func (h *Handler) Write()

type HandlerInterface Uses

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 Uses

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

Instantiates a new handler that will keep logs in memory

func NewStderrHandler Uses

func NewStderrHandler(level Severity) HandlerInterface

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

func NewStdoutHandler Uses

func NewStdoutHandler(level Severity) HandlerInterface

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

func NewSyslogHandler Uses

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

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

func NewWriteCloserHandler Uses

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

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

type LineFormatter Uses

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 Uses

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

Format the Record r with f.LineFormat

type Logger Uses

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

Code:

// 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 Uses

func NewLogger(name string) *Logger

Instanciates a new logger with specified name, handlers and processors

func (*Logger) AddAlert Uses

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

Log string with the ALERT level

func (*Logger) AddCritical Uses

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

Log string with the CRITICAL level

func (*Logger) AddDebug Uses

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

Log string with the DEBUG level

func (*Logger) AddEmergency Uses

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

Log string with the EMERGENCY level

func (*Logger) AddError Uses

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

Log string with the ERROR level

func (*Logger) AddInfo Uses

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

Log string with the INFO level

func (*Logger) AddNotice Uses

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

Log string with the NOTICE level

func (*Logger) AddRecord Uses

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

Log string with specified severity

func (*Logger) AddWarning Uses

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

Log string with the WARNING level

func (*Logger) Alert Uses

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

Log parameters with the ALERT level

func (*Logger) Alertf Uses

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

func (*Logger) Alertln Uses

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

func (*Logger) Critical Uses

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

Log parameters with the CRITICAL level

func (*Logger) Criticalf Uses

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

func (*Logger) Criticalln Uses

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

func (*Logger) Debug Uses

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

Log parameters with the DEBUG level

func (*Logger) Debugf Uses

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

func (*Logger) Debugln Uses

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

func (*Logger) Emergency Uses

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

Log parameters with the EMERGENCY level

func (*Logger) Emergencyf Uses

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

func (*Logger) Emergencyln Uses

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

func (*Logger) Error Uses

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

Log parameters with the ERROR level

func (*Logger) Errorf Uses

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

func (*Logger) Errorln Uses

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

func (*Logger) Info Uses

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

Log parameters with the INFO level

func (*Logger) Infof Uses

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

func (*Logger) Infoln Uses

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

func (*Logger) Notice Uses

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

Log parameters with the NOTICE level

func (*Logger) Noticef Uses

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

func (*Logger) Noticeln Uses

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

func (*Logger) PopHandler Uses

func (l *Logger) PopHandler()

Pop a handler from the handlers stack

func (*Logger) PopProcessor Uses

func (l *Logger) PopProcessor()

Pop a processor from the processor stack

func (*Logger) PushHandler Uses

func (l *Logger) PushHandler(h HandlerInterface)

Push a handler to the handlers stack

func (*Logger) PushProcessor Uses

func (l *Logger) PushProcessor(p Processor)

Push a processor to the processor stack

func (*Logger) S Uses

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

Returns true if a Handler can handle this severity level

func (*Logger) Warning Uses

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

Log parameters with the WARNING level

func (*Logger) Warningf Uses

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

func (*Logger) Warningln Uses

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

type Processor Uses

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 Uses

func NewProcessor(f func(*Record)) Processor

NewProcessor wraps a function to a Processor

type Record Uses

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 Uses

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
)

Package log imports 11 packages (graph). Updated 2016-07-19. Refresh now. Tools for package owners. This is an inactive package (no imports and no commits in at least two years).