vlog

package module
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2019 License: BSD-2-Clause Imports: 17 Imported by: 2

README

The Very Log lib for golang

Table of Contents

Usage

Get Logger

Each logger has a name, there is only one logger for same name. You can pass a name, or just using current package name as logger name:

var logger = vlog.GetLogger(loggerName) // specify a logger name
var logger = vlog.CurrentPackageLogger() // using full package name as logger name
Log Message

Logger has six levels: Trace/Debug/Info/Warn/Error/Critical, multi messages can be passed to logger methods, the messages are joined with a delimiter space char(' ').

logger.Info("start the server")
logger.Info("start the server at", host+":"+strconv.itoa(port))
logger.Error("start server error:", err)

The Logger's xxxFormat methods can use format string to format params, using {} as a placeholder. If has more params than placeholders, the remain params would be omitted. If there ware more placeholders than params, the extra placeholders will be output as original.

logger.InfoFormat("start the server at {}:{}", host, port)
logger.ErrorFormat("start server {}:{} error: {}", host, port, err)

Loggers also have XxxxEnabled methods, to avoid unnecessary converting cost:

if logger.DebugEnabled() {
	logger.Debug("server accept connection:", expensiveConvert(conn))
}

Or just use Lazy logger methods:

logger.DebugLazy(func() string {
	return "server accept connection:" +  expensiveConvertToString(conn)
})
Logger Setting

By default, logger only output message with info level or above, using default message format, to standard output. To change this, set custom Appender/Level/Transformer to the logger.

var logger = vlog.CurrentPackageLogger()

func init() {
	appender := vlog.NewConsoleAppender()
	// custom log format
	transformer, _ := vlog.NewPatternTransformer("{time} [{Level}] {file}:{line} - {message}\n")
	appender.SetTransformer(transformer)
	// using custom appender
	logger.SetAppenders(appender)
	// set level to debug, will output all message with level equal or higher than Debug
	logger.SetLevel(vlog.Debug)
}
Log Rotate

If using FileAppender to write log into file, a log rotater can be set to rotate log file, by log file size or time.

// appender without rotater
appender := vlog.NewFileAppender("path/to/logfile", nil)
// appender with rotater rotate log file every 800m
rotater := vlog.NewSizeRotater(800 * 1024*1024, 6)
appender := vlog.NewFileAppender("path/to/logfile", rotater)
// appender with rotater rotate log file every day
rotater := vlog.NewDailyRotater("20060102")
appender := vlog.NewFileAppender("path/to/logfile", rotater)
Override Log Levels

Loggers' level can be set by one environ: VLOG_LEVEL. The level set by environ will override the level set in code. So you can set logger by code in your final or in your lib in development, when final routine is deployed, you can set the environ meet your real need.

For example, run program in linux shell, you can set as follows:

export VLOG_LEVEL="package1=Warn;github.com/user1=Debug"

If use package path as logger name, vlog will match the setting by prefix. It means github.com/user1=Debug will take effect for logger with name github.com/user1/lib.

Appendix

Appenders
Appender Type Create by Code
ConsoleAppender NewConsoleAppender
ConsoleAppender NewConsole2Appender
FileAppender NewFileAppender
SyslogAppender SyslogAppender
NopAppender NewNopAppender
Rotaters
Rotater Type Create by Code
TimeRotater NewDailyRotater
TimeRotater NewHourlyRotater
TimeRotater NewTimeRotater
SizeRotater NewSizeRotater
Transformers
Transformer Type Create by Code
PatternTransformer NewPatternTransformer

Below variables can be used in PatternTransformer format string:

  • {file} filename
  • {package} package name
  • {line} line number
  • {function} function name
  • {time} time
  • {logger} the logger name
  • {Level}/{level}/{LEVEL} the logger level, with different character case
  • {message} the log message

Use {{ to escape {, use }} to escape }

{time} can set custom format via filter, by {time|2006-01-02 15:04:05.000}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AppendEvent added in v0.5.1

type AppendEvent struct {
	LoggerName string
	Level      Level
	Message    string // the logger message
}

AppendEvent is a log event passed to Appender

type Appender

type Appender interface {
	// Append append new data to destination. name is the name of logger, level is the level of logger
	Append(event AppendEvent) error
	// get the transformer of this appender
	Transformer() Transformer
	// set transformer to this appender
	SetTransformer(transformer Transformer)
}

Appender write the log to one destination, and can provider a transformer to convert the log message to desired data. Appender Should be reused across loggers.

func DefaultAppender

func DefaultAppender() Appender

DefaultAppender return the default appender all logger use

func NewSyslogAppenderToAddress added in v0.2.0

func NewSyslogAppenderToAddress(network string, address string, tag string) (Appender, error)

NewSyslogAppenderToAddress create syslog appender, to a log daemon connected by network address.

type BytesAppender

type BytesAppender struct {
	*CanFormattedMixin
	// contains filtered or unexported fields
}

BytesAppender write log into memory

func NewBytesAppender

func NewBytesAppender() *BytesAppender

NewBytesAppender create BytesAppender

func (*BytesAppender) Append

func (b *BytesAppender) Append(event AppendEvent) error

Append write log data to byte buffer

type CanFormattedMixin

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

CanFormattedMixin used for impl Appender Transformer/Name... methods

func NewAppenderMixin

func NewAppenderMixin() *CanFormattedMixin

NewAppenderMixin create new CanFormattedMixin

func (*CanFormattedMixin) SetTransformer

func (am *CanFormattedMixin) SetTransformer(transformer Transformer)

SetTransformer set transformer to this appender. This method is thread-safe

func (*CanFormattedMixin) Transformer

func (am *CanFormattedMixin) Transformer() Transformer

Transformer return the transformer of this appender. This method is thread-safe

type ConsoleAppender

type ConsoleAppender struct {
	*CanFormattedMixin
	// contains filtered or unexported fields
}

ConsoleAppender appender write log to stdout

func NewConsole2Appender

func NewConsole2Appender() *ConsoleAppender

NewConsole2Appender create console appender, which write log to stderr

func NewConsoleAppender

func NewConsoleAppender() *ConsoleAppender

NewConsoleAppender create console appender, which write log to stdout

func (*ConsoleAppender) Append

func (ca *ConsoleAppender) Append(event AppendEvent) error

Append log to stdout

type FileAppender

type FileAppender struct {
	*CanFormattedMixin
	// contains filtered or unexported fields
}

FileAppender appender that write log to local file

func NewFileAppender

func NewFileAppender(path string, rotater Rotater) (*FileAppender, error)

NewFileAppender create new file appender. path is the base path and filename of log file. appender can be nil, then the file would not be rotated.

func (*FileAppender) Append

func (f *FileAppender) Append(event AppendEvent) error

Append append new log to file

type Level

type Level int32

Level the logger level

const (
	Trace        Level = 10
	Debug        Level = 20
	Info         Level = 30
	Warn         Level = 40
	Error        Level = 50
	Critical     Level = 60
	Off          Level = 70
	DefaultLevel Level = Info
)

log levels

func (Level) Name

func (l Level) Name() string

Name return the name of level, using captical form

type LogRecord added in v0.5.1

type LogRecord struct {
	LoggerName string    // logger name
	Level      Level     // the level of this logger record
	LogTime    time.Time // Time
	Message    string    // the log message
}

LogRecord is one log message

type Logger

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

Logger the logger

func CurrentPackageLogger

func CurrentPackageLogger() *Logger

CurrentPackageLogger return the log of current package, use package name as logger name

func GetLogger

func GetLogger(name string) *Logger

GetLogger return the logger with name

func (*Logger) AddAppenders added in v0.3.0

func (l *Logger) AddAppenders(appenders ...Appender)

AddAppenders add one new appender to logger

func (*Logger) Appenders

func (l *Logger) Appenders() []Appender

Appenders return the appenders this logger have

func (*Logger) Critical

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

Critical log message with critical level

func (*Logger) CriticalEnabled added in v0.4.0

func (l *Logger) CriticalEnabled() bool

CriticalEnabled if this logger log critical message

func (*Logger) CriticalFormat added in v0.5.1

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

CriticalFormat log message with critical level

func (*Logger) CriticalLazy added in v0.5.1

func (l *Logger) CriticalLazy(f func() string)

CriticalLazy log message with critical level, and call func to get log message only when log is performed.

func (*Logger) Debug

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

Debug log message with debug level

func (*Logger) DebugEnabled added in v0.4.0

func (l *Logger) DebugEnabled() bool

DebugEnabled if this logger log debug message

func (*Logger) DebugFormat added in v0.5.1

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

DebugFormat log message with debug level

func (*Logger) DebugLazy added in v0.5.1

func (l *Logger) DebugLazy(f func() string)

DebugLazy log message with debug level, and call func to get log message only when log is performed.

func (*Logger) Error

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

log message with error level

func (*Logger) ErrorEnabled added in v0.4.0

func (l *Logger) ErrorEnabled() bool

ErrorEnabled if this logger log error message

func (*Logger) ErrorFormat added in v0.5.1

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

ErrorFormat message with error level

func (*Logger) ErrorLazy added in v0.5.1

func (l *Logger) ErrorLazy(f func() string)

ErrorLazy log message with error level, and call func to get log message only when log is performed.

func (*Logger) Info

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

Info log message with info level

func (*Logger) InfoEnabled added in v0.4.0

func (l *Logger) InfoEnabled() bool

InfoEnabled if this logger log info message

func (*Logger) InfoFormat added in v0.5.1

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

InfoFormat log message with info level

func (*Logger) InfoLazy added in v0.5.1

func (l *Logger) InfoLazy(f func() string)

InfoLazy log message with info level, and call func to get log message only when log is performed.

func (*Logger) Level

func (l *Logger) Level() Level

Level current level of this logger

func (*Logger) Name

func (l *Logger) Name() string

Name the name of this logger

func (*Logger) SetAppenders

func (l *Logger) SetAppenders(appenders ...Appender)

SetAppenders set one or multi appenders for this logger

func (*Logger) SetLevel

func (l *Logger) SetLevel(level Level)

SetLevel set new Level to this logger. the default log level is Debug

func (*Logger) SetTransformerForAppenders added in v0.1.1

func (l *Logger) SetTransformerForAppenders(transformer Transformer)

SetTransformerForAppenders set transformer, apply to all appenders the logger current have

func (*Logger) Trace

func (l *Logger) Trace(firstArg interface{}, args ...interface{})

Trace log message with trace level

func (*Logger) TraceEnabled added in v0.4.0

func (l *Logger) TraceEnabled() bool

TraceEnabled if this logger log trace message

func (*Logger) TraceFormat added in v0.5.1

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

TraceFormat log message with trace level

func (*Logger) TraceLazy added in v0.5.1

func (l *Logger) TraceLazy(f func() string)

TraceLazy log message with trace level, and call func to get log message only when log is performed.

func (*Logger) Warn

func (l *Logger) Warn(firstArg interface{}, args ...interface{})

Warn log message with warn level

func (*Logger) WarnEnabled added in v0.4.0

func (l *Logger) WarnEnabled() bool

WarnEnabled if this logger log warn level message

func (*Logger) WarnFormat added in v0.5.1

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

WarnFormat log message with warn level

func (*Logger) WarnLazy added in v0.5.1

func (l *Logger) WarnLazy(f func() string)

WarnLazy log message with warn level, and call func to get log message only when log is performed.

type LoggerCache

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

LoggerCache contains loggers with name as key

func (*LoggerCache) Load

func (lc *LoggerCache) Load(name string) *Logger

Load return logger for with name, using cached one or create new one if logger with name not exist

type NopAppender

type NopAppender struct {
	*CanFormattedMixin
}

NopAppender discard all logs

func NewNopAppender

func NewNopAppender() *NopAppender

NewNopAppender create nop appender

func (NopAppender) Append

func (NopAppender) Append(event AppendEvent) error

Append silently discard log data

type PatternTransformer

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

PatternTransformer transform one log record using pattern, to string

func MustNewPatternTransformer added in v0.3.0

func MustNewPatternTransformer(pattern string) *PatternTransformer

MustNewPatternTransformer create new pattern transformer, just as NewPatternTransformer do. But when an error occurred, MustNewPatternTransformer panic while NewPatternTransformer return the error.

func NewDefaultPatternTransformer

func NewDefaultPatternTransformer() *PatternTransformer

NewDefaultPatternTransformer return formatter with default format

func NewPatternTransformer

func NewPatternTransformer(pattern string) (*PatternTransformer, error)

NewPatternTransformer create new pattern transformer below variables can be used in format string: {file} filename {package} package name {line} line number {function} function name {time} time {logger} the logger name {Level}/{level}/{LEVEL} the logger level, with different character case {message} the log message use {{ to escape {, use }} to escape } {time} can set custom format via filter, by {time|2006-01-02 15:04:05.000}

func (*PatternTransformer) Transform

func (f *PatternTransformer) Transform(record LogRecord) AppendEvent

Transform format log data to byte array data

type Rotater

type Rotater interface {

	// call this to determine if should do rotate.
	// timestamp is the time the last log logged;
	// bytes is the data size logged since last call to this method;
	// records is new log num since last call to this method;
	Check(timestamp time.Time, bytes int, records int) (shouldRotate bool, suffixName string)
	// contains filtered or unexported methods
}

Rotater interface for log rotate

func NewDailyRotater

func NewDailyRotater(pattern string) Rotater

NewDailyRotater create rotater rotate log every day

func NewHourlyRotater

func NewHourlyRotater(pattern string) Rotater

NewHourlyRotater create rotater rotate log every hour

func NewSizeRotater

func NewSizeRotater(rotateSize int64, suffixWidth int) Rotater

NewSizeRotater create file size rotater, rotate log file when file size larger than rotateSize, in bytes

func NewTimeRotater

func NewTimeRotater(duration time.Duration, suffixFormat string) Rotater

NewTimeRotater create rotater rotate log by time

type SizeRotater

type SizeRotater struct {
	SuffixWidth int
	// contains filtered or unexported fields
}

SizeRotater rotate based on file size

func (*SizeRotater) Check

func (sr *SizeRotater) Check(timestamp time.Time, bytes int, records int) (shouldRotate bool, suffixName string)

Check if should rotate now

type SyslogAppender added in v0.2.0

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

SyslogAppender write log to syslogd, using go syslog package. This appender always send only raw log message, SyslogAppender will not take effect.

SyslogAppender will map log levels from vlog to syslog by the following rules: TRACE -- LOG_DEBUG DEBUG -- LOG_DEBUG INFO -- LOG_INFO WARN -- LOG_WARNING ERROR -- LOG_ERR CRITICAL -- LOG_CRIT

func NewSyslogAppender added in v0.2.0

func NewSyslogAppender(tag string) (*SyslogAppender, error)

NewSyslogAppender create syslog appender, to system syslog daemon.

func (*SyslogAppender) Append added in v0.2.0

func (sa *SyslogAppender) Append(event AppendEvent) error

Append write one log entry to syslog

func (*SyslogAppender) Close added in v0.2.0

func (sa *SyslogAppender) Close() error

Close the syslog connection

func (*SyslogAppender) SetLevelMap added in v0.2.0

func (sa *SyslogAppender) SetLevelMap(levelMap map[Level]syslog.Priority)

SetLevelMap set level map from vlog to syslog, replace the default log level map. This method should be called before appender start to work.

func (*SyslogAppender) SetTransformer added in v0.2.0

func (sa *SyslogAppender) SetTransformer(transformer Transformer)

SetTransformer not take effect for SyslogAppender, which always only send log message

func (*SyslogAppender) Transformer added in v0.2.0

func (sa *SyslogAppender) Transformer() Transformer

Transformer always return the default, non-

type TimeRotater

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

TimeRotater rotate log file by time

func (*TimeRotater) Check

func (t *TimeRotater) Check(timestamp time.Time, bytes int, records int) (shouldRotate bool, suffixName string)

Check if should rotate now

type Transformer

type Transformer interface {
	Transform(record LogRecord) AppendEvent
}

Transformer convert one log record to byte array data. Transformer should can be share across goroutines, and user Should always reuse transformers.

func DefaultTransformer

func DefaultTransformer() Transformer

DefaultTransformer the default transformer used if not set

Jump to

Keyboard shortcuts

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