logger

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Apr 6, 2018 License: BSD-3-Clause Imports: 10 Imported by: 0

README

logger

Package logger provides Logger4go which is a simple wrapper around go's log.Logger.

It provides three log handlers ConsoleHandler|FileHandler|SyslogHandler, wrapper methods named after syslog's severity levels and embedds log.Logger to provide seemless access to its methods as well if needed.

Supports:

- Write to multiple handlers, e.g., log to console, file and syslog at the same time.
- Use more than one logger instance. Each with its own set of handlers.
- Log file rotation (size or daily) and compression.
- Filter out severity levels.

Example output:

main 2013/06/21 08:21:44.680513 -info- init called
100m sprint 2013/06/21 08:21:44.680712 -info- Started 100m sprint: Should take 10 seconds.
Long jump 2013/06/21 08:21:44.680727 -info- Started Long jump: Should take 6 seconds.
High jump 2013/06/21 08:21:44.680748 -info- Started High jump: Should take 3 seconds.
High jump 2013/06/21 08:21:47.683402 -info- Finished High jump
Long jump 2013/06/21 08:21:50.683182 -info- Finished Long jump
100m sprint 2013/06/21 08:21:54.683871 -info- Finished 100m sprint
main 2013/06/21 08:22:14 -debug- A debug message
main 2013/06/21 08:22:14 -info- An info message
main 2013/06/21 08:22:14 -notice- A notice message
main 2013/06/21 08:22:14 -warn- A warning message
main 2013/06/21 08:22:14 -err- An error message
main 2013/06/21 08:22:14 -crit- A critical message
main 2013/06/21 08:22:14 -alert- An alert message
main 2013/06/21 08:22:14 -emerg- An emergency message

TODO: - Custom header format - Read settings from config file

package logger_test

import (
    "fmt"
    "github.com/alyu/logger"
    "log/syslog"
)

var lg *logger.Logger4go

func Example() {
    // get a new logger instance named "example" and with prefix example
    lg = logger.Get("example")
    lg.Info("This is not written out, we need to add a handler first")

    // log to console/stdout
    lg.AddConsoleHandler()
    lg.Info("This will be written out to stdout")

    // log to file. as default the log will be rotated 5 times with a
    // max filesize of 1MB starting with sequence no 1, daily rotate and compression disabled
    _, err := lg.AddStdFileHandler("/tmp/logger.log")
    if err != nil {
        fmt.Errorf("%v", err)
    }
    lg.Alert("This is an alert message written to the console and log file")

    // log to syslog
    protocol := "" // tcp|udp
    ipaddr := ""
    sh, err := lg.AddSyslogHandler(protocol, ipaddr, syslog.LOG_INFO|syslog.LOG_LOCAL0, "example")
    if err != nil {
        fmt.Errorf("%v", err)
    }
    lg.Notice("This is a critical message written to the console, log file and syslog")
    lg.Notice("The format written to syslog is the same as for the console and log file")
    err = sh.Out.Err("This is a message to syslog without any preformatted header, it just contains this message")
    if err != nil {
        fmt.Errorf("%v", err)
    }

    // filter logs
    lg.SetFilter(logger.DEBUG | logger.INFO)
    lg.Alert("This message should not be shown")
    lg.Debug("This debug message is filtered through")
    lg.Info("As well as this info message")

    lg = logger.GetWithFlags("micro", logger.Ldate|logger.Ltime|logger.Lmicroseconds)
    lg.Info("This is written out with micrseconds precision")

    // get standard logger
    log := logger.Std()
    log.Info("Standard logger always has a console handler")

    // add a file handler which rotates 5 files with a maximum size of 5MB starting with sequence no 1, daily midnight rotation disabled
    // and with compress logs enabled
    log.AddFileHandler("/tmp/logger2.log", uint(5*logger.MB), 5, 1, true, false)

    // add a file handler which keeps logs for 5 days with no filesize limit starting with sequence no 1, daily midnight rotation
    // and  compress logs enabled
    log.AddFileHandler("/tmp/logger3.log", 0, 5, 1, true, true)

    // add a file handler with only one daily midnight rotation and compress logs enabled
    log.AddFileHandler("/tmp/logger3.log", 0, 1, 1, true, true)

    // Same as above
    fh, _ := log.AddStdFileHandler("/tmp/logger4.log")
    fh.SetSize(0)
    fh.SetRotate(1)
    fh.SetCompress(true)
    fh.SetDaily(true)
}

Documentation

Overview

Package logger provides Logger4go which is a simple wrapper around go's log.Logger.

It provides three log handlers ConsoleHandler|FileHandler|SyslogHandler, wrapper methods named after syslog's severity levels and embedds log.Logger to provide seemless access to its methods as well if needed.

Supports:

  • Write to multiple handlers, e.g., log to console, file and syslog at the same time.
  • Use more than one logger instance. Each with its own set of handlers.
  • Log file rotation (size of daily) and compression.
  • Filter out severity levels.

Example output:

main 2013/06/21 08:21:44.680513 -info- init called
100m sprint 2013/06/21 08:21:44.680712 -info- Started 100m sprint: Should take 10 seconds.
Long jump 2013/06/21 08:21:44.680727 -info- Started Long jump: Should take 6 seconds.
High jump 2013/06/21 08:21:44.680748 -info- Started High jump: Should take 3 seconds.
High jump 2013/06/21 08:21:47.683402 -info- Finished High jump
Long jump 2013/06/21 08:21:50.683182 -info- Finished Long jump
100m sprint 2013/06/21 08:21:54.683871 -info- Finished 100m sprint
main 2013/06/21 08:22:14 -debug- A debug message
main 2013/06/21 08:22:14 -info- An info message
main 2013/06/21 08:22:14 -notice- A notice message
main 2013/06/21 08:22:14 -warn- A warning message
main 2013/06/21 08:22:14 -err- An error message
main 2013/06/21 08:22:14 -crit- A critical message
main 2013/06/21 08:22:14 -Alert- An alert message
main 2013/06/21 08:22:14 -Emerge- An Emergeency message

TODO:

  • Custom header format
  • Read settings from config file
Example
package main

import (
	"fmt"
	"github.com/alyu/logger"
	"log/syslog"
)

func main() {
	// Use the default logger.Logger instance
	logger.Info("logger.Info() severity")
	logger.Alert("logger.Alert() severity")
	logger.Debug("logger.Debug() debug")
	logger.Notice("logger.Notice() severity")

	var lg *logger.Logger4go
	// use the default Logger instance for the package
	lg = logger.Def()
	lg.Info("This is the default Logger available with the package and outputs to os.Stdout with no prefix")
	logger.Logger.Info("logger.Logger is the default exported Logger instance variable")

	// get a new logger instance named "example" and with prefix example
	lg = logger.Get("example")
	lg.Info("This is not written out, we need to add a handler first")

	// log to console/stdout
	lg.AddConsoleHandler()
	lg.Info("This will be written out to stdout")

	// log to file. as default the log will be rotated 5 times with a
	// max filesize of 1MB starting with sequence no 1, daily rotate and compression disabled
	_, err := lg.AddStdFileHandler("/tmp/logger.log")
	if err != nil {
		_ = fmt.Errorf("%v", err)
	}
	lg.Alert("This is an alert message written to the console and log file")

	// log to syslog
	protocol := "" // tcp|udp
	ipaddr := ""
	sh, err := lg.AddSyslogHandler(protocol, ipaddr, syslog.LOG_INFO|syslog.LOG_LOCAL0, "example")
	if err != nil {
		_ = fmt.Errorf("%v", err)
	}
	lg.Notice("This is a critical message written to the console, log file and syslog")
	lg.Notice("The format written to syslog is the same as for the console and log file")
	err = sh.Out.Err("This is a message to syslog without any preformatted header, it just contains this message")
	if err != nil {
		_ = fmt.Errorf("%v", err)
	}

	// filter logs
	lg.SetFilter(logger.DebugSeverity | logger.InfoSeverity)
	lg.Alert("This message should not be shown")
	lg.Debug("This debug message is filtered through")
	lg.Info("As well as this info message")

	lg = logger.GetWithFlags("micro", logger.Ldate|logger.Ltime|logger.Lmicroseconds)
	lg.Info("This is written out with micrseconds precision")

	// get the stdout logger
	lg = logger.Stdout()
	lg.Info("Stdout always has a console handler and prefix 'main'")
	// Set a new prefix
	lg.SetPrefix("api client")

	// add a file handler which rotates 5 files with a maximum size of 5MB starting with sequence no 1, daily midnight rotation disabled
	// and with compress logs enabled
	lg.AddFileHandler("/tmp/logger2.log", uint(5*logger.MB), 5, true, false)

	// add a file handler which keeps 5 rotated logs with no filesize limit starting with sequence no 1, daily midnight rotation
	// and  compress logs enabled
	lg.AddFileHandler("/tmp/logger3.log", 0, 5, true, true)

	// add a file handler with only daily midnight rotation and compress logs enabled
	lg.AddFileHandler("/tmp/logger3.log", 0, 1, true, true)

	// Same as above
	fh, _ := lg.AddStdFileHandler("/tmp/logger4.log")
	fh.SetSize(0)
	fh.SetRotate(1)
	fh.SetCompress(true)
	fh.SetDaily(true)

	// get the stderr logger
	lg = logger.Stderr()
	lg.Info("Stderr always has a console handler and prefix 'err'")
	lg.Err("Writes to stderr")
}
Output:

Index

Examples

Constants

View Source
const (
	DefRotatation = 5
	DefFileSize   = uint(1 * MB)
)

DefRotatation and DefFileSize sets the default number of rotated files and the max size per log file.

View Source
const (
	// Bits or'ed together to control what's printed. There is no control over the
	// order they appear (the order listed here) or the format they present (as
	// described in the comments).  A colon appears after these items:
	//	2009/01/23 01:23:23.123123 /a/b/c/d.go:23: message
	Ldate         = 1 << iota     // the date: 2009/01/23
	Ltime                         // the time: 01:23:23
	Lmicroseconds                 // microsecond resolution: 01:23:23.123123.  assumes Ltime.
	Llongfile                     // full file name and line number: /a/b/c/d.go:23
	Lshortfile                    // final file name element and line number: d.go:23. overrides Llongfile
	LstdFlags     = Ldate | Ltime // initial values for the standard logger
)

from go's log package

Variables

View Source
var (
	EmergString   = "-emerg-"
	AlertString   = "-alert-"
	CritString    = "-crit-"
	ErrString     = "-err-"
	WarningString = "-warning-"
	NoticeString  = "-notice-"
	InfoString    = "-info-"
	DebugString   = "-debug-"
	AllString     = ""
)

severity keywords

Functions

func Alert

func Alert(v ...interface{})

Alert log

func Alertf

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

Alertf log

func Crit

func Crit(v ...interface{})

Crit log

func Critf

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

Critf log

func Debug

func Debug(v ...interface{})

Debug log

func Debugf

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

Debugf log

func Emerg

func Emerg(v ...interface{})

Emerg log

func Emergf

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

Emergf log

func Err

func Err(v ...interface{})

Err log

func Errf

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

Errf log

func Info

func Info(v ...interface{})

Info log

func Infof

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

Infof log

func Notice

func Notice(v ...interface{})

Notice log

func Noticef

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

Noticef log

func Warn

func Warn(v ...interface{})

Warn log

func Warnf

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

Warnf log

func Warning

func Warning(v ...interface{})

Warning log

func Warningf

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

Warningf log

Types

type ByteSize

type ByteSize float64

ByteSize type for the log file size

const (
	KB ByteSize = 1 << (10 * iota)
	MB
	GB
	TB
	PB
	EB
	ZB
	YB
)

Log file size constants

type ConsoleHandler

type ConsoleHandler struct {
}

ConsoleHandler writes to os.Stdout.

func (*ConsoleHandler) Close

func (ch *ConsoleHandler) Close() error

Close handler.

func (*ConsoleHandler) String

func (ch *ConsoleHandler) String() string

String returns the handler name.

func (*ConsoleHandler) Write

func (ch *ConsoleHandler) Write(b []byte) (n int, err error)

Write a log message.

type ErrConsoleHandler

type ErrConsoleHandler struct {
}

ErrConsoleHandler writes to os.Stderr

func (*ErrConsoleHandler) Close

func (ch *ErrConsoleHandler) Close() error

Close handler.

func (*ErrConsoleHandler) String

func (ch *ErrConsoleHandler) String() string

String returns the handler name.

func (*ErrConsoleHandler) Write

func (ch *ErrConsoleHandler) Write(b []byte) (n int, err error)

Write a log message.

type FileHandler

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

FileHandler writes to file.

func (*FileHandler) Close

func (fh *FileHandler) Close() error

Close handler

func (*FileHandler) Compress

func (fh *FileHandler) Compress() bool

Compress returns true if file compression is set for the rotated log file.

func (*FileHandler) Daily

func (fh *FileHandler) Daily() bool

Daily returns whether the log file rotates daily.

func (*FileHandler) Rotate

func (fh *FileHandler) Rotate() byte

Rotate returns how many log files to rotate between.

func (*FileHandler) Seq

func (fh *FileHandler) Seq() byte

Seq returns the next log file sequence number for the rotated log file.

func (*FileHandler) SetCompress

func (fh *FileHandler) SetCompress(compress bool)

SetCompress sets whether file compression should be used for the rotated log file.

func (*FileHandler) SetDaily

func (fh *FileHandler) SetDaily(daily bool)

SetDaily sets whether the log file should rotate daily.

func (*FileHandler) SetRotate

func (fh *FileHandler) SetRotate(rotate byte)

SetRotate sets the number of log files to rotate between.

func (*FileHandler) SetSeq

func (fh *FileHandler) SetSeq(seq byte)

SetSeq sets the log file sequence number for the next rotated log file.

func (*FileHandler) SetSize

func (fh *FileHandler) SetSize(size uint)

SetSize sets the max log file size.

func (*FileHandler) Size

func (fh *FileHandler) Size() uint

Size returns the max log file size.

func (*FileHandler) String

func (fh *FileHandler) String() string

String returns the handler name.

func (*FileHandler) Write

func (fh *FileHandler) Write(b []byte) (n int, err error)

Write log message to file and rotate the file if necessary.

type Handler

type Handler interface {
	// Writer interface
	Write(b []byte) (n int, err error)
	// Release any allocated resources
	Close() error
	// Return the handler's type name
	String() string
}

Handler is an interface to different log/logger handlers.

type Logger4go

type Logger4go struct {
	*log.Logger
	// contains filtered or unexported fields
}

Logger4go embedds go's log.Logger as an anonymous field and so those methods are also exposed/accessable via Logger4go.

var Logger *Logger4go

Logger provides a default Logger4go instance that output to the console

func Def

func Def() *Logger4go

Def returns the default logger instance with a console handler with no prefix.

func Get

func Get(name string) *Logger4go

Get returns a logger with the specified name and default log header flags. If it does not exist a new instance will be created.

func GetWithFlags

func GetWithFlags(name string, flags int) *Logger4go

GetWithFlags returns a logger with the specified name and log header flags. If it does exist a new instance will be created.

func Stderr

func Stderr() *Logger4go

Stderr returns the standard logger instance with a stderr console handler using prefix 'err'

func Stdout

func Stdout() *Logger4go

Stdout returns a standard logger instance with a stdout console handler using prefix 'main'.

func (*Logger4go) AddConsoleHandler

func (l *Logger4go) AddConsoleHandler() (ch *ConsoleHandler, err error)

AddConsoleHandler adds a logger that writes to stdout/console

func (*Logger4go) AddErrConsoleHandler

func (l *Logger4go) AddErrConsoleHandler() (ch *ErrConsoleHandler, err error)

AddErrConsoleHandler adds a logger that writes to stderr/console

func (*Logger4go) AddFileHandler

func (l *Logger4go) AddFileHandler(filePath string, maxFileSize uint, maxRotation byte, isCompressFile, isDailyRotation bool) (fh *FileHandler, err error)

AddFileHandler adds a file handler with a specified max filesize, max number of rotations, file compression and daily rotation

func (*Logger4go) AddHandler

func (l *Logger4go) AddHandler(handler Handler)

AddHandler adds a custom handler which conforms to the Handler interface.

func (*Logger4go) AddStdFileHandler

func (l *Logger4go) AddStdFileHandler(filePath string) (fh *FileHandler, err error)

AddStdFileHandler adds a file handler which rotates the log file 5 times with a maximum size of 1MB each starting with sequence no 1 and with compression and daily rotation disabled

func (*Logger4go) AddSyslogHandler

func (l *Logger4go) AddSyslogHandler(protocol, ipaddr string, priority syslog.Priority, tag string) (sh *SyslogHandler, err error)

AddSyslogHandler adds a syslog handler with the specified network procotol tcp|udp, a syslog daemon ip address, a log/syslog priority flag (syslog severity + facility, see syslog godoc) and a tag/prefix. The syslog daemon on localhost will be used if protocol and ipaddr is "".

AddSyslogHandler returns a SyslogHandler which can be used to directly access the SyslogHandler.out (syslog.Writer) instance which can be used to write messages with a specific syslog severity and bypassing what the logger instance is set to use. No default header is written when going via the syslog.Writer instance.

func (*Logger4go) Alert

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

Alert log

func (*Logger4go) Alertf

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

Alertf log

func (*Logger4go) Crit

func (l *Logger4go) Crit(v ...interface{})

Crit log

func (*Logger4go) Critf

func (l *Logger4go) Critf(format string, v ...interface{})

Critf log

func (*Logger4go) Debug

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

Debug log

func (*Logger4go) Debugf

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

Debugf log

func (*Logger4go) Emerg

func (l *Logger4go) Emerg(v ...interface{})

Emerg log

func (*Logger4go) Emergf

func (l *Logger4go) Emergf(format string, v ...interface{})

Emergf log

func (*Logger4go) Err

func (l *Logger4go) Err(v ...interface{})

Err log

func (*Logger4go) Errf

func (l *Logger4go) Errf(format string, v ...interface{})

Errf log

func (*Logger4go) Flags

func (l *Logger4go) Flags() int

Flags returns the current set of logger flags

func (*Logger4go) Handlers

func (l *Logger4go) Handlers() []Handler

Handlers returns a list of registered handlers

func (*Logger4go) Info

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

Info log

func (*Logger4go) Infof

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

Infof log

func (*Logger4go) IsFilterSet

func (l *Logger4go) IsFilterSet(f SeverityFilter) bool

IsFilterSet returns true if the severity filter is set

func (*Logger4go) Notice

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

Notice log

func (*Logger4go) Noticef

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

Noticef log

func (*Logger4go) Prefix

func (l *Logger4go) Prefix() string

Prefix returns the logger prefix

func (*Logger4go) RemoveHandler

func (l *Logger4go) RemoveHandler(handler Handler)

RemoveHandler removes the handler from the logger.

func (*Logger4go) SetFilter

func (l *Logger4go) SetFilter(f SeverityFilter)

SetFilter sets a severity filter

func (*Logger4go) SetFlags

func (l *Logger4go) SetFlags(flag int)

SetFlags sets a logger flag

func (*Logger4go) SetOutput

func (l *Logger4go) SetOutput(out io.Writer)

SetOutput sets a writer

func (*Logger4go) SetPrefix

func (l *Logger4go) SetPrefix(prefix string)

SetPrefix sets the logger prefix

func (*Logger4go) Warn

func (l *Logger4go) Warn(v ...interface{})

Warn log

func (*Logger4go) Warnf

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

Warnf log

func (*Logger4go) Warning

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

Warning log

func (*Logger4go) Warningf

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

Warningf log

type NoopHandler

type NoopHandler struct {
}

NoopHandler is a dummy handler used for a new logger instance. Log to noop.

func (*NoopHandler) Close

func (nh *NoopHandler) Close() error

Close the handler.

func (*NoopHandler) String

func (nh *NoopHandler) String() string

String returns the handler name.

func (*NoopHandler) Write

func (nh *NoopHandler) Write(b []byte) (n int, err error)

Write a log message.

type SeverityFilter

type SeverityFilter int

SeverityFilter represents a severity level to filter go:generate stringer -type=SeverityFilter

const (
	EmergSeverity SeverityFilter = 1 << iota
	AlertSeverity
	CritSeverity
	ErrSeverity
	WarningSeverity
	NoticeSeverity
	InfoSeverity
	DebugSeverity
	All = EmergSeverity | AlertSeverity | CritSeverity | ErrSeverity | WarningSeverity | NoticeSeverity | InfoSeverity | DebugSeverity
)

severity levels

func (SeverityFilter) String

func (s SeverityFilter) String() string

type SyslogHandler

type SyslogHandler struct {
	Out *syslog.Writer
}

SyslogHandler writes to syslog.

func (*SyslogHandler) Close

func (sh *SyslogHandler) Close() error

Close handler.

func (*SyslogHandler) String

func (sh *SyslogHandler) String() string

String returns the handler name.

func (*SyslogHandler) Write

func (sh *SyslogHandler) Write(b []byte) (n int, err error)

Write log message.

Jump to

Keyboard shortcuts

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