log

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Jun 23, 2021 License: MIT Imports: 19 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")
}

Documentation

Index

Examples

Constants

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 // 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.

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 logging

func Printf

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

Printf wraps the global printer Printf method

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 Fields

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

Fields holds context fields

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.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")
	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} 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

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

func (*Fields) Bool

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

func (*Fields) Byte

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

func (*Fields) Complex64

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

func (*Fields) Complex128

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

func (*Fields) Date

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

func (*Fields) Duration

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

func (*Fields) Error

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

func (*Fields) Exec

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

func (*Fields) Float32

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

func (*Fields) Float64

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

func (*Fields) Int

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

func (*Fields) Int8

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

func (*Fields) Int16

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

func (*Fields) Int32

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

func (*Fields) Int64

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

func (*Fields) Microseconds

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

func (*Fields) Milliseconds

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

func (*Fields) Print

func (fields *Fields) Print(s string)

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

func (*Fields) Rune

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

func (*Fields) Seconds

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

func (*Fields) String

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

func (*Fields) Time

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

func (*Fields) Type

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

func (*Fields) Uint

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

func (*Fields) Uint8

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

func (*Fields) Uint16

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

func (*Fields) Uint32

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

func (*Fields) Uint64

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

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: <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

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

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 WithConsole

func WithConsole() Option

WithConsole appends a console writer

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() *Fields

Debug creates a context fields with level debug

func (Prefix) Error

func (p Prefix) Error() *Fields

Error creates a context fields with level error

func (Prefix) Fatal

func (p Prefix) Fatal() *Fields

Fatal creates a context fields with level fatal

func (Prefix) Info

func (p Prefix) Info() *Fields

Info creates a context fields 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() *Fields

Trace creates a context fields with level trace

func (Prefix) Warn

func (p Prefix) Warn() *Fields

Warn creates a context fields 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 specified calldepth and extra prefix
	Printf(calldepth int, level Level, prefix, format string, args ...interface{})
}

Printer represents the printer for logging

type Writer

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

Writer represents a writer for logging

Directories

Path Synopsis
wrapper
gorm_logger module

Jump to

Keyboard shortcuts

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