logging

package module
v0.3.7 Latest Latest
Warning

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

Go to latest
Published: Jan 22, 2023 License: BSD-3-Clause Imports: 23 Imported by: 13

README

go-logging

go-logging is a Golang library that implements the Python-like logging facility.

As we all know that logging is essientially significant for server side programming because in general logging the only way to report what happens inside the program.

The logging package of Python standard library is a popular logging facility among Pythoners. logging defines Logger as logging source, Handler as logging event destination, and supports Logger hierarchy and free combinations of both. It is powerful and flexible, in a similar style like Log4j, which is a popular logging facility among Javaers.

When it comes to Golang, the standard release has a library called log for logging. It's simple and good to log something into standard IO or a customized IO. In fact it's too simple to use in any real production enviroment, especially when compared to some other mature logging library.

Due to the lack of a good logging facility, many people start to develop their own versions. For example in github there are dozens of logging repositories for Golang. I run into the same problem when I am writing some project in Golang. A powerful logging facility is needed to develop and debug it. I take a search on a few existing logging libraries for Golang but none of them seems to meet the requirement. So I decide to join the parade of "everyone is busy developing his own version", and then this library is created.

Features

With an obivious intention to be a port of logging for Golang, go-logging has all the main features that logging package has:

  1. It supports logging level, logging sources(logger) and destinations(handler) customization and flexible combinations of them
  2. It supports logger hierarchy, optional filter on logger and handler, optional formatter on handler
  3. It supports handlers that frequently-used in most real production enviroments, e.g. it could write log events to stdout, memory, file, syslog, udp/tcp socket, rpc(e.g., thrift. For the corresponding servers, please refer to the unit test) etc.
  4. It could be configured throught handy config file in various format(e.g. yaml, json)

Usage

Get this library using the standard go tool:

go get github.com/hhkbp2/go-logging
Example 1: Log to standard output
package main

import (
	"github.com/hhkbp2/go-logging"
)

func main() {
	logger := logging.GetLogger("a.b")
	handler := logging.NewStdoutHandler()
	logger.AddHandler(handler)
	logger.Warnf("message: %s %d", "Hello", 2015)
}

The code above outputs as the following:

message: Hello 2015
Example 2: Log to file
package main

import (
	"github.com/hhkbp2/go-logging"
	"os"
	"time"
)

func main() {
	filePath := "./test.log"
	fileMode := os.O_APPEND
	bufferSize := 0
	bufferFlushTime := 30 * time.Second
	inputChanSize := 1
	// set the maximum size of every file to 100 M bytes
	fileMaxBytes := uint64(100 * 1024 * 1024)
	// keep 9 backup at most(including the current using one,
	// there could be 10 log file at most)
	backupCount := uint32(9)
	// create a handler(which represents a log message destination)
	handler := logging.MustNewRotatingFileHandler(
		filePath, fileMode, bufferSize, bufferFlushTime, inputChanSize,
		fileMaxBytes, backupCount)

	// the format for the whole log message
	format := "%(asctime)s %(levelname)s (%(filename)s:%(lineno)d) " +
		"%(name)s %(message)s"
	// the format for the time part
	dateFormat := "%Y-%m-%d %H:%M:%S.%3n"
	// create a formatter(which controls how log messages are formatted)
	formatter := logging.NewStandardFormatter(format, dateFormat)
	// set formatter for handler
	handler.SetFormatter(formatter)

	// create a logger(which represents a log message source)
	logger := logging.GetLogger("a.b.c")
	logger.SetLevel(logging.LevelInfo)
	logger.AddHandler(handler)

	// ensure all log messages are flushed to disk before program exits.
	defer logging.Shutdown()

	logger.Infof("message: %s %d", "Hello", 2015)
}

Compile and run the code above, it would generate a log file "./test.log" under current working directory. The log file contains a single line:

2015-04-04 14:20:33.714 INFO (main2.go:40) a.b.c message: Hello 2015
Example 3: Config Log via configuration file.

Write a configuration file config.yml as the following:

formatters:
    f:
        format: "%(asctime)s %(levelname)s (%(filename)s:%(lineno)d) %(name)s %(message)s"
        datefmt: "%Y-%m-%d %H:%M:%S.%3n"
handlers:
    h:
        class: RotatingFileHandler
        filepath: "./test.log"
        mode: O_APPEND
        bufferSize: 0
        # 30 * 1000 ms -> 30 seconds
        bufferFlushTime: 30000
        inputChanSize: 1
        # 100 * 1024 * 1024 -> 100M
        maxBytes: 104857600
        backupCount: 9
        formatter: f
loggers:
    a.b.c:
        level: INFO
        handlers: [h]

and use it to config logging facility like:

package main

import (
	"github.com/hhkbp2/go-logging"
)

func main() {
	config_file := "./config.yml"
	if err := logging.ApplyConfigFile(config_file); err != nil {
		panic(err.Error())
	}
	logger := logging.GetLogger("a.b.c")
	defer logging.Shutdown()
	logger.Infof("message: %s %d", "Hello", 2015)
}

It will write log as the same as the above example 2.

Documentation

For docs, refer to:

https://godoc.org/github.com/hhkbp2/go-logging

For much more details please refer to the documentation for logging.

Documentation

Index

Constants

View Source
const (
	SocketDefaultTimeout     = 1 * time.Second
	SocketDefaultDelay       = 1 * time.Second
	SocketDefaultMaxDeadline = 30 * time.Second
)
View Source
const (
	Day  = 24 * time.Hour
	Week = 7 * Day
)
View Source
const (
	UnlimitedDeadline time.Duration = time.Duration(math.MaxInt64)
	UnlimitedDelay                  = time.Duration(math.MaxInt64)
)

Variables

View Source
var (
	// A map from string description to file modes.
	// The string descriptions are used in configuration file.
	FileModeNameToValues = map[string]int{
		"O_RDONLY": os.O_RDONLY,
		"O_WRONLY": os.O_WRONLY,
		"O_RDWR":   os.O_RDWR,
		"O_APPEND": os.O_APPEND,
		"O_CREATE": os.O_CREATE,
		"O_EXCL":   os.O_EXCL,
		"O_SYNC":   os.O_SYNC,
		"O_TRUNC":  os.O_TRUNC,
	}
	// A map from string description to syslog priority.
	// The string descriptions are used in configuration file.
	SyslogNameToPriorities = map[string]syslog.Priority{
		"LOG_EMERG":    syslog.LOG_EMERG,
		"LOG_ALERT":    syslog.LOG_ALERT,
		"LOG_CRIT":     syslog.LOG_CRIT,
		"LOG_ERR":      syslog.LOG_ERR,
		"LOG_WARNING":  syslog.LOG_WARNING,
		"LOG_NOTICE":   syslog.LOG_NOTICE,
		"LOG_INFO":     syslog.LOG_INFO,
		"LOG_DEBUG":    syslog.LOG_DEBUG,
		"LOG_KERN":     syslog.LOG_KERN,
		"LOG_USER":     syslog.LOG_USER,
		"LOG_MAIL":     syslog.LOG_MAIL,
		"LOG_DAEMON":   syslog.LOG_DAEMON,
		"LOG_AUTH":     syslog.LOG_AUTH,
		"LOG_SYSLOG":   syslog.LOG_SYSLOG,
		"LOG_LPR":      syslog.LOG_LPR,
		"LOG_NEWS":     syslog.LOG_NEWS,
		"LOG_UUCP":     syslog.LOG_UUCP,
		"LOG_CRON":     syslog.LOG_CRON,
		"LOG_AUTHPRIV": syslog.LOG_AUTHPRIV,
		"LOG_FTP":      syslog.LOG_FTP,
		"LOG_LOCAL0":   syslog.LOG_LOCAL0,
		"LOG_LOCAL1":   syslog.LOG_LOCAL1,
		"LOG_LOCAL2":   syslog.LOG_LOCAL2,
		"LOG_LOCAL3":   syslog.LOG_LOCAL3,
		"LOG_LOCAL4":   syslog.LOG_LOCAL4,
		"LOG_LOCAL5":   syslog.LOG_LOCAL5,
		"LOG_LOCAL6":   syslog.LOG_LOCAL6,
		"LOG_LOCAL7":   syslog.LOG_LOCAL7,
	}
)
View Source
var (
	ForceRetryError  error = errors.New("force to retry")
	RetryFailedError       = errors.New("retry failed")
)
View Source
var (
	ErrorInvalidFormat = errors.New("invalid format")
)
View Source
var (
	ErrorNoSuchLevel = errors.New("no such level")
)
View Source
var (
	UnknownCallerInfo = &CallerInfo{
		PathName: "(unknown path)",
		FileName: "(unknown file)",
		LineNo:   0,
		FuncName: "(unknown function)",
	}
)

Functions

func AddLevel

func AddLevel(level LogLevelType, levelName string)

Associate levelName with level. This is used when converting levels to test during message formatting.

func ApplyConfigFile added in v0.2.5

func ApplyConfigFile(file string) error

Apply all configuration in specified file.

func ApplyJsonConfigFile added in v0.2.5

func ApplyJsonConfigFile(file string) error

Apply all configuration in specified json file.

func ApplyYAMLConfigFile added in v0.2.5

func ApplyYAMLConfigFile(file string) error

Apply all configuration in specified yaml file.

func ConfigFilters added in v0.2.5

func ConfigFilters(m ConfMap, i Filterer, env *ConfEnv) error

func ConfigFormatters added in v0.2.5

func ConfigFormatters(m ConfMap, i SetFormatterable, env *ConfEnv) error

func ConfigHandlers added in v0.2.5

func ConfigHandlers(m ConfMap, i AddHandlerable, env *ConfEnv) error

func ConfigLevel added in v0.2.5

func ConfigLevel(m ConfMap, i SetLevelable) error

func ConfigLogger added in v0.2.5

func ConfigLogger(m ConfMap, logger Logger, isRoot bool, env *ConfEnv) error

func Debugf

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

Log a message with severity "LevelDebug" on the root logger.

func DictConfig added in v0.2.5

func DictConfig(conf *Conf) error

func Errorf

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

Log a message with severity "LevelError" on the root logger.

func Fatalf

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

Log a message with severity "LevelFatal" on the root logger.

func FileExists added in v0.2.1

func FileExists(filename string) bool

Check whether the specified directory/file exists or not.

func GetLevelName

func GetLevelName(level LogLevelType) (name string)

Return the textual representation of specified logging level. If the level is one of the predefined levels (LevelFatal, LevelError, LevelWarn, LevelInfo, LevelDebug) then you get the corresponding string. If you have registered level with name using AddLevel() then the name you associated with level is returned. Otherwise, the string "Level %d"(%d is level value) is returned.

func Infof

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

Log a message with severity "LevelInfo" on the root logger.

func IsNil added in v0.2.1

func IsNil(i interface{}) bool

func IsNotNil added in v0.2.1

func IsNotNil(i interface{}) bool

func Logf

func Logf(level LogLevelType, format string, args ...interface{})

Log a message with specified severity level on the root logger.

func Min added in v0.2.1

func Min(a, b int64) int64

func RandIntN added in v0.2.1

func RandIntN(n int) int

func ReadN added in v0.3.0

func ReadN(reader io.Reader, b []byte) (int, error)

func SetLoggerMaker

func SetLoggerMaker(maker LoggerMaker)

Set logger maker for default manager.

func Shutdown

func Shutdown()

Ensure all log messages are flushed before program exits.

func Tracef added in v0.3.5

func Tracef(format string, args ...interface{})

Log a message with severity "LevelTrace" on the root logger.

func Warnf

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

Log a message with severity "LevelWarn" on the root logger.

func WriteN added in v0.3.0

func WriteN(writer io.Writer, b []byte) (int, error)

Types

type AddHandlerable added in v0.2.5

type AddHandlerable interface {
	AddHandler(handler Handler)
}

type BaseBufferingHandler added in v0.2.1

type BaseBufferingHandler struct {
	*BaseHandler
	// contains filtered or unexported fields
}

func NewBaseBufferingHandler added in v0.2.1

func NewBaseBufferingHandler(capacity uint64) *BaseBufferingHandler

func (*BaseBufferingHandler) Close added in v0.2.1

func (self *BaseBufferingHandler) Close()

func (*BaseBufferingHandler) Emit2 added in v0.2.1

func (self *BaseBufferingHandler) Emit2(
	handler BufferingHandler, record *LogRecord) error

func (*BaseBufferingHandler) Flush added in v0.2.1

func (self *BaseBufferingHandler) Flush() error

func (*BaseBufferingHandler) GetBuffer added in v0.2.1

func (self *BaseBufferingHandler) GetBuffer() *list.List

func (*BaseBufferingHandler) ShouldFlush added in v0.2.1

func (self *BaseBufferingHandler) ShouldFlush(_ *LogRecord) bool

type BaseHandler

type BaseHandler struct {
	*StandardFilterer
	// contains filtered or unexported fields
}

The base handler class. Acts as a base parent of any concrete handler class. By default, no formatter is specified, in this case, the "raw" message as determined by record.Message is logged.

func NewBaseHandler

func NewBaseHandler(name string, level LogLevelType) *BaseHandler

Initialize the instance - basically setting the formatter to nil and the filterer without filter.

func (*BaseHandler) Close

func (self *BaseHandler) Close()

A doing-nothing implementation as a stub for any subclass.

func (*BaseHandler) Flush

func (self *BaseHandler) Flush() error

A doing-nothing implementation as a stub for any subclass.

func (*BaseHandler) Format

func (self *BaseHandler) Format(record *LogRecord) string

Format the specified record. If a formatter is set, use it. Otherwise, use the default formatter for the module.

func (*BaseHandler) GetLevel

func (self *BaseHandler) GetLevel() LogLevelType

func (*BaseHandler) GetName

func (self *BaseHandler) GetName() string

func (*BaseHandler) Handle2

func (self *BaseHandler) Handle2(handler Handler, record *LogRecord) int

A helper function for any subclass to define its Handle() method. Logging event emission depends on filters which may have heen added to the handler. Wrap the actual emission of the record and error handling with Lock()/Unlock() of the I/O lock. Returns non-zero if the filter passed the record for emission, else zero.

func (*BaseHandler) HandleError

func (self *BaseHandler) HandleError(_ *LogRecord, _ error)

A doing-nothing implementation as a stub for any subclass.

func (*BaseHandler) Lock

func (self *BaseHandler) Lock()

Acquire a lock for serializing access to the underlying I/O.

func (*BaseHandler) SetFormatter

func (self *BaseHandler) SetFormatter(formatter Formatter)

func (*BaseHandler) SetLevel

func (self *BaseHandler) SetLevel(level LogLevelType) error

func (*BaseHandler) SetName

func (self *BaseHandler) SetName(name string)

func (*BaseHandler) Unlock

func (self *BaseHandler) Unlock()

Release the I/O lock.

type BaseRotatingHandler added in v0.2.1

type BaseRotatingHandler struct {
	*FileHandler
}

Base class for handlers that rotate log files at certain point. Not meant to be instantiated directly. Insteed, use RotatingFileHandler or TimedRotatingFileHandler.

func NewBaseRotatingHandler added in v0.2.1

func NewBaseRotatingHandler(
	filepath string, mode, bufferSize int) (*BaseRotatingHandler, error)

Initialize base rotating handler with specified filename for stream logging.

func (*BaseRotatingHandler) RolloverEmit added in v0.2.1

func (self *BaseRotatingHandler) RolloverEmit(
	handler RotatingHandler, record *LogRecord) error

A helper function for subclass to emit record.

type BoundedExponentialBackoffRetry added in v0.2.1

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

func NewBoundedExponentialBackoffRetry added in v0.2.1

func NewBoundedExponentialBackoffRetry(
	sleepFunc func(time.Duration),
	maxTries uint32,
	baseSleepTime time.Duration,
	maxSleepTime time.Duration) *BoundedExponentialBackoffRetry

func (*BoundedExponentialBackoffRetry) Do added in v0.2.1

func (self *BoundedExponentialBackoffRetry) Do(fn func() error) error

type BufferingFormatter

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

A formatter suitable for formatting a number of records.

func NewBufferingFormatter

func NewBufferingFormatter(lineFormatter Formatter) *BufferingFormatter

Initialize the buffering formatter with specified line formatter.

func (*BufferingFormatter) Format

func (self *BufferingFormatter) Format(records []*LogRecord) string

Format the specified records and return the result as a a string.

func (*BufferingFormatter) FormatFooter

func (self *BufferingFormatter) FormatFooter(_ []*LogRecord) string

Return the footer string for the specified records.

func (*BufferingFormatter) FormatHeader

func (self *BufferingFormatter) FormatHeader(_ []*LogRecord) string

Return the header string for the specified records.

type BufferingHandler added in v0.2.1

type BufferingHandler interface {
	Handler
	ShouldFlush(record *LogRecord) bool
}

type CallerInfo

type CallerInfo struct {
	PathName string
	FileName string
	LineNo   uint32
	FuncName string
}

The informations of caller of this module.

type Conf added in v0.2.5

type Conf struct {
	Version    int                      `json:"version" yaml:"version"`
	Root       ConfMap                  `json:"root" yaml:"root"`
	Loggers    map[string]ConfMap       `json:"loggers" yaml:"loggers"`
	Handlers   map[string]ConfMap       `json:"handlers" yaml:"handlers"`
	Formatters map[string]ConfFormatter `json:"formatters" yaml:"formatters"`
	Filters    map[string]ConfFilter    `json:"filters" yaml:"filters"`
}

type ConfEnv added in v0.2.5

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

func NewConfigEnv added in v0.2.5

func NewConfigEnv() *ConfEnv

type ConfFilter added in v0.2.5

type ConfFilter struct {
	Name string `json:"name"`
}

type ConfFormatter added in v0.2.5

type ConfFormatter struct {
	Format     *string `json:"format" yaml:"format"`
	DateFormat *string `json:"datefmt" yaml:"datefmt"`
}

type ConfMap added in v0.2.5

type ConfMap map[string]interface{}

A map represents configuration of various key and variable length. Access it just in raw key after parsed from config file.

func (ConfMap) GetBool added in v0.2.5

func (self ConfMap) GetBool(key string) (bool, error)

func (ConfMap) GetInt added in v0.2.5

func (self ConfMap) GetInt(key string) (int, error)

func (ConfMap) GetString added in v0.2.5

func (self ConfMap) GetString(key string) (string, error)

func (ConfMap) GetUint16 added in v0.2.5

func (self ConfMap) GetUint16(key string) (uint16, error)

func (ConfMap) GetUint32 added in v0.2.5

func (self ConfMap) GetUint32(key string) (uint32, error)

func (ConfMap) GetUint64 added in v0.2.5

func (self ConfMap) GetUint64(key string) (uint64, error)

type DatagramHandler added in v0.2.5

type DatagramHandler struct {
	*SocketHandler
}

A handler class which writes logging records, in gob format, to a datagram socket.

func NewDatagramHandler added in v0.2.5

func NewDatagramHandler(host string, port uint16) *DatagramHandler

type ErrorRetry added in v0.2.1

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

func NewErrorRetry added in v0.2.1

func NewErrorRetry() *ErrorRetry

func (*ErrorRetry) Backoff added in v0.2.1

func (self *ErrorRetry) Backoff(backoff uint32) *ErrorRetry

func (*ErrorRetry) Copy added in v0.2.1

func (self *ErrorRetry) Copy() *ErrorRetry

func (*ErrorRetry) Deadline added in v0.2.1

func (self *ErrorRetry) Deadline(deadline time.Duration) *ErrorRetry

func (*ErrorRetry) Delay added in v0.2.1

func (self *ErrorRetry) Delay(delay time.Duration) *ErrorRetry

func (*ErrorRetry) Do added in v0.2.1

func (self *ErrorRetry) Do(fn func() error) error

func (*ErrorRetry) MaxDelay added in v0.2.1

func (self *ErrorRetry) MaxDelay(maxDelay time.Duration) *ErrorRetry

func (*ErrorRetry) MaxJitter added in v0.2.1

func (self *ErrorRetry) MaxJitter(maxJitter float32) *ErrorRetry

func (*ErrorRetry) MaxTries added in v0.2.1

func (self *ErrorRetry) MaxTries(maxTries int) *ErrorRetry

func (*ErrorRetry) OnError added in v0.2.1

func (self *ErrorRetry) OnError(err error) *ErrorRetry

func (*ErrorRetry) SleepFunc added in v0.2.1

func (self *ErrorRetry) SleepFunc(fn func(time.Duration)) *ErrorRetry

type ExponentialBackoffRetry added in v0.2.1

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

func NewExponentialBackoffRetry added in v0.2.1

func NewExponentialBackoffRetry(
	sleepFunc func(time.Duration),
	baseSleepTime time.Duration,
	maxSleepTime time.Duration) *ExponentialBackoffRetry

func (*ExponentialBackoffRetry) Do added in v0.2.1

func (self *ExponentialBackoffRetry) Do(fn func() error) error

type ExtractAttr

type ExtractAttr func(record *LogRecord) string

Function type of extracting the corresponding LogRecord info for the attribute string.

type FileHandler added in v0.2.1

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

A handler class which writes formatted logging records to disk files.

func NewFileHandler added in v0.2.1

func NewFileHandler(filename string, mode int, bufferSize int) (*FileHandler, error)

Open the specified file and use it as the stream for logging.

func (*FileHandler) Close added in v0.2.1

func (self *FileHandler) Close()

Close this file handler.

func (*FileHandler) Emit added in v0.2.1

func (self *FileHandler) Emit(record *LogRecord) error

Emit a record.

func (*FileHandler) GetFilePath added in v0.2.1

func (self *FileHandler) GetFilePath() string

Return the absolute path of logging file.

func (*FileHandler) Handle added in v0.2.1

func (self *FileHandler) Handle(record *LogRecord) int

func (*FileHandler) Open added in v0.2.1

func (self *FileHandler) Open() error

Open the current base file with the (original) mode and encoding, and set it to the underlying stream handler. Return non-nil error if error happens.

type FileStream added in v0.2.1

type FileStream struct {
	File       *os.File
	BufferSize int
	Buffer     *bytes.Buffer
	Offset     int64
}

A class wraps os.File to the stream interface.

func NewFileStream added in v0.3.0

func NewFileStream(f *os.File, bufferSize int) *FileStream

func (*FileStream) Close added in v0.2.1

func (self *FileStream) Close() error

func (*FileStream) Flush added in v0.2.1

func (self *FileStream) Flush() error

func (*FileStream) Tell added in v0.2.1

func (self *FileStream) Tell() (int64, error)

func (*FileStream) Write added in v0.2.1

func (self *FileStream) Write(s string) error

type Filter

type Filter interface {
	Filter(record *LogRecord) bool
}

Filter interface is to perform arbitrary filtering of LogRecords. Loggers and handlers can optionally use filter instances to filter records as desired.

type Filterer

type Filterer interface {
	AddFilter(filter Filter)
	RemoveFilter(filter Filter)
	Filter(record *LogRecord) int
}

An interface for managing filters.

type FindCallerFunc

type FindCallerFunc func() *CallerInfo

type Formatter

type Formatter interface {
	Format(record *LogRecord) string
}

Formatter interface is for converting a LogRecord to text. Formatters need to know how a LogRecord is constructed. They are responsible for converting a LogRecord to (usually) a string which can be interpreted by either a human or an external system.

type GetFormatArgsFunc

type GetFormatArgsFunc func(record *LogRecord) []interface{}

type HandleFunc added in v0.3.0

type HandleFunc func(record *LogRecord) int

type Handler

type Handler interface {
	// Return the name of Handler.
	GetName() string
	// Set the name of Handler.
	SetName(name string)
	// Return the log level of Handler.
	GetLevel() LogLevelType
	// Set the log level of Handler.
	SetLevel(level LogLevelType) error

	// For Formatter.
	// Format the specified record.
	Formatter
	// Set the formatter for this Handler.
	SetFormatter(formatter Formatter)

	// For Filter managing.
	Filterer

	// Do whatever it takes to actually log the specified logging record.
	Emit(record *LogRecord) error
	// Conditionally emit the specified logging record.
	Handle(record *LogRecord) int
	// Handle errors which occur during an Emit() call.
	HandleError(record *LogRecord, err error)
	// Ensure all logging output has been flushed.
	Flush() error
	// Tidy up any resources used by the handler.
	Close()
}

An interface for dispatching logging events to specific destinations. Handler can optionally use formatter instances to format records as desired.

type HandlerCloser

type HandlerCloser struct {
	// contains filtered or unexported fields
}
var (
	Closer *HandlerCloser
)

func NewHandlerCloser

func NewHandlerCloser() *HandlerCloser

func (*HandlerCloser) AddHandler

func (self *HandlerCloser) AddHandler(handler Handler)

func (*HandlerCloser) Close

func (self *HandlerCloser) Close()

func (*HandlerCloser) RemoveHandler

func (self *HandlerCloser) RemoveHandler(handler Handler)

type ListSet added in v0.3.0

type ListSet struct {
	*list.List
}

func NewListSet added in v0.3.0

func NewListSet() *ListSet

func (*ListSet) SetAdd added in v0.3.0

func (self *ListSet) SetAdd(i interface{})

func (*ListSet) SetClone added in v0.3.0

func (self *ListSet) SetClone() *ListSet

func (*ListSet) SetContains added in v0.3.0

func (self *ListSet) SetContains(i interface{}) bool

func (*ListSet) SetRemove added in v0.3.0

func (self *ListSet) SetRemove(i interface{}) bool

type LogLevelType

type LogLevelType uint8

Type definition for log level

const (
	LevelCritical LogLevelType = 50
	LevelFatal    LogLevelType = LevelCritical
	LevelError    LogLevelType = 40
	LevelWarning  LogLevelType = 30
	LevelWarn     LogLevelType = LevelWarning
	LevelInfo     LogLevelType = 20
	LevelDebug    LogLevelType = 10
	LevelTrace    LogLevelType = 5
	LevelNotset   LogLevelType = 0
)

Default levels and level names, these can be replaced with any positive set of values having corresponding names. There is a pseudo-level, NOTSET, which is only really there as a lower limit for user-defined levels. Handlers and loggers are initialized with NOTSET so that they will log all messages, even at user-defined levels.

func GetNameLevel added in v0.3.5

func GetNameLevel(name string) (level LogLevelType, ok bool)

Return the level of specicial level name.

func (LogLevelType) String

func (level LogLevelType) String() string

Print the name of corresponding log level.

type LogRecord

type LogRecord struct {
	CreatedTime time.Time
	AscTime     string
	Name        string
	Level       LogLevelType
	PathName    string
	FileName    string
	LineNo      uint32
	FuncName    string
	Format      string
	UseFormat   bool
	Args        []interface{}
	Message     string
}

A LogRecord instance represents an event being logged. LogRecord instances are created every time something is logged. They contain all the information pertinent to the event being logged. The main information passed in is in Message and Args, which are combined using fmt.Sprintf() or fmt.Sprint(), depending on value of UseFormat flag, to create the message field of the record. The record also includes information such as when the record was created, the source line where the logging call was made, and any exception information to be logged.

func NewLogRecord

func NewLogRecord(
	name string,
	level LogLevelType,
	pathName string,
	fileName string,
	lineNo uint32,
	funcName string,
	format string,
	useFormat bool,
	args []interface{}) *LogRecord

Initialize a logging record with interesting information.

func (*LogRecord) GetMessage

func (self *LogRecord) GetMessage() string

Return the message for this LogRecord. The message is composed of the Message and any user-supplied arguments.

func (*LogRecord) String

func (self *LogRecord) String() string

Return the string representation for this LogRecord.

type Logger

type Logger interface {
	// A Logger is a node in Manager tree.
	Node

	// Return the name of Logger.
	GetName() string
	// Return the propagate of Logger.
	GetPropagate() bool
	// Set the propagate.
	SetPropagate(v bool)
	// Return the logging level attached to this Logger.
	GetLevel() LogLevelType
	// Set the logging level attached to this Logger.
	SetLevel(level LogLevelType) error
	// Query whether this Logger is enabled for specified logging level.
	IsEnabledFor(level LogLevelType) bool
	// Get the effective level for this Logger.
	// An effective level is the first level value of Logger and its all parent
	// in the Logger hierarchy, which is not equal to LevelNotset.
	GetEffectiveLevel() LogLevelType

	// Fatal formats using the default formats for its operands and
	// logs a message with severity "LevelFatal".
	Fatal(args ...interface{})
	// Error formats using the default formats for its operands and
	// logs a message with severity "LevelError".
	Error(args ...interface{})
	// Warn formats using the default formats for its operands and
	// logs a message with severity "LevelWarn".
	Warn(args ...interface{})
	// Info formats using the default formats for its operands and
	// logs a message with severity "LevelInfo".
	Info(args ...interface{})
	// Debug formats using the default formats for its operands and
	// logs a message with severity "LevelDebug".
	Debug(args ...interface{})
	// Trace formats using the default formats for its operands and
	// logs a message with severity "LevelTrace".
	Trace(args ...interface{})
	// Log formats using the default formats for its operands and
	// logs a message with specified severity level.
	Log(level LogLevelType, args ...interface{})

	// Fatalf formats according to a format specifier and
	// logs a message with severity "LevelFatal".
	Fatalf(format string, args ...interface{})
	// Errorf formats according to a format specifier and
	// logs a message with severity "LevelError".
	Errorf(format string, args ...interface{})
	// Warnf formats according to a format specifier and
	// logs a message with severity "LevelWarn".
	Warnf(format string, args ...interface{})
	// Infof formats according to a format specifier and
	// logs a message with severity "LevelInfo".
	Infof(format string, args ...interface{})
	// Debugf formats according to a format specifier and
	// logs a message with severity "LevelDebug".
	Debugf(format string, args ...interface{})
	// Tracef formats according to a format specifier and
	// logs a message with severity "LevelTrace".
	Tracef(format string, args ...interface{})
	// Logf formats according to a format specifier and
	// logs a message with specified severity level.
	Logf(level LogLevelType, format string, args ...interface{})

	// Add the specified handler to this Logger.
	AddHandler(handler Handler)
	// Remove the specified handler from this Logger.
	RemoveHandler(handler Handler)
	// Return all handler of this Logger.
	GetHandlers() []Handler
	// Call all handlers on the specified record.
	CallHandlers(record *LogRecord)

	// Filterer
	Filterer

	// Return the Manager of this Logger.
	GetManager() *Manager
	// Set the Manager of this Logger.
	SetManager(manager *Manager)
	// Return the parent Logger of this Logger.
	GetParent() Logger
	// Set the parent Logger of this Logger.
	SetParent(parent Logger)
}

An interface represents a single logging channel. A "logging channel" indicates an area of an application. Exactly how an "area" is defined is up to the application developer. Since an application can have any number of areas, logging channels are identified by a unique string. Application areas can be nested (e.g. an area of "input processing" might include sub-areas "read CSV files", "read XLS files" and "read Gnumberic files"). To cater for this natural nesting, channel names are organized into a namespace hierarchy where levels are separated by periods, much like the Java or Python package namespace. So in the instance given above, channel names might be "input" for the upper level, an "input.csv", "input.xls" and "input.gnu" for the sub-levels. There is no arbitrary limit to the depth of nesting.

func GetLogger

func GetLogger(name string) Logger

Return a logger with the specified name, creating it if necessary. If empty name is specified, return the root logger.

type LoggerMaker

type LoggerMaker func(name string) Logger

The logger maker function type.

type Manager

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

This is [under normal circumstances] just one manager instance, which holds the hierarchy of loggers.

func NewManager

func NewManager(logger Logger) *Manager

Initialize the manager with the root node of the logger hierarchy.

func (*Manager) GetLogger

func (self *Manager) GetLogger(name string) Logger

Get a logger with the specified name (channel name), creating it if it doesn't yet exists. This name is a dot-separated hierarchical name, such as "a", "a.b", "a.b.c" or similar.

If a placeholder existed for the specified name [i.e. the logger didn't exist but a child of it did], replace it with the created logger and fix up the parent/child references which pointed to the placeholder to now point to the logger.

func (*Manager) SetLoggerMaker

func (self *Manager) SetLoggerMaker(maker LoggerMaker)

Set the logger maker to be used when instantiating a logger with this manager.

type MemoryHandler added in v0.2.1

type MemoryHandler struct {
	*BaseBufferingHandler
	// contains filtered or unexported fields
}

func NewMemoryHandler added in v0.2.1

func NewMemoryHandler(
	capacity uint64, flushLevel LogLevelType, target Handler) *MemoryHandler

func (*MemoryHandler) Close added in v0.2.1

func (self *MemoryHandler) Close()

func (*MemoryHandler) Emit added in v0.2.1

func (self *MemoryHandler) Emit(record *LogRecord) error

func (*MemoryHandler) Flush added in v0.2.1

func (self *MemoryHandler) Flush() error

func (*MemoryHandler) Handle added in v0.2.1

func (self *MemoryHandler) Handle(record *LogRecord) int

func (*MemoryHandler) SetTarget added in v0.2.1

func (self *MemoryHandler) SetTarget(target Handler)

func (*MemoryHandler) ShouldFlush added in v0.2.1

func (self *MemoryHandler) ShouldFlush(record *LogRecord) bool

type NTimesRetry added in v0.2.1

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

func NewNTimesRetry added in v0.2.1

func NewNTimesRetry(
	sleepFunc func(time.Duration),
	maxTimes uint32,
	sleepTimeBetweenRetries time.Duration) *NTimesRetry

func (*NTimesRetry) Do added in v0.2.1

func (self *NTimesRetry) Do(fn func() error) error

type NameFilter

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

The base filter allows events which are below a certain point in the logger hierarchy. For Example, a filter initialized with "A.B" will allow events logged by loggers "A.B", "A.B.C", "A.B.C.D", "A.B.D" etc. but not "A.BB", "B.A.B" etc. If initialized with the empty string, all events are passed.

func NewNameFilter

func NewNameFilter(name string) *NameFilter

Initialize a name filter. The name of the logger/handler is specified, all the events of logger's children are allowed through the filter. If no name is specified, every event is allowed.

func (*NameFilter) Filter

func (self *NameFilter) Filter(record *LogRecord) bool

Determine if the specified record is to be logged. Is the specified record to be logged? Returns false for no, true for yes. If deemed appropriate, the record may be modified in-place.

type Node

type Node interface {
	// Return the node type.
	Type() NodeType
}

Node interface for the placeHolder/logger tree in manager.

type NodeType

type NodeType uint8

Node type definition for the placeholder/logger tree in manager.

const (
	NodeUnknown NodeType = 0 + iota
	NodeLogger
	NodePlaceHolder
)

type NullHandler added in v0.2.1

type NullHandler struct {
	*BaseHandler
}

This handler does nothing. It's intended to be used to avoid the "No handlers could be found for logger XXX" one-off warning. This is important for library code, which may contain code to log events. If a user of the library does not configure logging, the one-off warning might be produced; to avoid this, the library developer simply needs to instantiate a NullHandler and add it to the top-level logger of the library module or package.

func NewNullHandler added in v0.2.1

func NewNullHandler() *NullHandler

Initialize a NullHandler.

func (*NullHandler) Emit added in v0.2.1

func (self *NullHandler) Emit(_ *LogRecord) error

func (*NullHandler) Handle added in v0.2.1

func (self *NullHandler) Handle(_ *LogRecord) int

type OnceRetry added in v0.2.1

type OnceRetry struct {
	*NTimesRetry
}

func NewOnceRetry added in v0.2.1

func NewOnceRetry(
	sleepFunc func(time.Duration),
	sleepTimeBetweenRetries time.Duration) *OnceRetry

type PlaceHolder

type PlaceHolder struct {
	Loggers *ListSet
}

Placeholder instances are used in the manager logger hierarchy to take the place of nodes for which no loggers have been defined. This class is intended for internal use only and not as part of the public API.

func NewPlaceHolder

func NewPlaceHolder(logger Logger) *PlaceHolder

Initialize a PlaceHolder with the specified logger being a child of this PlaceHolder.

func (*PlaceHolder) Append

func (self *PlaceHolder) Append(logger Logger)

Add the specified logger as a child of this PlaceHolder.

func (*PlaceHolder) Type

func (self *PlaceHolder) Type() NodeType

type Retry added in v0.2.1

type Retry interface {
	Do(func() error) error
}

type RootLogger

type RootLogger struct {
	*StandardLogger
}

A root logger is not that different to any other logger, except that it must have a logging level and there is only one instance of it in the hierarchy.

func NewRootLogger

func NewRootLogger(level LogLevelType) *RootLogger

Initialize the root logger with the name "root".

type RotatingFileHandler added in v0.2.1

type RotatingFileHandler struct {
	*BaseRotatingHandler
	// contains filtered or unexported fields
}

Handler for logging to a set of files, which switches from one file to the next when the current file reaches a certain size.

func MustNewRotatingFileHandler added in v0.2.1

func MustNewRotatingFileHandler(
	filepath string,
	mode int,
	bufferSize int,
	bufferFlushTime time.Duration,
	inputChanSize int,
	maxBytes uint64,
	backupCount uint32) *RotatingFileHandler

func NewRotatingFileHandler added in v0.2.1

func NewRotatingFileHandler(
	filepath string,
	mode int,
	bufferSize int,
	bufferFlushTime time.Duration,
	inputChanSize int,
	maxBytes uint64,
	backupCount uint32) (*RotatingFileHandler, error)

Open the specified file and use it as the stream for logging.

By default, the file grows indefinitely. You can specify particular values of maxBytes and backupCount to allow the file to rollover at a predetermined size.

Rollover occurs whenever the current log file is nearly maxBytes in length. If backupCount is >= 1, the system will successively create new files with the same pathname as the base file, but with extensions ".1", ".2" etc. append to it. For example, with a backupCount of 5 and a base file name of "app.log", you would get "app.log", "app.log.1", "app.log.2", ... through to "app.log.5". The file being written to is always "app.log" - when it gets filled up, it is closed and renamed to "app.log.1", and if files "app.log.1", "app.log.2" etc. exist, then they are renamed to "app.log.2", "app.log.3" etc. respectively.

If maxBytes is zero, rollover never occurs.

bufferSize specifies the size of the internal buffer. If it is positive, the internal buffer will be enabled, the logs will be first written into the internal buffer, when the internal buffer is full all buffer content will be flushed to file. bufferFlushTime specifies the time for flushing the internal buffer in period, no matter the buffer is full or not. Its value is used only when inputChanSize is set to positive. inputChanSize specifies the chan size of the handler. If it is positive, this handler will be initialized as a standardlone go routine to handle log message.

func (*RotatingFileHandler) Close added in v0.3.0

func (self *RotatingFileHandler) Close()

func (*RotatingFileHandler) DoRollover added in v0.2.1

func (self *RotatingFileHandler) DoRollover() (err error)

Do a rollover, as described above.

func (*RotatingFileHandler) Emit added in v0.2.1

func (self *RotatingFileHandler) Emit(record *LogRecord) error

Emit a record.

func (*RotatingFileHandler) Handle added in v0.2.1

func (self *RotatingFileHandler) Handle(record *LogRecord) int

func (*RotatingFileHandler) RotateFile added in v0.2.1

func (self *RotatingFileHandler) RotateFile(sourceFile, destFile string) error

Rotate source file to destination file if source file exists.

func (*RotatingFileHandler) ShouldRollover added in v0.2.1

func (self *RotatingFileHandler) ShouldRollover(
	record *LogRecord) (bool, string)

Determine if rollover should occur. Basically, see if the supplied record would cause the file to exceed the size limit we have.

type RotatingHandler added in v0.2.1

type RotatingHandler interface {
	Handler
	// Determine if rollover should occur.
	ShouldRollover(record *LogRecord) (doRollover bool, message string)
	// Do a rollover.
	DoRollover() error
}

An interface for rotating handler abstraction.

type SetFormatterable added in v0.2.5

type SetFormatterable interface {
	SetFormatter(formatter Formatter)
}

type SetLevelable added in v0.2.5

type SetLevelable interface {
	SetLevel(level LogLevelType) error
}

type SocketHandler added in v0.2.1

type SocketHandler struct {
	*BaseHandler
	// contains filtered or unexported fields
}

A handler class which write logging records, in gob format, to a streaming socket. The socket is kept open across logging calls. If the peer resets it, an attempt is made to reconnect on the next call.

func NewSocketHandler added in v0.2.1

func NewSocketHandler(host string, port uint16) *SocketHandler

Initializes the handler with a specific host address and port. The attribute 'closeOnError' is set to true by default, which means that if a socket error occurs, the socket is silently closed and then reopen on the next loggging call.

func (*SocketHandler) Close added in v0.2.1

func (self *SocketHandler) Close()

Close the socket.

func (*SocketHandler) Emit added in v0.2.1

func (self *SocketHandler) Emit(record *LogRecord) error

Emit a record. Marshals the record and writes it to the socket in binary format. If there is an error with the socket, silently drop the packet. If there was a problem with the socket, re-establishes the socket.

func (*SocketHandler) Handle added in v0.2.1

func (self *SocketHandler) Handle(record *LogRecord) int

func (*SocketHandler) HandleError added in v0.2.1

func (self *SocketHandler) HandleError(record *LogRecord, err error)

Handles an error during logging. An error has occurred during logging. Most likely cause connection lost. Close the socket so that we can retry on the next event.

func (*SocketHandler) Marshal added in v0.2.1

func (self *SocketHandler) Marshal(record *LogRecord) ([]byte, error)

Marshals the record in gob binary format and returns it ready for transmission across socket.

type SocketLogRecord added in v0.2.1

type SocketLogRecord struct {
	CreatedTime time.Time
	AscTime     string
	Name        string
	Level       LogLevelType
	PathName    string
	FileName    string
	LineNo      uint32
	FuncName    string
	Format      string
	UseFormat   bool
	Message     string
}

A SocketLogRecord instance contains all LogRecord fields tailored for uploading to socket server. We could keep the interested fields and remove all others to minimize the network bandwidth usage.

type StandardFilterer

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

An base class for loggers and handlers which allows them to share common code of managing the filters.

func NewStandardFilterer

func NewStandardFilterer() *StandardFilterer

Initialize the standard filterer, with no filter.

func (*StandardFilterer) AddFilter

func (self *StandardFilterer) AddFilter(filter Filter)

Add the specified filter.

func (*StandardFilterer) Filter

func (self *StandardFilterer) Filter(record *LogRecord) int

Determine if a record is loggable by consulting all the filters. The default is to allow the record to be logged: any filter can veto this and the record is then dropped. Returns a zero value if a record is to be dropped, else non-zero.

func (*StandardFilterer) GetFilters

func (self *StandardFilterer) GetFilters() *ListSet

Return all the filter in this filterer.

func (*StandardFilterer) RemoveFilter

func (self *StandardFilterer) RemoveFilter(filter Filter)

Remove the specified filter.

type StandardFormatter

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

The standard formatter. It allows a formatting string to be specified. If none is supplied, the default value of "%(message)s" is used.

The formatter can be initialized with a format string which makes use of knowledge of the LogRecord attributes - e.g. the default value mentioned above makes use of the fact that the user's message and arguments are preformatted into a LogRecord's message attribute. Currently, the usefull attributes in a LogRecord are described by:

%(name)s Name of the logger(logging channel) %(levelno)d Numeric logging level for the message %(levelname)s Text logging level for the message %(pathname)s Full pathname of the source file where the logging

call was issued (is available)

%(filename)s Filename portion of pathname %(lineno)d Source line number where the logging call was issued %(funcname)s Function name %(created)d Time when the LogRecord was created(time.Now()

return value)

%(asctime)s Textual time when LogRecord was created %(message)s The result of record.GetMessage(), computed just as the

record is emitted

func NewStandardFormatter

func NewStandardFormatter(format string, dateFormat string) *StandardFormatter

Initialize the formatter with specified format strings. Allow for specialized date formatting with the dateFormat arguement.

func (*StandardFormatter) Format

func (self *StandardFormatter) Format(record *LogRecord) string

Format the specified record as text. The record's attribute is used as the operand to a string formatting operation which yields the returned string. Before the formatting, a couple of preparatory steps are carried out. The message attribute of the record is computed using LogRecord.GetMessage(). If the formatting string uses the time, FormatTime() is called to format the event time.

func (*StandardFormatter) FormatAll

func (self *StandardFormatter) FormatAll(record *LogRecord) string

Helper function using regexp to replace every valid format attribute string to the record's specific value.

func (*StandardFormatter) FormatTime

func (self *StandardFormatter) FormatTime(record *LogRecord) string

Return the creation time of the specified LogRecord as formatted text. This method should be called from Format() by a formatter which wants to make use of a formatted time. This method can be overridden in formatters to provide for any specific requirement, but the basic behaviour is as follows: the dateFormat is used with strftime.Format() to format the creation time of the record.

type StandardLogger

type StandardLogger struct {
	*StandardFilterer
	// contains filtered or unexported fields
}

The standard logger implementation class.

func NewStandardLogger

func NewStandardLogger(name string, level LogLevelType) *StandardLogger

Initialize a standard logger instance with name and logging level.

func (*StandardLogger) AddHandler

func (self *StandardLogger) AddHandler(handler Handler)

func (*StandardLogger) CallHandlers added in v0.3.0

func (self *StandardLogger) CallHandlers(record *LogRecord)

func (*StandardLogger) Debug

func (self *StandardLogger) Debug(args ...interface{})

func (*StandardLogger) Debugf

func (self *StandardLogger) Debugf(format string, args ...interface{})

func (*StandardLogger) Error

func (self *StandardLogger) Error(args ...interface{})

func (*StandardLogger) Errorf

func (self *StandardLogger) Errorf(format string, args ...interface{})

func (*StandardLogger) Fatal

func (self *StandardLogger) Fatal(args ...interface{})

func (*StandardLogger) Fatalf

func (self *StandardLogger) Fatalf(format string, args ...interface{})

func (*StandardLogger) GetChild

func (self *StandardLogger) GetChild(suffix string) Logger

Get a logger which is descendant to this one. This is a convenience method, such that

logging.GetLogger("abc").GetChild("def.ghi")

is the same as

logging.GetLogger("abc.def.ghi")

It's useful, for example, when the parent logger is named using some string unknown or random.

func (*StandardLogger) GetEffectiveLevel

func (self *StandardLogger) GetEffectiveLevel() LogLevelType

Get the effective level for this logger. Loop through this logger and its parents in the logger hierarchy, looking for a non-zero logging level. Return the first one found.

func (*StandardLogger) GetHandlers

func (self *StandardLogger) GetHandlers() []Handler

func (*StandardLogger) GetLevel

func (self *StandardLogger) GetLevel() LogLevelType

func (*StandardLogger) GetManager

func (self *StandardLogger) GetManager() *Manager

func (*StandardLogger) GetName

func (self *StandardLogger) GetName() string

func (*StandardLogger) GetParent

func (self *StandardLogger) GetParent() Logger

func (*StandardLogger) GetPropagate

func (self *StandardLogger) GetPropagate() bool

func (*StandardLogger) Handle

func (self *StandardLogger) Handle(record *LogRecord)

func (*StandardLogger) Info

func (self *StandardLogger) Info(args ...interface{})

func (*StandardLogger) Infof

func (self *StandardLogger) Infof(format string, args ...interface{})

func (*StandardLogger) IsEnabledFor

func (self *StandardLogger) IsEnabledFor(level LogLevelType) bool

func (*StandardLogger) Log

func (self *StandardLogger) Log(
	level LogLevelType, args ...interface{})

func (*StandardLogger) Logf

func (self *StandardLogger) Logf(
	level LogLevelType, format string, args ...interface{})

func (*StandardLogger) RemoveHandler

func (self *StandardLogger) RemoveHandler(handler Handler)

func (*StandardLogger) SetFindCallerFunc

func (self *StandardLogger) SetFindCallerFunc(f FindCallerFunc)

func (*StandardLogger) SetLevel

func (self *StandardLogger) SetLevel(level LogLevelType) error

func (*StandardLogger) SetManager

func (self *StandardLogger) SetManager(manager *Manager)

func (*StandardLogger) SetParent

func (self *StandardLogger) SetParent(parent Logger)

func (*StandardLogger) SetPropagate

func (self *StandardLogger) SetPropagate(v bool)

func (*StandardLogger) Trace added in v0.3.5

func (self *StandardLogger) Trace(args ...interface{})

func (*StandardLogger) Tracef added in v0.3.5

func (self *StandardLogger) Tracef(format string, args ...interface{})

func (*StandardLogger) Type

func (self *StandardLogger) Type() NodeType

func (*StandardLogger) Warn

func (self *StandardLogger) Warn(args ...interface{})

func (*StandardLogger) Warnf

func (self *StandardLogger) Warnf(format string, args ...interface{})

type StdoutHandler added in v0.2.1

type StdoutHandler struct {
	*StreamHandler
}

func NewStdoutHandler added in v0.2.1

func NewStdoutHandler() *StdoutHandler

func (*StdoutHandler) Close added in v0.2.1

func (self *StdoutHandler) Close()

func (*StdoutHandler) Emit added in v0.2.1

func (self *StdoutHandler) Emit(record *LogRecord) error

func (*StdoutHandler) Handle added in v0.2.1

func (self *StdoutHandler) Handle(record *LogRecord) int

type StdoutStream added in v0.2.1

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

func NewStdoutStream added in v0.2.1

func NewStdoutStream() *StdoutStream

func (*StdoutStream) Close added in v0.2.1

func (self *StdoutStream) Close() error

func (*StdoutStream) Flush added in v0.2.1

func (self *StdoutStream) Flush() error

func (*StdoutStream) Tell added in v0.2.1

func (self *StdoutStream) Tell() (int64, error)

func (*StdoutStream) Write added in v0.2.1

func (self *StdoutStream) Write(s string) error

type Stream added in v0.2.1

type Stream interface {
	// Report the current offset in the stream.
	Tell() (offset int64, err error)
	// Write a string into the stream.
	Write(s string) error
	// Flush the stream.
	Flush() error
	// Close the stream.
	Close() error
}

An interface to stream abstraction.

type StreamHandler added in v0.2.1

type StreamHandler struct {
	*BaseHandler
	// contains filtered or unexported fields
}

A handler class with writes logging records, appropriately formatted, to a stream. Note that this class doesn't close the stream, as os.Stdin or os.Stdout my be used. However a Close2() method is there for subclass.

func NewStreamHandler added in v0.2.1

func NewStreamHandler(
	name string, level LogLevelType, stream Stream) *StreamHandler

Initialize a stream handler with name, logging level and underlying stream.

func (*StreamHandler) Close2 added in v0.2.1

func (self *StreamHandler) Close2()

A helper function for subclass implementation to close stream.

func (*StreamHandler) Emit added in v0.2.1

func (self *StreamHandler) Emit(record *LogRecord) error

Emit a record.

func (*StreamHandler) Emit2 added in v0.2.1

func (self *StreamHandler) Emit2(
	handler Handler, record *LogRecord) error

A helper function to emit a record. If a formatter is specified, it is used to format the record. The record is then written to the stream with a trailing newline.

func (*StreamHandler) Flush added in v0.2.1

func (self *StreamHandler) Flush() error

Flush the stream.

func (*StreamHandler) GetStream added in v0.2.1

func (self *StreamHandler) GetStream() Stream

Return the underlying stream.

func (*StreamHandler) Handle added in v0.2.1

func (self *StreamHandler) Handle(record *LogRecord) int

Handle() function is for the usage of stream handler on its own.

func (*StreamHandler) SetStream added in v0.2.1

func (self *StreamHandler) SetStream(s Stream)

Set the underlying stream.

type SyslogHandler added in v0.2.1

type SyslogHandler struct {
	*BaseHandler
	// contains filtered or unexported fields
}

A handler class which sends formatted logging records to a syslog server.

func NewSyslogHandler added in v0.2.1

func NewSyslogHandler(
	priority syslog.Priority,
	tag string) (*SyslogHandler, error)

Initialize a syslog handler. The arguements are the same as New() in package log/syslog.

func NewSyslogHandlerToAddr added in v0.2.1

func NewSyslogHandlerToAddr(
	network, raddr string,
	priority syslog.Priority,
	tag string) (*SyslogHandler, error)

Initialize a syslog handler with connection to a specified syslog server. The arguements are the same as Dial() in package log/syslog.

func (*SyslogHandler) Close added in v0.2.1

func (self *SyslogHandler) Close()

func (*SyslogHandler) Emit added in v0.2.1

func (self *SyslogHandler) Emit(record *LogRecord) error

Emit a record. The record is formatted, and then sent to the syslog server in specified log level.

func (*SyslogHandler) Flush added in v0.2.1

func (self *SyslogHandler) Flush() error

func (*SyslogHandler) Handle added in v0.2.1

func (self *SyslogHandler) Handle(record *LogRecord) int

type TimedRotatingFileHandler added in v0.2.1

type TimedRotatingFileHandler struct {
	*BaseRotatingHandler
	// contains filtered or unexported fields
}

Handler for logging to a file, rotating the log file at certain timed intervals.

if backupCount is > 0, when rollover is done, no more than backupCount files are kept - the oldest ones are deleted.

func NewTimedRotatingFileHandler added in v0.2.1

func NewTimedRotatingFileHandler(
	filepath string,
	mode int,
	bufferSize int,
	bufferFlushTime time.Duration,
	inputChanSize int,
	when string,
	interval uint32,
	backupCount uint32,
	utc bool) (*TimedRotatingFileHandler, error)

Note: weekday index starts from 0(Monday) to 6(Sunday) in Python. But in Golang weekday index starts from 0(Sunday) to 6(Saturday). Here we stick to semantics of the original Python logging interface.

func (*TimedRotatingFileHandler) Close added in v0.3.6

func (self *TimedRotatingFileHandler) Close()

func (*TimedRotatingFileHandler) DoRollover added in v0.2.1

func (self *TimedRotatingFileHandler) DoRollover() (err error)

Do a rollover; in this case, a date/time stamp is appended to the filename when the rollover happens. However, you want the file to be named for the start of the interval, not the current time. If there is a backup count, then we have to get a list of matching filenames, sort them and remove the one with the oldest suffix.

func (*TimedRotatingFileHandler) Emit added in v0.2.1

func (self *TimedRotatingFileHandler) Emit(record *LogRecord) error

Emit a record.

func (*TimedRotatingFileHandler) Handle added in v0.2.1

func (self *TimedRotatingFileHandler) Handle(record *LogRecord) int

func (*TimedRotatingFileHandler) ShouldRollover added in v0.2.1

func (self *TimedRotatingFileHandler) ShouldRollover(
	record *LogRecord) (bool, string)

Determine if rollover should occur.

type UntilElapsedRetry added in v0.2.1

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

func NewUntilElapsedRetry added in v0.2.1

func NewUntilElapsedRetry(
	sleepFunc func(time.Duration),
	sleepTimeBetweenRetries time.Duration,
	maxElapsedTime time.Duration) *UntilElapsedRetry

func (*UntilElapsedRetry) Do added in v0.2.1

func (self *UntilElapsedRetry) Do(fn func() error) error

Jump to

Keyboard shortcuts

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