log

package module
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Jun 29, 2021 License: MIT Imports: 18 Imported by: 26

README

LOG

log is a structured logger library. We have following key features:

  • lightweight: no any dependencies.
  • fast: formmating log message very fast.
  • zero-memory: zero memory allocation while formmating log message.
  • customizable: customize Writer and Printer.

Getting started

Install:

go get github.com/gopherd/log
package main

import (
	"errors"
	"time"

	"github.com/gopherd/log"
)

func main() {
	// Start and defer Shutdown
	if err := log.Start(log.WithConsole()); err != nil {
		panic(err)
	}
	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.SetLevel(log.LvTRACE)

	log.Trace().Print("verbose message")
	log.Debug().
		Int("id", 123).
		String("name", "gopherd").
		Print("debug message")

	log.Info().
		Int32("i32", -12).
		Print("important message")
	log.Warn().
		Duration("duration", time.Second).
		Print("warning: cost to much time")
	log.Error().
		Error("error", errors.New("EOF")).
		Print("something is wrong")

	// Set header flags, all supported flags: Ldatetime, Llongfile, Lshortfile, LUTC
	log.SetFlags(log.Ldatetime | log.Lshortfile | log.LUTC)

	log.Fatal().Print("should be printed and exit program with status code 1")
	log.Info().Print("You cannot see me")
}

Linter: loglint

install loglint:

go install github.com/gopherd/log/cmd/loglint

loglint used to check unfinished chain calls, e.g.

// wrong
log.Debug()                              // warning: result of github.com/gopherd/log.Debug call not used
log.Prefix("pre").Trace()                // warning: result of (github.com/gopherd/log.Prefix).Trace call not used
log.Debug().String("k", "v")             // warning: result of (*github.com/gopherd/log.Recorder).String call not used
log.Debug().Int("i", 1).String("k", "v") // warning: result of (*github.com/gopherd/log.Recorder).String call not used

// right
log.Debug().String("k", "v").Print("message")
log.Debug().Print("message")

Documentation

Overview

Auto-generated by genslice.go, DON'T EDIT IT!

Index

Examples

Constants

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

View Source
const (
	KB = 1024
	MB = 1024 * KB
	GB = 1024 * MB
)

Variables

This section is empty.

Functions

func GetFlags

func GetFlags()

GetFlags returns the flags

func Log

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

Log is a low-level API to print log.

func Printf

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

Printf wraps the global printer Printf method

func Register added in v0.0.2

func Register(name string, creator WriterCreator)

func SetFlags

func SetFlags(flags int)

SetFlags sets the flags

func SetLevel

func SetLevel(level Level)

SetLevel sets current log level

func Shutdown

func Shutdown()

Shutdown shutdowns global printer

func Start

func Start(options ...Option) error

Start starts logging with options

Types

type FS

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 File

type File interface {
	io.WriteCloser
	// 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

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

type FileOptions struct {
	Dir      string     `json:"dir"`      // log directory (default: .)
	Filename string     `json:"filename"` // log filename (default: <process name>)
	Symdir   string     `json:"symdir"`   // symlinked directory (default: "")
	Rotate   bool       `json:"rotate"`   // enable log rotate (default: false)
	MaxSize  int64      `json:"maxsize"`  // max number bytes of log file (default: 64M)
	Suffix   string     `json:"suffix"`   // filename suffix (default: .log)
	Header   FileHeader `json:"header"`   // header type of file (default: NoHeader)

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

FileOptions represents options of file writer

fullname of log file: $Filename.$date[.$rotateId]$Suffix

type Level

type Level int32

Level represents log level

const (
	LevelFatal Level // 1
	LevelError       // 2
	LevelWarn        // 3
	LevelInfo        // 4
	LevelDebug       // 5
	LevelTrace       // 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

func (level Level) Literal() string

Literal returns literal value which is a number

func (Level) MarshalJSON

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

MarshalJSON implements json.Marshaler

func (Level) MoreVerboseThan

func (level Level) MoreVerboseThan(other Level) bool

MoreVerboseThan returns whether level more verbose than other

func (*Level) Set

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

func (level Level) String() string

String returns a serialized string of level

func (*Level) UnmarshalJSON

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

UnmarshalJSON implements json.Unmarshaler

type MultiFileOptions

type MultiFileOptions struct {
	FileOptions
	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

type Option func(*startOptions)

Option is option for Start

func WithFile

func WithFile(fileOptions FileOptions) Option

WithFile appends a file writer

func WithFlags

func WithFlags(flags int) Option

WithFlags enable or disable flags information

func WithHTTPHandler

func WithHTTPHandler(yes bool) Option

WithHTTPHandler enable or disable http handler for settting level

func WithLevel

func WithLevel(level Level) Option

WithLevel sets log level

func WithMultiFile

func WithMultiFile(multiFileOptions MultiFileOptions) Option

WithMultiFile appends a multifile writer

func WithOutput

func WithOutput(w io.Writer) Option

WithOutput appends a console writer with specified io.Writer

func WithPrefix

func WithPrefix(prefix string) Option

WithPrefix set log prefix

func WithPrinter

func WithPrinter(printer Printer) Option

WithPrinter specify custom printer

func WithSync

func WithSync(yes bool) Option

WithSync synchronize outputs log or not

func WithWriters

func WithWriters(writers ...Writer) Option

WithWriters appends the writers

type Prefix

type Prefix string

Prefix wraps a string as a prefixed logger

func (Prefix) Debug

func (p Prefix) Debug() *Recorder

Debug creates a context recorder with level debug

func (Prefix) Error

func (p Prefix) Error() *Recorder

Error creates a context recorder with level error

func (Prefix) Fatal

func (p Prefix) Fatal() *Recorder

Fatal creates a context recorder with level fatal

func (Prefix) Info

func (p Prefix) Info() *Recorder

Info creates a context recorder with level info

func (Prefix) Prefix

func (p Prefix) Prefix(prefix string) Prefix

Prefix appends a prefix to current prefix

func (Prefix) Printf

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

Printf wraps the global printer Printf method

func (Prefix) Trace

func (p Prefix) Trace() *Recorder

Trace creates a context recorder with level trace

func (Prefix) Warn

func (p Prefix) Warn() *Recorder

Warn creates a context recorder with level warn

type Printer

type Printer interface {
	// Start starts the printer
	Start()
	// Quit quits the printer
	Shutdown()
	// Flush flushs all queued logs
	Flush()
	// GetFlags returns the flags
	GetFlags() int
	// SetFlags sets the flags
	SetFlags(flags int)
	// GetLevel returns log level
	GetLevel() Level
	// SetLevel sets log level
	SetLevel(Level)
	// SetPrefix sets log prefix
	SetPrefix(string)
	// Printf outputs leveled logs with file, line and extra prefix.
	// If line <= 0, then file and line both are invalid.
	Printf(file string, line int, level Level, prefix, format string, args ...interface{})
}

Printer represents the printer for logging

type Recorder added in v0.0.3

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

Recorder holds context recorder

Example
package main

import (
	"bytes"
	"errors"
	"fmt"
	"time"

	"github.com/gopherd/log"
)

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('[')
		w.buf.WriteString(level.String())
		w.buf.WriteByte(']')
		w.buf.WriteByte(' ')
		w.buf.Write(data[headerLen:])
	}
	return nil
}

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

func main() {
	writer := new(testingLogWriter)
	log.Start(log.WithWriters(writer), log.WithLevel(log.LevelInfo), log.WithPrefix("testing"))
	log.Info().Int("int", 123456).Print("recorder")
	log.Info().Int8("int8", -12).Print("recorder")
	log.Info().Int16("int16", 1234).Print("recorder")
	log.Info().Int32("int32", -12345678).Print("recorder")
	log.Info().Int64("int64", 1234567890).Print("recorder")
	log.Info().Uint("uint", 123456).Print("recorder")
	log.Info().Uint8("uint8", 120).Print("recorder")
	log.Info().Uint16("uint16", 12340).Print("recorder")
	log.Info().Uint32("uint32", 123456780).Print("recorder")
	log.Info().Uint64("uint64", 12345678900).Print("recorder")
	log.Info().Float32("float32", 1234.5678).Print("recorder")
	log.Info().Float64("float64", 0.123456789).Print("recorder")
	log.Info().Complex64("complex64", 1+2i).Print("recorder")
	log.Info().Complex128("complex128", 1).Print("recorder")
	log.Info().Complex128("complex128", 2i).Print("recorder")
	log.Info().Byte("byte", 'h').Print("recorder")
	log.Info().Rune("rune", 'Å').Print("recorder")
	log.Info().Bool("bool", true).Print("recorder")
	log.Info().Bool("bool", false).Print("recorder")
	log.Info().String("string", "hello").Print("recorder")
	log.Info().Error("error", nil).Print("recorder")
	log.Info().Error("error", errors.New("err")).Print("recorder")
	log.Info().Any("any", nil).Print("recorder")
	log.Info().Any("any", "nil").Print("recorder")
	log.Info().Any("any", struct {
		x int
		y string
	}{1, "hello"}).Print("recorder")
	log.Info().Type("type", nil).Print("recorder")
	log.Info().Type("type", "string").Print("recorder")
	log.Info().Type("type", new(int)).Print("recorder")
	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("recorder")
	log.Info().Time("time", t).Print("recorder")
	log.Info().Duration("duration", time.Millisecond*1200).Print("recorder")
	log.Info().String("$name", "hello").Print("recorder")
	log.Info().String("name of", "hello").Print("recorder")
	log.Info().Int32s("int32s", []int32{1, 3, 5}).Print("recorder")
	log.Info().Strings("strings", []string{"x", "x y", "z"}).Print("recorder")
	log.Info().Bytes("bytes", []byte{'1', '3', 'x'}).Print("recorder")
	log.Prefix("prefix").Info().
		String("k1", "v1").
		Int("k2", 2).
		Print("prefix logging")
	log.Debug().String("key", "value").Print("not output")
	log.Shutdown()
	fmt.Print(writer.buf.String())
}
Output:

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

func Debug

func Debug() *Recorder

Debug creates a context recorder with level debug

func Error

func Error() *Recorder

Error creates a context recorder with level error

func Fatal

func Fatal() *Recorder

Fatal creates a context recorder with level fatal

func Info

func Info() *Recorder

Info creates a context recorder with level info

func Trace

func Trace() *Recorder

Trace creates a context recorder with level trace

func Warn

func Warn() *Recorder

Warn creates a context recorder with level warn

func (*Recorder) Any added in v0.0.3

func (recorder *Recorder) Any(key string, value interface{}) *Recorder

func (*Recorder) Bool added in v0.0.3

func (recorder *Recorder) Bool(key string, value bool) *Recorder

func (*Recorder) Bools added in v0.0.3

func (recorder *Recorder) Bools(key string, value []bool) *Recorder

func (*Recorder) Byte added in v0.0.3

func (recorder *Recorder) Byte(key string, value byte) *Recorder

func (*Recorder) Bytes added in v0.0.3

func (recorder *Recorder) Bytes(key string, value []byte) *Recorder

func (*Recorder) Complex64 added in v0.0.3

func (recorder *Recorder) Complex64(key string, value complex64) *Recorder

func (*Recorder) Complex64s added in v0.0.3

func (recorder *Recorder) Complex64s(key string, value []complex64) *Recorder

func (*Recorder) Complex128 added in v0.0.3

func (recorder *Recorder) Complex128(key string, value complex128) *Recorder

func (*Recorder) Complex128s added in v0.0.3

func (recorder *Recorder) Complex128s(key string, value []complex128) *Recorder

func (*Recorder) Date added in v0.0.3

func (recorder *Recorder) Date(key string, value time.Time) *Recorder

func (*Recorder) Duration added in v0.0.3

func (recorder *Recorder) Duration(key string, value time.Duration) *Recorder

func (*Recorder) Error added in v0.0.3

func (recorder *Recorder) Error(key string, value error) *Recorder

func (*Recorder) Exec added in v0.0.3

func (recorder *Recorder) Exec(key string, stringer func() string) *Recorder

func (*Recorder) Float32 added in v0.0.3

func (recorder *Recorder) Float32(key string, value float32) *Recorder

func (*Recorder) Float32s added in v0.0.3

func (recorder *Recorder) Float32s(key string, value []float32) *Recorder

func (*Recorder) Float64 added in v0.0.3

func (recorder *Recorder) Float64(key string, value float64) *Recorder

func (*Recorder) Float64s added in v0.0.3

func (recorder *Recorder) Float64s(key string, value []float64) *Recorder

func (*Recorder) Int added in v0.0.3

func (recorder *Recorder) Int(key string, value int) *Recorder

func (*Recorder) Int8 added in v0.0.3

func (recorder *Recorder) Int8(key string, value int8) *Recorder

func (*Recorder) Int8s added in v0.0.3

func (recorder *Recorder) Int8s(key string, value []int8) *Recorder

func (*Recorder) Int16 added in v0.0.3

func (recorder *Recorder) Int16(key string, value int16) *Recorder

func (*Recorder) Int16s added in v0.0.3

func (recorder *Recorder) Int16s(key string, value []int16) *Recorder

func (*Recorder) Int32 added in v0.0.3

func (recorder *Recorder) Int32(key string, value int32) *Recorder

func (*Recorder) Int32s added in v0.0.3

func (recorder *Recorder) Int32s(key string, value []int32) *Recorder

func (*Recorder) Int64 added in v0.0.3

func (recorder *Recorder) Int64(key string, value int64) *Recorder

func (*Recorder) Int64s added in v0.0.3

func (recorder *Recorder) Int64s(key string, value []int64) *Recorder

func (*Recorder) Ints added in v0.0.3

func (recorder *Recorder) Ints(key string, value []int) *Recorder

func (*Recorder) Microseconds added in v0.0.3

func (recorder *Recorder) Microseconds(key string, value time.Time) *Recorder

func (*Recorder) Milliseconds added in v0.0.3

func (recorder *Recorder) Milliseconds(key string, value time.Time) *Recorder

func (*Recorder) Print added in v0.0.3

func (recorder *Recorder) Print(s string)

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

func (*Recorder) Rune added in v0.0.3

func (recorder *Recorder) Rune(key string, value rune) *Recorder

func (*Recorder) Seconds added in v0.0.3

func (recorder *Recorder) Seconds(key string, value time.Time) *Recorder

func (*Recorder) String added in v0.0.3

func (recorder *Recorder) String(key string, value string) *Recorder

func (*Recorder) Strings added in v0.0.3

func (recorder *Recorder) Strings(key string, value []string) *Recorder

func (*Recorder) Time added in v0.0.3

func (recorder *Recorder) Time(key string, value time.Time) *Recorder

func (*Recorder) Type added in v0.0.3

func (recorder *Recorder) Type(key string, value interface{}) *Recorder

func (*Recorder) Uint added in v0.0.3

func (recorder *Recorder) Uint(key string, value uint) *Recorder

func (*Recorder) Uint8 added in v0.0.3

func (recorder *Recorder) Uint8(key string, value uint8) *Recorder

func (*Recorder) Uint8s added in v0.0.3

func (recorder *Recorder) Uint8s(key string, value []uint8) *Recorder

func (*Recorder) Uint16 added in v0.0.3

func (recorder *Recorder) Uint16(key string, value uint16) *Recorder

func (*Recorder) Uint16s added in v0.0.3

func (recorder *Recorder) Uint16s(key string, value []uint16) *Recorder

func (*Recorder) Uint32 added in v0.0.3

func (recorder *Recorder) Uint32(key string, value uint32) *Recorder

func (*Recorder) Uint32s added in v0.0.3

func (recorder *Recorder) Uint32s(key string, value []uint32) *Recorder

func (*Recorder) Uint64 added in v0.0.3

func (recorder *Recorder) Uint64(key string, value uint64) *Recorder

func (*Recorder) Uint64s added in v0.0.3

func (recorder *Recorder) Uint64s(key string, value []uint64) *Recorder

func (*Recorder) Uints added in v0.0.3

func (recorder *Recorder) Uints(key string, value []uint) *Recorder

type Writer

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

Writer represents a writer for logging

func Open added in v0.0.2

func Open(url string) (Writer, error)

type WriterCreator added in v0.0.2

type WriterCreator func(source string) (Writer, error)

Directories

Path Synopsis
Auto-generated by github.com/gopherd/log/genlintfuncs.sh, DON'T EDIT IT!
Auto-generated by github.com/gopherd/log/genlintfuncs.sh, DON'T EDIT IT!
wrapper
gorm_logger module

Jump to

Keyboard shortcuts

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