package module
Version: v1.1.15 Latest Latest

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

Go to latest
Published: Jun 23, 2021 License: MIT Imports: 19 Imported by: 14



License Go Report Card Travis branch GoDoc

log package inspired from golang/glog. We have following key features:

  • dependentless - No any dependencies.
  • lightweight - Lightweight and easy to use.
  • highly customizable - You can customize Writer,Printer.
  • fast - Write logs to a buffer queue.

Getting started

package main

import (

func main() {
	// Start and Shutdown
	log.Start(/* options ... */)
	defer log.Shutdown()

	// Default log level is log.LvINFO, you can change the level as following:
	//	log.SetLevel(log.LvTRACE)
	// 	log.SetLevel(log.LvDEBUG)
	// 	log.SetLevel(log.LvINFO)
	// 	log.SetLevel(log.LvWARN)
	// 	log.SetLevel(log.LvERROR)
	// 	log.SetLevel(log.LvFATAL)

	log.Trace("%s cannot be printed", "TRACE")
	log.Debug("%s cannot be printed", "DEBUG")

	log.Info("%s should be printed", "INFO")
	log.Warn("%s should be printed", "WARN")
	log.Error("%s should be printed", "ERROR")

	log.Fatal("%s should be printed and exit program with status code 1", "FATAL")
	log.Info("You cannot see me")

Log level

There are 6 log levels: Fatal,Error,Warn,Info,Debug,Trace

Default log level is Info if log level isn't specified.

Start options


// WithConsole
func main() {
	defer log.Shutdown()
// WithFile
func main() {
		Dir: "./log",
		Filename: "app.log",
	defer log.Shutdown()
// WithMultiFile
func main() {
		RootDir: "./log",
		Filename: "app.log",
	defer log.Shutdown()
// WithWriters

// coloredConsole implements log.Writer interface
type coloredConsole struct {}

// Write implements log.Writer Write method
func (c coloredConsole) Write(level log.Level, data []byte, headerLen int) error {
	// ...
	return nil

// Close implements log.Writer Close method
func (c coloredConsole) Close() error{
	return nil

func main() {
	// multi-writers supported, e.g.
	// log.Start(log.WithWriters(coloredConsole{}), log.WithFile(...))
	defer log.Shutdown()
	// ...
// WithPrinter

// printer implements log.Printer
type printer struct {}

// ... implements log.Printer methods

func main() {
	// WithPrinter conflicts with WithWriters, and printer should specified once.
	// panics if printer and writers both specified.
	// panics if more than one printer specified.
	defer log.Shutdown()
	// ...
// WithHTTPHandler
func main() {
	defer log.Shutdown()
	// ...
// WithLevel
func main() {
	defer log.Shutdown()
	// ...
// WithPrefix
func main() {
	defer log.Shutdown()
	// ...

Print functions

  • Fatal(format string, args ...interface{})
  • Error(format string, args ...interface{})
  • Warn(format string, args ...interface{})
  • Info(format string, args ...interface{})
  • Debug(format string, args ...interface{})
  • Trace(format string, args ...interface{})





View Source
const (
	Ldatetime     = 1 << iota              // the datetime in the local time zone: 2001/02/03 01:23:23
	Llongfile                              // full file name and line number: /a/b/c/d.go:23
	Lshortfile                             // final file name element and line number: d.go:23. overrides Llongfile
	LUTC                                   // if Ldatetime is set, use UTC rather than the local time zone
	LdefaultFlags = Ldatetime | Lshortfile // default values for the standard logger

These flags define which text to prefix to each log entry generated by the Logger. Bits are or'ed together to control what's printed.


This section is empty.


func GetFlags added in v1.1.11

func GetFlags()

GetFlags returns the flags

func Log added in v1.1.6

func Log(calldepth int, level Level, prefix, format string, args ...interface{})

Log is a low-level API to print logging

func Printf added in v1.0.0

func Printf(level Level, format string, args ...interface{})

Printf wraps the global printer Printf method

func SetFlags added in v1.1.11

func SetFlags(flags int)

SetFlags sets the flags

func SetLevel

func SetLevel(level Level)

SetLevel sets current log level

func Shutdown added in v1.1.0

func Shutdown()

Shutdown shutdowns global printer

func Start added in v1.1.0

func Start(options ...Option) error

Start starts logging with options


type FS added in v1.1.5

type FS interface {
	OpenFile(name string, flag int, perm os.FileMode) (File, error) // OpenFile opens the file
	Remove(name string) error                                       // Remove removes the file
	Symlink(oldname, newname string) error                          // Symlink creates file symlink
	MkdirAll(path string, perm os.FileMode) error                   // MkdirAll creates a directory

FS wraps the basic fs operations for logging

type Fields added in v1.1.5

type Fields struct {
	// contains filtered or unexported fields

Fields holds context fields

package main

import (


type testingLogWriter struct {
	discard bool
	buf     bytes.Buffer

func (w *testingLogWriter) Write(level log.Level, data []byte, headerLen int) error {
	if !w.discard {
		w.buf.WriteByte(' ')
	return nil

func (w *testingLogWriter) Close() error { return nil }

func main() {
	writer := new(testingLogWriter)
	log.Start(log.WithWriters(writer), log.WithLevel(log.LvINFO), log.WithPrefix("testing"))
	log.Info().Int("int", 123456).Print("fields")
	log.Info().Int8("int8", -12).Print("fields")
	log.Info().Int16("int16", 1234).Print("fields")
	log.Info().Int32("int32", -12345678).Print("fields")
	log.Info().Int64("int64", 1234567890).Print("fields")
	log.Info().Uint("uint", 123456).Print("fields")
	log.Info().Uint8("uint8", 120).Print("fields")
	log.Info().Uint16("uint16", 12340).Print("fields")
	log.Info().Uint32("uint32", 123456780).Print("fields")
	log.Info().Uint64("uint64", 12345678900).Print("fields")
	log.Info().Float32("float32", 1234.5678).Print("fields")
	log.Info().Float64("float64", 0.123456789).Print("fields")
	log.Info().Complex64("complex64", 1+2i).Print("fields")
	log.Info().Complex128("complex128", 1).Print("fields")
	log.Info().Complex128("complex128", 2i).Print("fields")
	log.Info().Byte("byte", 'h').Print("fields")
	log.Info().Rune("rune", 'Å').Print("fields")
	log.Info().Bool("bool", true).Print("fields")
	log.Info().Bool("bool", false).Print("fields")
	log.Info().String("string", "hello").Print("fields")
	log.Info().Error("error", nil).Print("fields")
	log.Info().Error("error", errors.New("err")).Print("fields")
	log.Info().Any("any", nil).Print("fields")
	log.Info().Any("any", "nil").Print("fields")
	log.Info().Any("any", struct {
		x int
		y string
	}{1, "hello"}).Print("fields")
	log.Info().Type("type", nil).Print("fields")
	log.Info().Type("type", "string").Print("fields")
	log.Info().Type("type", new(int)).Print("fields")
	const (
		year  = 2020
		month = time.May
		day   = 1
		hour  = 12
		min   = 20
		sec   = 30
		nsec  = 123456789
	t := time.Date(year, month, day, hour, min, sec, nsec, time.Local)
	log.Info().Date("date", t).Print("fields")
	log.Info().Time("time", t).Print("fields")
	log.Info().Duration("duration", time.Millisecond*1200).Print("fields")
	log.Info().String("$name", "hello").Print("fields")
	log.Info().String("name of", "hello").Print("fields")
		String("k1", "v1").
		Int("k2", 2).
		Print("prefix logging")
	log.Debug().String("key", "value").Print("not output")

[INFO] (testing) {int:123456} fields
[INFO] (testing) {int8:-12} fields
[INFO] (testing) {int16:1234} fields
[INFO] (testing) {int32:-12345678} fields
[INFO] (testing) {int64:1234567890} fields
[INFO] (testing) {uint:123456} fields
[INFO] (testing) {uint8:120} fields
[INFO] (testing) {uint16:12340} fields
[INFO] (testing) {uint32:123456780} fields
[INFO] (testing) {uint64:12345678900} fields
[INFO] (testing) {float32:1234.5677} fields
[INFO] (testing) {float64:0.123456789} fields
[INFO] (testing) {complex64:1+2i} fields
[INFO] (testing) {complex128:1} fields
[INFO] (testing) {complex128:2i} fields
[INFO] (testing) {byte:'h'} fields
[INFO] (testing) {rune:'Å'} fields
[INFO] (testing) {bool:true} fields
[INFO] (testing) {bool:false} fields
[INFO] (testing) {string:"hello"} fields
[INFO] (testing) {error:nil} fields
[INFO] (testing) {error:"err"} fields
[INFO] (testing) {any:nil} fields
[INFO] (testing) {any:"nil"} fields
[INFO] (testing) {any:"{1 hello}"} fields
[INFO] (testing) {type:"nil"} fields
[INFO] (testing) {type:"string"} fields
[INFO] (testing) {type:"*int"} fields
[INFO] (testing) {date:2020-05-01+08:00} fields
[INFO] (testing) {time:2020-05-01T12:20:30.123456789+08:00} fields
[INFO] (testing) {duration:1.2s} fields
[INFO] (testing) {$name:"hello"} fields
[INFO] (testing) {"name of":"hello"} fields
[INFO] (testing/prefix) {k1:"v1" k2:2} prefix logging

func Debug

func Debug() *Fields

Debug creates a context fields with level debug

func Error

func Error() *Fields

Error creates a context fields with level error

func Fatal

func Fatal() *Fields

Fatal creates a context fields with level fatal

func Info

func Info() *Fields

Info creates a context fields with level info

func Trace

func Trace() *Fields

Trace creates a context fields with level trace

func Warn

func Warn() *Fields

Warn creates a context fields with level warn

func (*Fields) Any added in v1.1.7

func (fields *Fields) Any(key string, value interface{}) *Fields

func (*Fields) Bool added in v1.1.5

func (fields *Fields) Bool(key string, value bool) *Fields

func (*Fields) Byte added in v1.1.5

func (fields *Fields) Byte(key string, value byte) *Fields

func (*Fields) Complex128 added in v1.1.14

func (fields *Fields) Complex128(key string, value complex128) *Fields

func (*Fields) Complex64 added in v1.1.14

func (fields *Fields) Complex64(key string, value complex64) *Fields

func (*Fields) Date added in v1.1.14

func (fields *Fields) Date(key string, value time.Time) *Fields

func (*Fields) Duration added in v1.1.9

func (fields *Fields) Duration(key string, value time.Duration) *Fields

func (*Fields) Error added in v1.1.7

func (fields *Fields) Error(key string, value error) *Fields

func (*Fields) Exec added in v1.1.9

func (fields *Fields) Exec(key string, stringer func() string) *Fields

func (*Fields) Float32 added in v1.1.5

func (fields *Fields) Float32(key string, value float32) *Fields

func (*Fields) Float64 added in v1.1.5

func (fields *Fields) Float64(key string, value float64) *Fields

func (*Fields) Int added in v1.1.5

func (fields *Fields) Int(key string, value int) *Fields

func (*Fields) Int16 added in v1.1.5

func (fields *Fields) Int16(key string, value int16) *Fields

func (*Fields) Int32 added in v1.1.5

func (fields *Fields) Int32(key string, value int32) *Fields

func (*Fields) Int64 added in v1.1.5

func (fields *Fields) Int64(key string, value int64) *Fields

func (*Fields) Int8 added in v1.1.5

func (fields *Fields) Int8(key string, value int8) *Fields

func (*Fields) Microseconds added in v1.1.14

func (fields *Fields) Microseconds(key string, value time.Time) *Fields

func (*Fields) Milliseconds added in v1.1.14

func (fields *Fields) Milliseconds(key string, value time.Time) *Fields

func (*Fields) Print added in v1.1.8

func (fields *Fields) Print(s string)

Print prints logging with context fields. After this call, the fields not available.

func (*Fields) Rune added in v1.1.5

func (fields *Fields) Rune(key string, value rune) *Fields

func (*Fields) Seconds added in v1.1.14

func (fields *Fields) Seconds(key string, value time.Time) *Fields

func (*Fields) String added in v1.1.5

func (fields *Fields) String(key string, value string) *Fields

func (*Fields) Time added in v1.1.9

func (fields *Fields) Time(key string, value time.Time) *Fields

func (*Fields) Type added in v1.1.7

func (fields *Fields) Type(key string, value interface{}) *Fields

func (*Fields) Uint added in v1.1.5

func (fields *Fields) Uint(key string, value uint) *Fields

func (*Fields) Uint16 added in v1.1.5

func (fields *Fields) Uint16(key string, value uint16) *Fields

func (*Fields) Uint32 added in v1.1.5

func (fields *Fields) Uint32(key string, value uint32) *Fields

func (*Fields) Uint64 added in v1.1.5

func (fields *Fields) Uint64(key string, value uint64) *Fields

func (*Fields) Uint8 added in v1.1.5

func (fields *Fields) Uint8(key string, value uint8) *Fields

type File added in v1.1.4

type File interface {
	// Sync commits the current contents of the file to stable storage.
	// Typically, this means flushing the file system's in-memory copy
	// of recently written data to disk.
	Sync() error

File contains the basic writable file operations for logging

type FileHeader added in v1.1.0

type FileHeader int

FileHeader represents header type of file

const (
	NoHeader   FileHeader = 0 // no header in file
	HTMLHeader FileHeader = 1 // append html header in file

FileHeader constants

type FileOptions added in v1.1.0

type FileOptions struct {
	Dir          string     `json:"dir"`          // log directory (default: .)
	Filename     string     `json:"filename"`     // log filename (default: <appName>.log)
	SymlinkedDir string     `json:"symlinkeddir"` // symlinked directory is symlink enabled (default: symlinked)
	NoSymlink    bool       `json:"nosymlink"`    // doesn't create symlink to latest log file (default: false)
	MaxSize      int        `json:"maxsize"`      // max bytes number of every log file(default: 64M)
	Rotate       bool       `json:"rotate"`       // enable log rotate (default: no)
	Suffix       string     `json:"suffix"`       // filename suffixa(default: .log)
	DateFormat   string     `json:"dateformat"`   // date format string for filename (default: %04d%02d%02d)
	Header       FileHeader `json:"header"`       // header type of file (default: NoHeader)

	FS FS `json:"-"` // custom filesystem (default: stdFS)

FileOptions represents options of file writer

type Level added in v1.1.0

type Level int32

Level represents log level

const (
	LvFATAL Level // 1
	LvERROR       // 2
	LvWARN        // 3
	LvINFO        // 4
	LvDEBUG       // 5
	LvTRACE       // 6


Level constants

func GetLevel

func GetLevel() Level

GetLevel returns current log level

func ParseLevel

func ParseLevel(s string) (lv Level, ok bool)

ParseLevel parses log level from string

func (Level) Literal added in v1.1.0

func (level Level) Literal() string

Literal returns literal value which is a number

func (Level) MarshalJSON added in v1.1.0

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

MarshalJSON implements json.Marshaler

func (Level) MoreVerboseThan added in v1.1.0

func (level Level) MoreVerboseThan(other Level) bool

MoreVerboseThan returns whether level more verbose than other

func (*Level) Set added in v1.1.0

func (level *Level) Set(s string) error

Set implements flag.Value interface such that you can use level as a command as following:

var level logger.Level
flag.Var(&level, "log_level", "log level: trace/debug/info/warn/error/fatal")

func (Level) String added in v1.1.0

func (level Level) String() string

String returns a serialized string of level

func (*Level) UnmarshalJSON added in v1.1.0

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

UnmarshalJSON implements json.Unmarshaler

type MultiFileOptions added in v1.1.0

type MultiFileOptions struct {
	FatalDir string `json:"fataldir"` // fatal subdirectory (default: fatal)
	ErrorDir string `json:"errordir"` // error subdirectory (default: error)
	WarnDir  string `json:"warndir"`  // warn subdirectory (default: warn)
	InfoDir  string `json:"infodir"`  // info subdirectory (default: info)
	DebugDir string `json:"debugdir"` // debug subdirectory (default: debug)
	TraceDir string `json:"tracedir"` // trace subdirectory (default: trace)

MultiFileOptions represents options for multi file writer

type Option added in v1.1.0

type Option func(*startOptions)

Option is option for Start

func WithConsole added in v1.1.15

func WithConsole() Option

WithConsole appends a console writer

func WithFile added in v1.1.0

func WithFile(fileOptions FileOptions) Option

WithFile appends a file writer

func WithFlags added in v1.1.11

func WithFlags(flags int) Option

WithFlags enable or disable flags information

func WithHTTPHandler added in v1.1.0

func WithHTTPHandler(yes bool) Option

WithHTTPHandler enable or disable http handler for settting level

func WithLevel added in v1.1.0

func WithLevel(level Level) Option

WithLevel sets log level

func WithMultiFile added in v1.1.0

func WithMultiFile(multiFileOptions MultiFileOptions) Option

WithMultiFile appends a multifile writer

func WithOutput added in v1.1.15

func WithOutput(w io.Writer) Option

WithOutput appends a console writer with specified io.Writer

func WithPrefix added in v1.1.0

func WithPrefix(prefix string) Option

WithPrefix set log prefix

func WithPrinter added in v1.1.0

func WithPrinter(printer Printer) Option

WithPrinter specify custom printer

func WithSync added in v1.1.0

func WithSync(yes bool) Option

WithSync synchronize outputs log or not

func WithWriters added in v1.1.4

func WithWriters(writers ...Writer) Option

WithWriters appends the writers

type Prefix added in v1.1.6

type Prefix string

Prefix wraps a string as a prefixed logger

func (Prefix) Debug added in v1.1.6

func (p Prefix) Debug() *Fields

Debug creates a context fields with level debug

func (Prefix) Error added in v1.1.6

func (p Prefix) Error() *Fields

Error creates a context fields with level error

func (Prefix) Fatal added in v1.1.6

func (p Prefix) Fatal() *Fields

Fatal creates a context fields with level fatal

func (Prefix) Info added in v1.1.6

func (p Prefix) Info() *Fields

Info creates a context fields with level info

func (Prefix) Prefix added in v1.1.13

func (p Prefix) Prefix(prefix string) Prefix

Prefix appends a prefix to current prefix

func (Prefix) Printf added in v1.1.6

func (p Prefix) Printf(level Level, format string, args ...interface{})

Printf wraps the global printer Printf method

func (Prefix) Trace added in v1.1.6

func (p Prefix) Trace() *Fields

Trace creates a context fields with level trace

func (Prefix) Warn added in v1.1.6

func (p Prefix) Warn() *Fields

Warn creates a context fields with level warn

type Printer added in v1.1.0

type Printer interface {
	// Start starts the printer
	// Quit quits the printer
	// Flush flushs all queued logs
	// GetFlags returns the flags
	GetFlags() int
	// SetFlags sets the flags
	SetFlags(flags int)
	// GetLevel returns log level
	GetLevel() Level
	// SetLevel sets log level
	// SetPrefix sets log prefix
	// Printf outputs leveled logs with specified calldepth and extra prefix
	Printf(calldepth int, level Level, prefix, format string, args ...interface{})

Printer represents the printer for logging

type Writer added in v1.1.0

type Writer interface {
	Write(level Level, data []byte, headerLen int) error
	Close() error

Writer represents a writer for logging

Jump to

Keyboard shortcuts

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