log

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Jul 25, 2021 License: MIT Imports: 17 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.Context).String call not used
log.Debug().Int("i", 1).String("k", "v") // warning: result of (*github.com/gopherd/log.Context).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 (
	Ltimestamp    = 1 << iota                  // the timestamp in the local time zone: 2001/02/03 01:23:23
	LUTC                                       // if Ltimestamp is set, use UTC rather than the local time zone
	Lmicroseconds                              // microsecond resolution: 01:23:23.123123.  assumes Ltimestamp.
	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
	LdefaultFlags = Ltimestamp | Lmicroseconds // 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 output flags

func Log

func Log(level Level, msg string)

Log output log with specified level

func Print added in v0.0.11

func Print(calldepth int, level Level, msg string)

Print is a low-level API to print log.

func Register added in v0.0.2

func Register(name string, creator WriterCreator)

func SetFlags

func SetFlags(flags int)

SetFlags sets the output flags

func SetLevel

func SetLevel(level Level)

SetLevel sets the log level

func Shutdown

func Shutdown()

Shutdown shutdowns the global logger

func Start

func Start(options ...Option) error

Start starts the global logger

Types

type Caller added in v0.0.11

type Caller struct {
	Filename string
	Line     int
}

type Context added in v0.0.11

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

Context holds context ctx

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

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

func Debug

func Debug() *Context

Debug creates a context with level debug

func Error

func Error() *Context

Error creates a context with level error

func Fatal

func Fatal() *Context

Fatal creates a context with level fatal

func Info

func Info() *Context

Info creates a context with level info

func Trace

func Trace() *Context

Trace creates a context with level trace

func Warn

func Warn() *Context

Warn creates a context with level warn

func (*Context) Any added in v0.0.11

func (ctx *Context) Any(key string, value interface{}) *Context

func (*Context) Bool added in v0.0.11

func (ctx *Context) Bool(key string, value bool) *Context

func (*Context) Bools added in v0.0.11

func (ctx *Context) Bools(key string, value []bool) *Context

func (*Context) Byte added in v0.0.11

func (ctx *Context) Byte(key string, value byte) *Context

func (*Context) Bytes added in v0.0.11

func (ctx *Context) Bytes(key string, value []byte) *Context

func (*Context) Complex64 added in v0.0.11

func (ctx *Context) Complex64(key string, value complex64) *Context

func (*Context) Complex64s added in v0.0.11

func (ctx *Context) Complex64s(key string, value []complex64) *Context

func (*Context) Complex128 added in v0.0.11

func (ctx *Context) Complex128(key string, value complex128) *Context

func (*Context) Complex128s added in v0.0.11

func (ctx *Context) Complex128s(key string, value []complex128) *Context

func (*Context) Date added in v0.0.11

func (ctx *Context) Date(key string, value time.Time) *Context

func (*Context) Duration added in v0.0.11

func (ctx *Context) Duration(key string, value time.Duration) *Context

func (*Context) Error added in v0.0.11

func (ctx *Context) Error(key string, value error) *Context

func (*Context) Exec added in v0.0.11

func (ctx *Context) Exec(key string, stringer func() string) *Context

func (*Context) Float32 added in v0.0.11

func (ctx *Context) Float32(key string, value float32) *Context

func (*Context) Float32s added in v0.0.11

func (ctx *Context) Float32s(key string, value []float32) *Context

func (*Context) Float64 added in v0.0.11

func (ctx *Context) Float64(key string, value float64) *Context

func (*Context) Float64s added in v0.0.11

func (ctx *Context) Float64s(key string, value []float64) *Context

func (*Context) Int added in v0.0.11

func (ctx *Context) Int(key string, value int) *Context

func (*Context) Int8 added in v0.0.11

func (ctx *Context) Int8(key string, value int8) *Context

func (*Context) Int8s added in v0.0.11

func (ctx *Context) Int8s(key string, value []int8) *Context

func (*Context) Int16 added in v0.0.11

func (ctx *Context) Int16(key string, value int16) *Context

func (*Context) Int16s added in v0.0.11

func (ctx *Context) Int16s(key string, value []int16) *Context

func (*Context) Int32 added in v0.0.11

func (ctx *Context) Int32(key string, value int32) *Context

func (*Context) Int32s added in v0.0.11

func (ctx *Context) Int32s(key string, value []int32) *Context

func (*Context) Int64 added in v0.0.11

func (ctx *Context) Int64(key string, value int64) *Context

func (*Context) Int64s added in v0.0.11

func (ctx *Context) Int64s(key string, value []int64) *Context

func (*Context) Ints added in v0.0.11

func (ctx *Context) Ints(key string, value []int) *Context

func (*Context) Microseconds added in v0.0.11

func (ctx *Context) Microseconds(key string, value time.Time) *Context

func (*Context) Milliseconds added in v0.0.11

func (ctx *Context) Milliseconds(key string, value time.Time) *Context

func (*Context) Print added in v0.0.11

func (ctx *Context) Print(msg string)

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

func (*Context) Rune added in v0.0.11

func (ctx *Context) Rune(key string, value rune) *Context

func (*Context) Seconds added in v0.0.11

func (ctx *Context) Seconds(key string, value time.Time) *Context

func (*Context) String added in v0.0.11

func (ctx *Context) String(key string, value string) *Context

func (*Context) Strings added in v0.0.11

func (ctx *Context) Strings(key string, value []string) *Context

func (*Context) Time added in v0.0.11

func (ctx *Context) Time(key string, value time.Time) *Context

func (*Context) Type added in v0.0.11

func (ctx *Context) Type(key string, value interface{}) *Context

func (*Context) Uint added in v0.0.11

func (ctx *Context) Uint(key string, value uint) *Context

func (*Context) Uint8 added in v0.0.11

func (ctx *Context) Uint8(key string, value uint8) *Context

func (*Context) Uint8s added in v0.0.11

func (ctx *Context) Uint8s(key string, value []uint8) *Context

func (*Context) Uint16 added in v0.0.11

func (ctx *Context) Uint16(key string, value uint16) *Context

func (*Context) Uint16s added in v0.0.11

func (ctx *Context) Uint16s(key string, value []uint16) *Context

func (*Context) Uint32 added in v0.0.11

func (ctx *Context) Uint32(key string, value uint32) *Context

func (*Context) Uint32s added in v0.0.11

func (ctx *Context) Uint32s(key string, value []uint32) *Context

func (*Context) Uint64 added in v0.0.11

func (ctx *Context) Uint64(key string, value uint64) *Context

func (*Context) Uint64s added in v0.0.11

func (ctx *Context) Uint64s(key string, value []uint64) *Context

func (*Context) Uints added in v0.0.11

func (ctx *Context) Uints(key string, value []uint) *Context

type ContextLogger added in v0.0.11

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

func Prefix

func Prefix(logger *Logger, prefix string) *ContextLogger

func (*ContextLogger) Debug added in v0.0.11

func (p *ContextLogger) Debug() *Context

Debug creates a context with level debug

func (*ContextLogger) Error added in v0.0.11

func (p *ContextLogger) Error() *Context

Error creates a context with level error

func (*ContextLogger) Fatal added in v0.0.11

func (p *ContextLogger) Fatal() *Context

Fatal creates a context with level fatal

func (*ContextLogger) Info added in v0.0.11

func (p *ContextLogger) Info() *Context

Info creates a context with level info

func (*ContextLogger) Log added in v0.0.11

func (p *ContextLogger) Log(level Level, msg string)

Log output log with specified level

func (*ContextLogger) Prefix added in v0.0.11

func (p *ContextLogger) Prefix() string

func (*ContextLogger) Print added in v0.0.11

func (p *ContextLogger) Print(calldepth int, level Level, msg string)

Print is a low-level API to print log.

func (*ContextLogger) Trace added in v0.0.11

func (p *ContextLogger) Trace() *Context

Trace creates a context with level trace

func (*ContextLogger) Warn added in v0.0.11

func (p *ContextLogger) Warn() *Context

Warn creates a context with level warn

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 the 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 Logger added in v0.0.11

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

func GlobalLogger added in v0.0.11

func GlobalLogger() *Logger

func NewLogger added in v0.0.11

func NewLogger(prefix string) *Logger

NewLogger creates logger

func (*Logger) Debug added in v0.0.11

func (logger *Logger) Debug() *Context

Debug creates a context with level debug

func (*Logger) Error added in v0.0.11

func (logger *Logger) Error() *Context

Error creates a context with level error

func (*Logger) Fatal added in v0.0.11

func (logger *Logger) Fatal() *Context

Fatal creates a context with level fatal

func (*Logger) GetFlags added in v0.0.11

func (logger *Logger) GetFlags() int

GetFlags returns the output flags

func (*Logger) GetLevel added in v0.0.11

func (logger *Logger) GetLevel() Level

GetLevel returns the log level

func (*Logger) Info added in v0.0.11

func (logger *Logger) Info() *Context

Info creates a context with level info

func (*Logger) Log added in v0.0.11

func (logger *Logger) Log(level Level, msg string)

Log output log with specified level

func (*Logger) Print added in v0.0.11

func (logger *Logger) Print(calldepth int, level Level, msg string)

Print is a low-level API to print log.

func (*Logger) SetFlags added in v0.0.11

func (logger *Logger) SetFlags(flags int)

SetFlags sets the output flags

func (*Logger) SetLevel added in v0.0.11

func (logger *Logger) SetLevel(level Level)

SetLevel sets the log level

func (*Logger) Shutdown added in v0.0.11

func (logger *Logger) Shutdown()

func (*Logger) Start added in v0.0.11

func (logger *Logger) Start(options ...Option) error

Start starts logging with options

func (*Logger) Trace added in v0.0.11

func (logger *Logger) Trace() *Context

Trace creates a context with level trace

func (*Logger) Warn added in v0.0.11

func (logger *Logger) Warn() *Context

Warn creates a context with level warn

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

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

type Printer interface {
	// Start starts the printer
	Start()
	// Shutdown shutdowns the printer
	Shutdown()
	// Print outputs leveled logs with file, line and extra prefix.
	// If line <= 0, then file and line both are invalid.
	Print(level Level, flags int, caller Caller, prefix, msg string)
}

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

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