logging

package module
v0.1.8 Latest Latest
Warning

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

Go to latest
Published: Mar 23, 2023 License: BSD-3-Clause Imports: 17 Imported by: 6

README

Logging library for Go

GoDoc

Installation

Run go get resenje.org/logging from command line.

Documentation

Overview

Package logging is async logger library. It is based on idea that log messages are created when client wants to log something, but actual processing is done is designated goroutine. This means that main application will not be blocked while logging is performed with IO operations (writing to file, stdout/stderr, to socket).

However, be warned that if your application panics and quits, it is possible that some log messages will be lost, since they might not be processed.

Most simple way of using this module is by just importing it and start logging. Default logger (that writes messages to stderr) is created by default.

Example:

import "resenje.org/logging"
func main() {
    logging.Info("Some message")
    logging.WaitForAllUnprocessedRecords()
}

Since this is async logger, last line in main function is needed because program will end before logger has a chance to process message.

Example (Basic)

Shows basic example of using library without any setup.

// most basic way of using logging is by just calling logging functions
// without any setup. All these messages will be written to stdout.
Debug("Debug message")
Debugf("Debug message %s", "with formatting")
Info("Info message")
Infof("Info message %s", "with formatting")
Output:

Example (Custom)

This example show how to create logger with specific name and custom handlers.

// handler that writes all log messages to memory
// PassThroughFormatter only returns messages provided, without any modification
memoryHandler := &MemoryHandler{
	Level:     WARNING,
	Formatter: &PassThroughFormatter{},
}

NewLogger("myLogger", WARNING, []Handler{memoryHandler}, 0)

// this will probably be called somewhere else in the code
if logger, err := GetLogger("myLogger"); err != nil {
	panic(err)
} else {
	logger.Infof("Should not be logged")
	logger.Error("Should be logged")
}

// wait for all messages to be processed, this is blocking
WaitForAllUnprocessedRecords()

fmt.Printf("%v\n", memoryHandler.Messages)
Output:

[Should be logged]

Index

Examples

Constants

View Source
const (
	// StandardTimeFormat defines a representation of timestamps in log lines.
	StandardTimeFormat = "2006-01-02 15:04:05.000Z07:00"
)

Variables

View Source
var ErrInvalidLevel = errors.New("invalid log level")

ErrInvalidLevel is error returned if no valid log level can be decoded.

Functions

func AddHandler

func AddHandler(handler Handler)

AddHandler adds new handler to default logger.

func Alert

func Alert(a ...interface{})

Alert logs provided message in ALERT level with default logger.

func Alertf

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

Alertf logs provided message with formatting in ALERT level with default logger.

func ClearHandlers

func ClearHandlers()

ClearHandlers remove all handlers from default logger.

func Critical

func Critical(a ...interface{})

Critical logs provided message in CRITICAL level with default logger.

func Criticalf

func Criticalf(format string, a ...interface{})

Criticalf logs provided message with formatting in CRITICAL level with default logger.

func Debug

func Debug(a ...interface{})

Debug logs provided message in DEBUG level with default logger.

func Debugf

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

Debugf logs provided message with formatting in DEBUG level with default logger.

func Emergency

func Emergency(a ...interface{})

Emergency logs provided message in EMERGENCY level with default logger.

func Emergencyf

func Emergencyf(format string, a ...interface{})

Emergencyf logs provided message with formatting in EMERGENCY level with default logger.

func Error

func Error(a ...interface{})

Error logs provided message in ERROR level with default logger.

func Errorf

func Errorf(format string, a ...interface{})

Errorf logs provided message with formatting in ERROR level with default logger.

func Info

func Info(a ...interface{})

Info logs provided message in INFO level with default logger.

func Infof

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

Infof logs provided message with formatting in INFO level with default logger.

func Log

func Log(level Level, a ...interface{})

Log logs provided message with default logger.

func Logf

func Logf(level Level, format string, a ...interface{})

Logf logs provided message with formatting with default logger.

func Notice

func Notice(a ...interface{})

Notice logs provided message in NOTICE level with default logger.

func Noticef

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

Noticef logs provided message with formatting in NOTICE level with default logger.

func Pause

func Pause()

Pause temporarily stops processing of log messages in default logger.

func RemoveLogger

func RemoveLogger(name string)

RemoveLogger deletes logger from global logger registry.

func RemoveLoggers

func RemoveLoggers()

RemoveLoggers removes all loggers from global logger registry. After calling this, not loggers exist, so new ones has to be creaded for logging to work.

func SetBufferLength

func SetBufferLength(length int)

SetBufferLength sets default buffer length for default logger.

func SetLevel

func SetLevel(level Level)

SetLevel sets maximum level for log messages that default logger will process.

func Stop

func Stop()

Stop permanently stops processing of log messages in default logger.

func Unpause

func Unpause()

Unpause continues processing of log messages in default logger.

func WaitForAllUnprocessedRecords

func WaitForAllUnprocessedRecords()

WaitForAllUnprocessedRecords blocks execution until all unprocessed log records are processed. Since this library implements async logging, it is possible to have unprocessed logs at the moment when application is terminating. In that case, log messages can be lost. This mehtods blocks execution until all log records are processed, to ensure that all log messages are handled.

func Warning

func Warning(a ...interface{})

Warning logs provided message in WARNING level with default logger.

func Warningf

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

Warningf logs provided message with formatting in WARNING level with default logger.

Types

type DebugLogWriter

type DebugLogWriter struct {
	*Logger
}

DebugLogWriter is a Logger with Write method what writes all messages with Debug level.

func NewDebugLogWriter

func NewDebugLogWriter(logger *Logger) DebugLogWriter

NewDebugLogWriter creates a writer object that will send messages with Debug log level to a logger.

func (DebugLogWriter) Write

func (lw DebugLogWriter) Write(p []byte) (int, error)

Write logs an Debug message to a logger.

type ErrorLogWriter

type ErrorLogWriter struct {
	*Logger
}

ErrorLogWriter is a Logger with Write method what writes all messages with Error level.

func NewErrorLogWriter

func NewErrorLogWriter(logger *Logger) ErrorLogWriter

NewErrorLogWriter creates a writer object that will send messages with Error log level to a logger.

func (ErrorLogWriter) Write

func (lw ErrorLogWriter) Write(p []byte) (int, error)

Write logs an Error message to a logger.

type FileHandler

type FileHandler struct {
	NullHandler

	Level     Level
	Formatter Formatter
	FilePath  string
	FileMode  os.FileMode
	// contains filtered or unexported fields
}

FileHandler is a handler that writes log messages to file. If file on provided path does not exist it will be created.

Note that this handler does not perform any kind of file rotation or truncation, so files will grow indefinitely. You might want to check out RotatingFileHandler and

func (*FileHandler) Close

func (handler *FileHandler) Close() (err error)

Close releases resources used by this handler (file that log messages were written into).

func (*FileHandler) GetLevel

func (handler *FileHandler) GetLevel() Level

GetLevel returns minimal log level that this handler will process.

func (*FileHandler) Handle

func (handler *FileHandler) Handle(record *Record) error

Handle writes message from log record into file.

type Formatter

type Formatter interface {
	// Should return string that represents log message based on provided Record.
	Format(record *Record) string
}

Formatter is interface for defining new custom log messages formats.

type GRPCLoggerV2

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

GRPCLoggerV2 implements methods to satisfy interface google.golang.org/grpc/grpclog.LoggerV2.

func NewGRPCLoggerV2

func NewGRPCLoggerV2(l *Logger) *GRPCLoggerV2

NewGRPCLoggerV2 creates GRPCLoggerV2 that will use Logger for logging messages.

Example:

logger, _ := logging.GetLogger("default")
grpclog.SetLoggerV2(logging.NewGRPCLoggerV2(logger))

func (GRPCLoggerV2) Error

func (g GRPCLoggerV2) Error(args ...interface{})

Error calls Logger.Error method with provided arguments.

func (GRPCLoggerV2) Errorf

func (g GRPCLoggerV2) Errorf(format string, args ...interface{})

Errorf calls Logger.Errorf method with provided arguments.

func (GRPCLoggerV2) Errorln

func (g GRPCLoggerV2) Errorln(args ...interface{})

Errorln calls Logger.Error method with provided arguments.

func (GRPCLoggerV2) Fatal

func (g GRPCLoggerV2) Fatal(args ...interface{})

Fatal calls Logger.Critical method with provided arguments.

func (GRPCLoggerV2) Fatalf

func (g GRPCLoggerV2) Fatalf(format string, args ...interface{})

Fatalf calls Logger.Criticalf method with provided arguments.

func (GRPCLoggerV2) Fatalln

func (g GRPCLoggerV2) Fatalln(args ...interface{})

Fatalln calls Logger.Critical method with provided arguments.

func (GRPCLoggerV2) Info

func (g GRPCLoggerV2) Info(args ...interface{})

Info calls Logger.Info method with provided arguments.

func (GRPCLoggerV2) Infof

func (g GRPCLoggerV2) Infof(format string, args ...interface{})

Infof calls Logger.Infof method with provided arguments.

func (GRPCLoggerV2) Infoln

func (g GRPCLoggerV2) Infoln(args ...interface{})

Infoln calls Logger.Info method with provided arguments.

func (GRPCLoggerV2) V

func (g GRPCLoggerV2) V(l int) bool

V always returns true.

func (GRPCLoggerV2) Warning

func (g GRPCLoggerV2) Warning(args ...interface{})

Warning calls Logger.Warning method with provided arguments.

func (GRPCLoggerV2) Warningf

func (g GRPCLoggerV2) Warningf(format string, args ...interface{})

Warningf calls Logger.Warningf method with provided arguments.

func (GRPCLoggerV2) Warningln

func (g GRPCLoggerV2) Warningln(args ...interface{})

Warningln calls Logger.Warning method with provided arguments.

type Handler

type Handler interface {
	// Handle should accept log record instance and process it.
	Handle(record *Record) error
	// HandleError should process errors that occurred during calls to Handle method
	HandleError(error) error
	// GetLevel should return level that this handler is processing.
	GetLevel() Level
	// Close should free handler resources (opened files, etc)
	Close() error
}

Handler is interface that declares what every logging handler must implement in order to be used with this library.

type InfoLogWriter

type InfoLogWriter struct {
	*Logger
}

InfoLogWriter is a Logger with Write method what writes all messages with Info level.

func NewInfoLogWriter

func NewInfoLogWriter(logger *Logger) InfoLogWriter

NewInfoLogWriter creates a writer object that will send messages with Info log level to a logger.

func (InfoLogWriter) Write

func (lw InfoLogWriter) Write(p []byte) (int, error)

Write logs an Info message to a logger.

type JSONFormatter

type JSONFormatter struct{}

JSONFormatter creates JSON struct with provided record.

func (*JSONFormatter) Format

func (formatter *JSONFormatter) Format(record *Record) string

Format creates JSON struct from provided record and returns it.

type Level

type Level int8

Level represents log level for log message.

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

Levels of logging supported by library. They are ordered in descending order or imporance.

func (Level) MarshalJSON

func (level Level) MarshalJSON() ([]byte, error)

MarshalJSON is implementation of json.Marshaler interface, will be used when log level is serialized to json.

func (Level) MarshalText

func (level Level) MarshalText() ([]byte, error)

MarshalText is implementation of encoding.TextMarshaler interface, will be used when log level is serialized to text.

func (Level) String

func (level Level) String() string

String returns stirng representation of log level.

func (*Level) UnmarshalJSON

func (level *Level) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unamrshaler interface.

func (*Level) UnmarshalText

func (level *Level) UnmarshalText(data []byte) error

UnmarshalText implements encoding.TextUnamrshaler interface.

type Logger

type Logger struct {
	Name     string
	Level    Level
	Handlers []Handler
	// contains filtered or unexported fields
}

Logger is struct that is capable of processing log messages. It is central point of application logging configuration. Application can have multiple loggers with different names and at moment of logging logger is chosen.

Each logger has level and ignores all log records below defined level. Also, each logger has array of handlers used to to actuall log record processing.

func GetLogger

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

GetLogger returns logger instance based on provided name. If logger does not exist, error will be returned.

func NewLogger

func NewLogger(name string, level Level, handlers []Handler, bufferLength int) (l *Logger)

NewLogger creates and returns new logger instance with provided name, log level, handlers and buffer length. If a logger with the same name already exists, it will be replaced with a new one. Log level is lowest level or log record that this logger will handle. Log records (above defined log level) will be passed to all log handlers for processing.

func (*Logger) AddHandler

func (logger *Logger) AddHandler(handler Handler)

AddHandler add new handler to current logger.

func (*Logger) Alert

func (logger *Logger) Alert(a ...interface{})

Alert logs provided message in ALERT level.

func (*Logger) Alertf

func (logger *Logger) Alertf(format string, a ...interface{})

Alertf logs provided message with formatting in ALERT level.

func (*Logger) ClearHandlers

func (logger *Logger) ClearHandlers()

ClearHandlers removes all handlers from current logger.

func (*Logger) Critical

func (logger *Logger) Critical(a ...interface{})

Critical logs provided message in CRITICAL level.

func (*Logger) Criticalf

func (logger *Logger) Criticalf(format string, a ...interface{})

Criticalf logs provided message with formatting in CRITICAL level.

func (*Logger) Debug

func (logger *Logger) Debug(a ...interface{})

Debug logs provided message in DEBUG level.

func (*Logger) Debugf

func (logger *Logger) Debugf(format string, a ...interface{})

Debugf logs provided message with formatting in DEBUG level.

func (*Logger) Emergency

func (logger *Logger) Emergency(a ...interface{})

Emergency logs provided message in EMERGENCY level.

func (*Logger) Emergencyf

func (logger *Logger) Emergencyf(format string, a ...interface{})

Emergencyf logs provided message with formatting in EMERGENCY level.

func (*Logger) Error

func (logger *Logger) Error(a ...interface{})

Error logs provided message in ERROR level.

func (*Logger) Errorf

func (logger *Logger) Errorf(format string, a ...interface{})

Errorf logs provided message with formatting in ERROR level.

func (*Logger) Info

func (logger *Logger) Info(a ...interface{})

Info logs provided message in INFO level.

func (*Logger) Infof

func (logger *Logger) Infof(format string, a ...interface{})

Infof logs provided message with formatting in INFO level.

func (*Logger) Log

func (logger *Logger) Log(level Level, a ...interface{})

Log logs provided message.

func (*Logger) Logf

func (logger *Logger) Logf(level Level, format string, a ...interface{})

Logf logs provided message with formatting.

func (*Logger) Notice

func (logger *Logger) Notice(a ...interface{})

Notice logs provided message in NOTICE level.

func (*Logger) Noticef

func (logger *Logger) Noticef(format string, a ...interface{})

Noticef logs provided message with formatting in NOTICE level.

func (*Logger) Pause

func (logger *Logger) Pause()

Pause temporarily stops processing of log messages in current logger.

func (*Logger) SetBufferLength

func (logger *Logger) SetBufferLength(length int)

SetBufferLength sets length of buffer for accepting log records.

func (*Logger) SetLevel

func (logger *Logger) SetLevel(level Level)

SetLevel sets lower level that current logger will process.

func (*Logger) Stop

func (logger *Logger) Stop()

Stop permanently stops processing of log messages in current logger.

func (*Logger) String

func (logger *Logger) String() string

String returns logger name.

func (*Logger) Unpause

func (logger *Logger) Unpause()

Unpause continues processing of log messages in current logger.

func (*Logger) WaitForUnprocessedRecords

func (logger *Logger) WaitForUnprocessedRecords()

WaitForUnprocessedRecords block execution until all unprocessed log records for this logger are processed. In order to wait for processing in all loggers, logging.WaitForAllUnprocessedRecords can be used.

func (*Logger) Warning

func (logger *Logger) Warning(a ...interface{})

Warning logs provided message in WARNING level.

func (*Logger) Warningf

func (logger *Logger) Warningf(format string, a ...interface{})

Warningf logs provided message with formatting in WARNING level.

type MemoryHandler

type MemoryHandler struct {
	NullHandler

	Level     Level
	Formatter Formatter
	Messages  []string
	// contains filtered or unexported fields
}

MemoryHandler stores all messages in memory. If needed, messages can be obtained from Messages field.

func (*MemoryHandler) GetLevel

func (handler *MemoryHandler) GetLevel() Level

GetLevel returns current level for this handler.

func (*MemoryHandler) Handle

func (handler *MemoryHandler) Handle(record *Record) error

Handle appends message to Messages array.

type MessageFormatter

type MessageFormatter struct{}

MessageFormatter logs only Message from the Record.

func (*MessageFormatter) Format

func (formatter *MessageFormatter) Format(record *Record) string

Format returns only the Record Message

type NullHandler

type NullHandler struct{}

NullHandler ignores all messages provided to it.

func (*NullHandler) Close

func (handler *NullHandler) Close() error

Close does nothing for this handler.

func (*NullHandler) GetLevel

func (handler *NullHandler) GetLevel() Level

GetLevel returns current level for this handler.

func (*NullHandler) Handle

func (handler *NullHandler) Handle(record *Record) error

Handle ignores all messages.

func (*NullHandler) HandleError

func (handler *NullHandler) HandleError(err error) error

HandleError prints provided error to stderr.

type Record

type Record struct {
	Time    time.Time `json:"time"`
	Level   Level     `json:"level"`
	Message string    `json:"message"`
}

Record is representation of single message that needs to be logged in single handler.

type RotatingFileHandler

type RotatingFileHandler struct {
	NullHandler

	Level           Level
	Formatter       Formatter
	Directory       string
	FileName        string
	FileExtension   string
	NumberSeparator string
	FileMode        os.FileMode
	MaxFileSize     int64
	MaxFiles        int
	// contains filtered or unexported fields
}

RotatingFileHandler writes all log messages to file with capability to rotate files once they reach defined size. If file on provided path does not exist it will be created.

func (*RotatingFileHandler) Close

func (handler *RotatingFileHandler) Close() (err error)

Close releases resources used by this handler (file that log messages were written into).

func (*RotatingFileHandler) GetLevel

func (handler *RotatingFileHandler) GetLevel() Level

GetLevel returns minimal log level that this handler will process.

func (*RotatingFileHandler) Handle

func (handler *RotatingFileHandler) Handle(record *Record) error

Handle writes message from log record into file.

type StandardFormatter

type StandardFormatter struct {
	TimeFormat string
}

StandardFormatter adds time of logging with message to be logged.

func (*StandardFormatter) Format

func (formatter *StandardFormatter) Format(record *Record) string

Format constructs string for logging. Time of logging is added to log message. Also, if time of logging is more then 100 miliseconds in the passt, both times will be added to message (time when application sent log and time when message was processed). Otherwise, only time of processing will be written.

type SyslogFacility

type SyslogFacility string

SyslogFacility is a string representation of syslog facility.

func (SyslogFacility) OK

func (s SyslogFacility) OK() (ok bool)

OK checks if SyslogFacility is valid.

func (SyslogFacility) Priority

func (s SyslogFacility) Priority() syslog.Priority

Priority returns a syslog.Priority representation of SyslogFacility.

func (SyslogFacility) String

func (s SyslogFacility) String() string

String returns a string representation of SyslogFacility.

type SyslogHandler

type SyslogHandler struct {
	NullHandler

	Formatter Formatter
	Tag       string
	Facility  syslog.Priority
	Severity  syslog.Priority
	// Network is a named network to connect to syslog.
	// Known networks are "tcp", "tcp4" (IPv4-only), "tcp6" (IPv6-only),
	// "udp", "udp4" (IPv4-only), "udp6" (IPv6-only), "ip", "ip4" (IPv4-only),
	// "ip6" (IPv6-only), "unix", "unixgram" and "unixpacket".
	// If network is empty, SyslogHandler will connect to the local
	// syslog server.
	Network string
	// Address is a network address to connect to syslog.
	Address string
	// contains filtered or unexported fields
}

SyslogHandler sends all messages to syslog.

func (*SyslogHandler) Close

func (handler *SyslogHandler) Close() error

Close closes an associated syslog Writer.

func (*SyslogHandler) GetLevel

func (handler *SyslogHandler) GetLevel() Level

GetLevel returns a Level from handler's Severity.

func (*SyslogHandler) Handle

func (handler *SyslogHandler) Handle(record *Record) error

Handle sends a record message to syslog Writer.

type TimedFileHandler

type TimedFileHandler struct {
	NullHandler

	Level          Level
	Formatter      Formatter
	Directory      string
	FileExtension  string
	FilenameLayout string
	FileMode       os.FileMode
	DirectoryMode  os.FileMode
	// contains filtered or unexported fields
}

TimedFileHandler writes all log messages to file with name constructed from record time. If file or directoeies on provided path do not exist they will be created.

func (*TimedFileHandler) Close

func (handler *TimedFileHandler) Close() (err error)

Close releases resources used by this handler (file that log messages were written into).

func (*TimedFileHandler) GetLevel

func (handler *TimedFileHandler) GetLevel() Level

GetLevel returns minimal log level that this handler will process.

func (*TimedFileHandler) Handle

func (handler *TimedFileHandler) Handle(record *Record) (err error)

Handle writes message from log record into file.

type WarningLogWriter

type WarningLogWriter struct {
	*Logger
}

WarningLogWriter is a Logger with Write method what writes all messages with Warning level.

func NewWarningLogWriter

func NewWarningLogWriter(logger *Logger) WarningLogWriter

NewWarningLogWriter creates a writer object that will send messages with Warning log level to a logger.

func (WarningLogWriter) Write

func (lw WarningLogWriter) Write(p []byte) (int, error)

Write logs an Warning message to a logger.

type WriteHandler

type WriteHandler struct {
	NullHandler

	Level     Level
	Formatter Formatter
	Writer    io.Writer
}

WriteHandler requires io.Writer and sends all messages to this writer.

func (*WriteHandler) GetLevel

func (handler *WriteHandler) GetLevel() Level

GetLevel returns current level for this handler.

func (*WriteHandler) Handle

func (handler *WriteHandler) Handle(record *Record) error

Handle writes all provided log records to writer provided during creation.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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