slog

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Mar 3, 2023 License: MIT Imports: 12 Imported by: 1

README

golog

GoDoc Build Status Go Report Card

Features

  1. Unstructured
  2. Leveled
  3. Customizable output layout
  4. Rotating by size, date or hour
  5. Cross platform, tested on Linux, macOS and Windows
  6. No 3rd party dependancy
  7. Fast

Installation

go get -u github.com/keakon/golog

Benchmarks

BenchmarkBufferedFileLogger-8   	 5000000	       294 ns/op	       0 B/op	       0 allocs/op
BenchmarkDiscardLogger-8        	 5000000	       254 ns/op	       0 B/op	       0 allocs/op
BenchmarkNopLog-8               	2000000000	         0.45 ns/op	       0 B/op	       0 allocs/op
BenchmarkMultiLevels-8           	 2000000	      1000 ns/op	       0 B/op	       0 allocs/op

Example output of the benchmarks:

[I 2018-11-20 17:05:37 log_test:118] test

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// DefaultFormatter is the default formatter
	DefaultFormatter = ParseFormat("%D %T %l %m")
	// TimedRotatingFormatter is a formatter for TimedRotatingFileWriter
	TimedRotatingFormatter = ParseFormat("[%l %T] %m")
)
View Source
var Crit func(args ...interface{})

Crit logs a _critical level message. It uses fmt.Fprint() to format args.

View Source
var Critf func(msg string, args ...interface{})

Critf logs a _critical level message. It uses fmt.Fprintf() to format msg and args.

View Source
var Debug func(args ...interface{})

Debug logs a _debug level message. It uses fmt.Fprint() to format args.

View Source
var Debugf func(msg string, args ...interface{})

Debugf logs a _debug level message. It uses fmt.Fprintf() to format msg and args.

View Source
var Error func(args ...interface{})

Error logs an _error level message. It uses fmt.Fprint() to format args.

View Source
var Errorf func(msg string, args ...interface{})

Errorf logs a _error level message. It uses fmt.Fprintf() to format msg and args.

View Source
var Info func(args ...interface{})

Info logs a _info level message. It uses fmt.Fprint() to format args.

View Source
var Infof func(msg string, args ...interface{})

Infof logs a _info level message. It uses fmt.Fprintf() to format msg and args.

View Source
var (
	//StampNano = "15:04:05.000000000+07:00"
	StampNano = "15:04:05.000000Z0700"
)
View Source
var Warn func(args ...interface{})

Warn logs a _warning level message. It uses fmt.Fprint() to format args.

View Source
var Warnf func(msg string, args ...interface{})

Warnf logs a _warning level message. It uses fmt.Fprintf() to format msg and args.

Functions

func NewFileWriter

func NewFileWriter(path string) (*os.File, error)

NewFileWriter creates a FileWriter by its path.

func SetDefaultLogger

func SetDefaultLogger(l *Logger)

SetDefaultLogger set the logger as the defaultLogger. The logging functions in this package use it as their logger. This function should be called before using the others.

func SetInternalLogger

func SetInternalLogger(l *Logger)

SetInternalLogger sets a logger as the internalLogger which is used to log internal errors. The logger and its handlers will be marked as internal, so do not reuse them. The internalLogger may discard its own errors to prevent recursive log.

Types

type BufferedFileWriter

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

A BufferedFileWriter is a buffered file writer. The written bytes will be flushed to the log file every 0.1 second, or when reaching the buffer capacity (4 MB).

func NewBufferedFileWriter

func NewBufferedFileWriter(path string) (*BufferedFileWriter, error)

NewBufferedFileWriter creates a new BufferedFileWriter.

func (*BufferedFileWriter) Close

func (w *BufferedFileWriter) Close() error

Close flushes the buffer, then closes the file writer.

func (*BufferedFileWriter) Write

func (w *BufferedFileWriter) Write(p []byte) (n int, err error)

Write writes a byte slice to the buffer.

type ByteFormatPart

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

ByteFormatPart is a FormatPart containing a byte.

func (*ByteFormatPart) Format

func (p *ByteFormatPart) Format(r *Record, buf *bytes.Buffer)

Format writes its byte to the buf.

type BytesFormatPart

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

BytesFormatPart is a FormatPart containing a byte slice.

func (*BytesFormatPart) Format

func (p *BytesFormatPart) Format(r *Record, buf *bytes.Buffer)

Format writes its bytes to the buf.

type ConsoleWriter

type ConsoleWriter struct {
	*os.File // faster than io.Writer
}

A ConsoleWriter is a writer which should not be acturelly closed.

func NewConsoleWriter

func NewConsoleWriter(f *os.File) *ConsoleWriter

NewConsoleWriter creates a new ConsoleWriter.

func NewStderrWriter

func NewStderrWriter() *ConsoleWriter

NewStderrWriter creates a new stderr writer.

func NewStdoutWriter

func NewStdoutWriter() *ConsoleWriter

NewStdoutWriter creates a new stdout writer.

func (*ConsoleWriter) Close

func (w *ConsoleWriter) Close() error

Close sets its File to nil.

type DateFormatPart

type DateFormatPart struct{}

DateFormatPart is a FormatPart of the date placeholder.

func (*DateFormatPart) Format

func (p *DateFormatPart) Format(r *Record, buf *bytes.Buffer)

Format writes the date string of the record to the buf.

type DiscardWriter

type DiscardWriter struct {
	io.Writer
}

DiscardWriter is a WriteCloser which write everything to devNull

func NewDiscardWriter

func NewDiscardWriter() *DiscardWriter

NewDiscardWriter creates a new ConsoleWriter.

func (*DiscardWriter) Close

func (w *DiscardWriter) Close() error

Close sets its Writer to nil.

type FormatPart

type FormatPart interface {
	Format(r *Record, buf *bytes.Buffer)
}

FormatPart is an interface containing the Format() method.

type Formatter

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

A Formatter containing a sequence of FormatParts.

func ParseFormat

func ParseFormat(format string) (formatter *Formatter)

ParseFormat parses a format string into a formatter.

func (*Formatter) Format

func (f *Formatter) Format(r *Record, buf *bytes.Buffer)

Format formats a record to a bytes.Buffer. Supported format verbs:

%%: %
%l: short name of the level
%T: time string (HH:MM:SS)
%D: date string (YYYY-mm-DD)
%s: source code string (filename:line)
%S: full source code string (/path/filename.go:line)

type Handler

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

A Handler is a leveled log handler with a formatter and several writers.

func NewHandler

func NewHandler(level Level, formatter *Formatter) *Handler

NewHandler creates a new Handler of the given level with the formatter. Records with the lower level than the handler will be ignored.

func (*Handler) AddWriter

func (h *Handler) AddWriter(w io.WriteCloser)

AddWriter adds a writer to the Handler. The Write() method of the writer should be thread-safe.

func (*Handler) Close

func (h *Handler) Close()

Close closes all its writers. It's safe to call this method more than once, but it's unsafe to call its writers' Close() more than once.

func (*Handler) Handle

func (h *Handler) Handle(r *Record) bool

Handle formats a record using its formatter, then writes the formatted result to all of its writers. Returns true if it can handle the record. The errors during writing will be logged by the internalLogger. It's not thread-safe, concurrent record may be written in a random order through different writers. But two records won't be mixed in a single line.

type Level

type Level uint8

Level specifies the log level.

const (
	DebugLevel Level = iota
	InfoLevel
	WarnLevel
	ErrorLevel
	CritLevel
)

All the log levels.

type LevelFormatPart

type LevelFormatPart struct{}

LevelFormatPart is a FormatPart of the level placeholder.

func (*LevelFormatPart) Format

func (p *LevelFormatPart) Format(r *Record, buf *bytes.Buffer)

Format writes the short level name of the record to the buf.

type Logger

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

A Logger is a leveled logger with several handlers.

func NewLogger

func NewLogger(lv Level) *Logger

NewLogger creates a new Logger of the given level. Messages with lower level than the logger will be ignored.

func NewLoggerWithWriter

func NewLoggerWithWriter(w io.WriteCloser) *Logger

NewLoggerWithWriter creates an info level logger with a writer.

func NewStderrLogger

func NewStderrLogger() *Logger

NewStderrLogger creates a logger with a stderr writer.

func NewStdoutLogger

func NewStdoutLogger() *Logger

NewStdoutLogger creates a logger with a stdout writer.

func (*Logger) AddHandler

func (l *Logger) AddHandler(h *Handler)

AddHandler adds a Handler to the Logger. A handler with lower level than the logger will be ignored.

func (*Logger) Close

func (l *Logger) Close()

Close closes its handlers. It's safe to call this method more than once.

func (*Logger) Crit

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

Crit logs a critical level message. It uses fmt.Fprint() to format args.

func (*Logger) Critf

func (l *Logger) Critf(msg string, args ...interface{})

Critf logs a critical level message. It uses fmt.Fprintf() to format msg and args.

func (*Logger) Debug

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

Debug logs a debug level message. It uses fmt.Fprint() to format args.

func (*Logger) Debugf

func (l *Logger) Debugf(msg string, args ...interface{})

Debugf logs a debug level message. It uses fmt.Fprintf() to format msg and args.

func (*Logger) Error

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

Error logs an error level message. It uses fmt.Fprint() to format args.

func (*Logger) Errorf

func (l *Logger) Errorf(msg string, args ...interface{})

Errorf logs a error level message. It uses fmt.Fprintf() to format msg and args.

func (*Logger) GetMinLevel

func (l *Logger) GetMinLevel() Level

GetMinLevel returns its minLevel. Records lower than its minLevel will be ignored.

func (*Logger) Info

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

Info logs a info level message. It uses fmt.Fprint() to format args.

func (*Logger) Infof

func (l *Logger) Infof(msg string, args ...interface{})

Infof logs a info level message. It uses fmt.Fprintf() to format msg and args.

func (*Logger) IsEnabledFor

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

IsEnabledFor returns whether it's enabled for the level

func (*Logger) Log

func (l *Logger) Log(lv Level, msg string, args ...interface{})

Log logs a message with context. A logger should check the message level before call its Log(). The line param should be uint32. It's not thread-safe, concurrent messages may be written in a random order through different handlers or writers. But two messages won't be mixed in a single line.

func (*Logger) Warn

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

Warn logs a warning level message. It uses fmt.Fprint() to format args.

func (*Logger) Warnf

func (l *Logger) Warnf(msg string, args ...interface{})

Warnf logs a warning level message. It uses fmt.Fprintf() to format msg and args.

type MessageFormatPart

type MessageFormatPart struct{}

MessageFormatPart is a FormatPart of the message placeholder.

func (*MessageFormatPart) Format

func (p *MessageFormatPart) Format(r *Record, buf *bytes.Buffer)

Format writes the formatted message with args to the buf.

type Record

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

A Record is an item which contains required context for the logger.

type RotateDuration

type RotateDuration uint8

RotateDuration specifies rotate duration type, should be either RotateByDate or RotateByHour.

const (
	// RotateByDate set the log file to be rotated each day.
	RotateByDate RotateDuration = iota
	// RotateByHour set the log file to be rotated each hour.
	RotateByHour
)

type RotatingFileWriter

type RotatingFileWriter struct {
	BufferedFileWriter
	// contains filtered or unexported fields
}

A RotatingFileWriter is a buffered file writer which will rotate before reaching its maxSize. An exception is when a record is larger than maxSize, it won't be separated into 2 files. It keeps at most backupCount backups.

func NewRotatingFileWriter

func NewRotatingFileWriter(path string, maxSize uint64, backupCount uint8) (*RotatingFileWriter, error)

NewRotatingFileWriter creates a new RotatingFileWriter.

func (*RotatingFileWriter) Write

func (w *RotatingFileWriter) Write(p []byte) (n int, err error)

Write writes a byte slice to the buffer and rotates if reaching its maxSize.

type TimeFormatPart

type TimeFormatPart struct{}

TimeFormatPart is a FormatPart of the time placeholder.

func (*TimeFormatPart) Format

func (p *TimeFormatPart) Format(r *Record, buf *bytes.Buffer)

Format writes the time string of the record to the buf.

type TimedRotatingFileWriter

type TimedRotatingFileWriter struct {
	BufferedFileWriter
	// contains filtered or unexported fields
}

A TimedRotatingFileWriter is a buffered file writer which will rotate by time. Its rotateDuration can be either RotateByDate or RotateByHour. It keeps at most backupCount backups.

func NewTimedRotatingFileWriter

func NewTimedRotatingFileWriter(pathPrefix string, rotateDuration RotateDuration, backupCount uint8) (*TimedRotatingFileWriter, error)

NewTimedRotatingFileWriter creates a new TimedRotatingFileWriter.

Jump to

Keyboard shortcuts

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