logging

package module
Version: v0.0.0-...-3eee531 Latest Latest
Warning

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

Go to latest
Published: Feb 8, 2016 License: BSD-3-Clause Imports: 15 Imported by: 0

README

Golang logging library

Build Status

Package logging implements a logging infrastructure for Go. It supports different logging backends like syslog, file and memory. Multiple backends can be utilized with different log levels per backend and logger.

Installing

Using go get

$ go get github.com/op/go-logging

After this command go-logging is ready to use. Its source will be in:

$GOROOT/src/pkg/github.com/op/go-logging

You can use go get -u -a to update all installed packages.

Example

You can find a more detailed example at the end.

package main

import "github.com/op/go-logging"

var log = logging.MustGetLogger("package.example")

func main() {
	var format = logging.MustStringFormatter("%{level} %{message}")
	logging.SetFormatter(format)
	logging.SetLevel(logging.INFO, "package.example")

	log.Debug("hello %s", "golang")
	log.Info("hello %s", "golang")
}

Documentation

For docs, see http://godoc.org/github.com/op/go-logging or run:

$ go doc github.com/op/go-logging

Full example

package main

import (
	stdlog "log"
	"os"

	"github.com/op/go-logging"
)

var log = logging.MustGetLogger("test")

type Password string

func (p Password) Redacted() interface{} {
	return logging.Redact(string(p))
}

func main() {
	// Customize the output format
	logging.SetFormatter(logging.MustStringFormatter("▶ %{level:.1s} 0x%{id:x} %{message}"))

	// Setup one stdout and one syslog backend.
	logBackend := logging.NewLogBackend(os.Stderr, "", stdlog.LstdFlags|stdlog.Lshortfile)
	logBackend.Color = true

	syslogBackend, err := logging.NewSyslogBackend("")
	if err != nil {
		log.Fatal(err)
	}

	// Combine them both into one logging backend.
	logging.SetBackend(logBackend, syslogBackend)

	// Run one with debug setup for "test" and one with error.
	for _, level := range []logging.Level{logging.DEBUG, logging.ERROR} {
		logging.SetLevel(level, "test")

		log.Critical("crit")
		log.Error("err")
		log.Warning("warning")
		log.Notice("notice")
		log.Info("info")
		log.Debug("debug %s", Password("secret"))
	}
}

Documentation

Overview

Package logging implements a logging infrastructure for Go. It supports different logging backends like syslog, file and memory. Multiple backends can be utilized with different log levels per backend and logger.

Index

Constants

This section is empty.

Variables

View Source
var ErrInvalidLogLevel = errors.New("logger: invalid log level")

Functions

func MustStringFormatter

func MustStringFormatter(format string) *stringFormatter

MustStringFormatter is equivalent to NewStringFormatter with a call to panic on error.

func NewStringFormatter

func NewStringFormatter(format string) (*stringFormatter, error)

NewStringFormatter returns a new Formatter which outputs the log record as a string based on the 'verbs' specified in the format string.

The verbs:

General:

%{id}        Sequence number for log message (uint64).
%{pid}       Process id (int)
%{time}      Time when log occurred (time.Time)
%{level}     Log level (Level)
%{module}    Module (string)
%{program}   Basename of os.Args[0] (string)
%{message}   Message (string)
%{longfile}  Full file name and line number: /a/b/c/d.go:23
%{shortfile} Final file name element and line number: d.go:23

For normal types, the output can be customized by using the 'verbs' defined in the fmt package, eg. '%{id:04d}' to make the id output be '%04d' as the format string.

For time.Time, use the same layout as time.Format to change the time format when output, eg "2006-01-02T15:04:05.999Z-07:00".

func Redact

func Redact(s string) string

Redact returns a string of * having the same length as s.

func Reset

func Reset()

Reset restores the internal state of the logging library.

func SetFormatter

func SetFormatter(f Formatter)

SetFormatter sets the default formatter for all new backends. A backend will fetch this value once it is needed to format a record. Note that backends will cache the formatter after the first point. For now, make sure to set the formatter before logging.

func SetLevel

func SetLevel(level Level, module string)

SetLevel sets the logging level for the specified module. The module corresponds to the string specified in GetLogger.

Types

type Backend

type Backend interface {
	Log(Level, int, *Record) error
}

Backend is the interface which a log backend need to implement to be able to be used as a logging backend.

type ChannelMemoryBackend

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

ChannelMemoryBackend is very similar to the MemoryBackend, except that it internally utilizes a channel.

func NewChannelMemoryBackend

func NewChannelMemoryBackend(size int) *ChannelMemoryBackend

NewChannelMemoryBackend creates a simple in-memory logging backend which utilizes a go channel for communication.

Start will automatically be called by this function.

func (*ChannelMemoryBackend) Flush

func (b *ChannelMemoryBackend) Flush()

Flush waits until all records in the buffered channel have been processed.

func (*ChannelMemoryBackend) Head

func (b *ChannelMemoryBackend) Head() *node

Head returns the oldest record node kept in memory. It can be used to iterate over records, one by one, up to the last record.

Note: new records can get added while iterating. Hence the number of records iterated over might be larger than the maximum size.

func (*ChannelMemoryBackend) Log

func (b *ChannelMemoryBackend) Log(level Level, calldepth int, rec *Record) error

Log implements the Log method required by Backend.

func (*ChannelMemoryBackend) Start

func (b *ChannelMemoryBackend) Start()

Start launches the internal goroutine which starts processing data from the input channel.

func (*ChannelMemoryBackend) Stop

func (b *ChannelMemoryBackend) Stop()

Stop signals the internal goroutine to exit and waits until it have.

type Formatter

type Formatter interface {
	Format(calldepth int, r *Record, w io.Writer) error
}

Formatter is the required interface for a custom log record formatter.

var (
	// DefaultFormatter is the default formatter used and is only the message.
	DefaultFormatter Formatter = MustStringFormatter("%{message}")

	// Glog format
	GlogFormatter Formatter = MustStringFormatter("%{level:.1s}%{time:0102 15:04:05.999999} %{pid} %{shortfile}] %{message}")
)

type Level

type Level int

Level defines all available log levels for log messages.

const (
	CRITICAL Level = iota
	ERROR
	WARNING
	NOTICE
	INFO
	DEBUG
)

func GetLevel

func GetLevel(module string) Level

GetLevel returns the logging level for the specified module.

func LogLevel

func LogLevel(level string) (Level, error)

LogLevel returns the log level from a string representation.

func (Level) String

func (p Level) String() string

String returns the string representation of a logging level.

type Leveled

type Leveled interface {
	GetLevel(string) Level
	SetLevel(Level, string)
	IsEnabledFor(Level, string) bool
}

type LeveledBackend

type LeveledBackend interface {
	Backend
	Leveled
}

LeveledBackend is a log backend with additional knobs for setting levels on individual modules to different levels.

func AddModuleLevel

func AddModuleLevel(backend Backend) LeveledBackend

AddModuleLevel wraps a log backend with knobs to have different log levels for different modules.

func MultiLogger

func MultiLogger(backends ...Backend) LeveledBackend

MultiLogger creates a logger which contain multiple loggers.

func SetBackend

func SetBackend(backends ...Backend) LeveledBackend

Set backend replaces the backend currently set with the given new logging backend.

type LogBackend

type LogBackend struct {
	Logger *log.Logger
	Color  bool
}

LogBackend utilizes the standard log module.

func NewLogBackend

func NewLogBackend(out io.Writer, prefix string, flag int) *LogBackend

NewLogBackend creates a new LogBackend.

func (*LogBackend) Log

func (b *LogBackend) Log(level Level, calldepth int, rec *Record) error

type Logger

type Logger struct {
	Module string
}

func GetLogger

func GetLogger(module string) (*Logger, error)

TODO call NewLogger and remove MustGetLogger? GetLogger creates and returns a Logger object based on the module name.

func MustGetLogger

func MustGetLogger(module string) *Logger

MustGetLogger is like GetLogger but panics if the logger can't be created. It simplifies safe initialization of a global logger for eg. a package.

func (*Logger) Critical

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

Critical logs a message using CRITICAL as log level.

func (*Logger) Debug

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

Debug logs a message using DEBUG as log level.

func (*Logger) Error

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

Error logs a message using ERROR as log level.

func (*Logger) Fatal

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

Fatal is equivalent to l.Critical(fmt.Sprint()) followed by a call to os.Exit(1).

func (*Logger) Fatalf

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

Fatalf is equivalent to l.Critical followed by a call to os.Exit(1).

func (*Logger) Info

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

Info logs a message using INFO as log level.

func (*Logger) IsEnabledFor

func (l *Logger) IsEnabledFor(level Level) bool

IsEnabledFor returns true if the logger is enabled for the given level.

func (*Logger) Notice

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

Notice logs a message using NOTICE as log level.

func (*Logger) Panic

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

Panic is equivalent to l.Critical(fmt.Sprint()) followed by a call to panic().

func (*Logger) Panicf

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

Panicf is equivalent to l.Critical followed by a call to panic().

func (*Logger) Warning

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

Warning logs a message using WARNING as log level.

type MemoryBackend

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

MemoryBackend is a simple memory based logging backend that will not produce any output but merly keep records, up to the given size, in memory.

func InitForTesting

func InitForTesting(level Level) *MemoryBackend

InitForTesting is a convenient method when using logging in a test. Once called, the time will be frozen to January 1, 1970 UTC.

func NewMemoryBackend

func NewMemoryBackend(size int) *MemoryBackend

NewMemoryBackend creates a simple in-memory logging backend.

func (*MemoryBackend) Head

func (b *MemoryBackend) Head() *node

Head returns the oldest record node kept in memory. It can be used to iterate over records, one by one, up to the last record.

Note: new records can get added while iterating. Hence the number of records iterated over might be larger than the maximum size.

func (*MemoryBackend) Log

func (b *MemoryBackend) Log(level Level, calldepth int, rec *Record) error

Log implements the Log method required by Backend.

type Record

type Record struct {
	Id     uint64
	Time   time.Time
	Module string
	Level  Level
	Fmt    string
	Args   []interface{}
	// contains filtered or unexported fields
}

Record represents a log record and contains the timestamp when the record was created, an increasing id, filename and line and finally the actual formatted log line.

func (*Record) Formatted

func (r *Record) Formatted(calldepth int) string

func (*Record) Message

func (r *Record) Message() string

type Redactor

type Redactor interface {
	Redacted() interface{}
}

Redactor is an interface for types that may contain sensitive information (like passwords), which shouldn't be printed to the log. The idea was found in relog as part of the vitness project.

type SyslogBackend

type SyslogBackend struct {
	Writer *syslog.Writer
}

SyslogBackend is a simple logger to syslog backend. It automatically maps the internal log levels to appropriate syslog log levels.

func NewSyslogBackend

func NewSyslogBackend(prefix string) (b *SyslogBackend, err error)

NewSyslogBackend connects to the syslog daemon using UNIX sockets with the given prefix. If prefix is not given, the prefix will be derived from the launched command.

func NewSyslogBackendPriority

func NewSyslogBackendPriority(prefix string, priority syslog.Priority) (b *SyslogBackend, err error)

NewSyslogBackendPriority is the same as NewSyslogBackend, but with custom syslog priority, like syslog.LOG_LOCAL3|syslog.LOG_DEBUG etc.

func (*SyslogBackend) Log

func (b *SyslogBackend) Log(level Level, calldepth int, rec *Record) error

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
t or T : Toggle theme light dark auto
y or Y : Canonical URL