log

package module
v0.0.0-...-57875b1 Latest Latest
Warning

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

Go to latest
Published: Feb 8, 2021 License: Apache-2.0 Imports: 21 Imported by: 0

README

log15

This Package is a fork from log15

For more information, you can access the Source Link .

Add new features:

  • Filter log level when writing into Log File .
  • Rotating logfile automaticly when logfile size larger than setting or default. (eg: > 100M)
  • You can rotate logfile whenever you want by using func "Rotate()"
Usage:

Importing

import log "github.com/wuzuoliang/log"

Examples

1: Basic usage
func main() {

    h,_ := log.FileHandler("./app.log", log.LogfmtFormat())
    log.Root().SetHandler(h)

    Path := "http://test.com"
    for i:=1; i < 1000000 ; i++ {
        log.Info("page accessed", "path", Path, "user_id", i)
        time.Sleep(50 * time.Millisecond)
    }
}

Will result in output that looks like this:

t=2017-09-26T01:40:37-0400 lvl=info msg="page accessed" path=http://woda.com user_id=21
t=2017-09-26T01:40:37-0400 lvl=info msg="page accessed" path=http://woda.com user_id=22
2: Set LogLevel filter
func main() {
    // set level to Warn
    log.SetOutLevel(log.LvlWarn)

    h,_ := log.FileHandler("./app.log", log.LogfmtFormat())
    log.Root().SetHandler(h)

    Path := "http://test.com"
    for i:=1; i < 1000000 ; i++ {

        // Info is large than Warn, output none
        log.Info("page accessed", "path", Path, "user_id", i)
        time.Sleep(50 * time.Millisecond)
    }
}

Will output nothing.

Log level define: (from small to large)
  • LvlCrit
  • LvlError
  • LvlWarn
  • LvlInfo
  • LvlDebug
3: Modify default rotate parameters
func main() {
    // set rotate parameters:
    // size:1m, keep 10days, backup 5 files, uncompress when rotate
    log.SetRotatePara(1,10,5,false,true)

    h,_ := log.FileHandlerRotate("./app.log", log.LogfmtFormat())
    log.Root().SetHandler(h)

    Path := "http://test.com"
    for i:=1; i < 1000000 ; i++ {
        log.Info("page accessed", "path", Path, "user_id", i)
    }

Will result in output that looks like this:

log15]$ ls -l
total 8664
-rw-r--r--. 1 work work 1048524 Sep 26 02:43 app-2017-09-26T02-43-12.826.log
-rw-r--r--. 1 work work 1048524 Sep 26 02:43 app-2017-09-26T02-43-12.890.log
-rw-r--r--. 1 work work 1048524 Sep 26 02:43 app-2017-09-26T02-43-12.941.log
-rw-r--r--. 1 work work 1048524 Sep 26 02:43 app-2017-09-26T02-43-13.006.log
-rw-r--r--. 1 work work 1048524 Sep 26 02:43 app-2017-09-26T02-43-13.068.log
-rw-r--r--. 1 work work  667368 Sep 26 02:43 app.log

func "SetRotatePara()" define:

SetRotatePara(maxsize, maxage, maxbackup int, compress bool)

The default rotate parameters:

  • maxSize : 100 // 100M
  • maxAge: 10 // days
  • maxBackUp: 30 // files
  • compress: true
  • dayRotate: true
4: Force logfile rotate
func main() {
    h,_ := log.FileHandlerRotate("./app.log", log.LogfmtFormat())
    log.Root().SetHandler(h)
    

    go func(){
      for {
          time.Sleep( 1 * time.Second)
          log.LogRotate()
      }
    }()

    Path := "http://test.com"
    for i:=1; i < 1000000 ; i++ {
        log.Info("page accessed", "path", Path, "user_id", i)
        time.Sleep(50 * time.Millisecond)
    }
    
     for i:=1; i < 1000000 ; i++ {
            if IsInfoEnable(){
               log.Info("page accessed", "path", Path, "user_id", i)
             }
             time.Sleep(50 * time.Millisecond)
       }
}

Will result in output that looks like this:

log15]$ ls -l
total 2924
-rw-r--r--. 1 work work     201 Sep 26 03:08 app-2017-09-26T03-08-59.134.log.gz
-rw-r--r--. 1 work work     171 Sep 26 03:09 app-2017-09-26T03-09-00.135.log.gz
-rw-r--r--. 1 work work     174 Sep 26 03:09 app-2017-09-26T03-09-01.136.log.gz
-rw-r--r--. 1 work work     171 Sep 26 03:09 app-2017-09-26T03-09-02.138.log.gz
-rw-r--r--. 1 work work     616 Sep 26 03:09 app.log

every second rotate once.

License

Apache

Documentation

Index

Constants

View Source
const (
	LvlFatal = iota
	LvlError
	LvlWarn
	LvlInfo
	LvlDebug
	LvlTrace

	LvlFatalStr = "fatal"
	LvlErrorStr = "error"
	LvlWarnStr  = "warn"
	LvlInfoStr  = "info"
	LvlDebugStr = "debug"
	LvlTraceStr = "trace"
)

Variables

View Source
var (
	StdoutHandler = StreamHandler(os.Stdout, LogfmtFormat())
	StderrHandler = StreamHandler(os.Stderr, LogfmtFormat())
)

Functions

func Debug

func Debug(msg string, keyValues ...interface{})

Debug is a convenient alias for Root().Debug

func DebugContext

func DebugContext(ctx context.Context, msg string, keyValues ...interface{})

Debug is a convenient alias for Root().Debug

func Error

func Error(msg string, keyValues ...interface{})

Error is a convenient alias for Root().Error

func ErrorContext

func ErrorContext(ctx context.Context, msg string, keyValues ...interface{})

Error is a convenient alias for Root().Error

func Fatal

func Fatal(msg string, keyValues ...interface{})

Fatal is a convenient alias for Root().Fatal

func FatalContext

func FatalContext(ctx context.Context, msg string, keyValues ...interface{})

Fatal is a convenient alias for Root().Fatal

func GetDefaultRotateOption

func GetDefaultRotateOption() *rotateOptions

func Info

func Info(msg string, keyValues ...interface{})

Info is a convenient alias for Root().Info

func InfoContext

func InfoContext(ctx context.Context, msg string, keyValues ...interface{})

Info is a convenient alias for Root().Info

func IsDebugEnable

func IsDebugEnable() bool

func IsErrorEnable

func IsErrorEnable() bool

func IsFatalEnable

func IsFatalEnable() bool

func IsInfoEnable

func IsInfoEnable() bool

func IsWarnEnable

func IsWarnEnable() bool

func JSON

func JSON(v interface{}) string

JSON is a helper function, following is its function code.

data, _ := json.Marshal(v)
return string(data)

func Log

func Log(msg string, keyValues ...interface{})

Log is a convenient alias for Root().Log

func LogContext

func LogContext(ctx context.Context, msg string, keyValues ...interface{})

LogContext is a convenient alias for Root().Log with context.Context

func SetBytesBufferPool

func SetBytesBufferPool(pool BytesBufferPool)

func SetDefaultRotateOptions

func SetDefaultRotateOptions(opts []RotateOptions)

func SetOutLevel

func SetOutLevel(level Level)

func Warn

func Warn(msg string, keyValues ...interface{})

Warn is a convenient alias for Root().Warn

func WarnContext

func WarnContext(ctx context.Context, msg string, keyValues ...interface{})

Warn is a convenient alias for Root().Warn

func XML

func XML(v interface{}) string

XML is a helper function, following is its function code.

data, _ := xml.Marshal(v)
return string(data)

Types

type BytesBufferPool

type BytesBufferPool interface {
	Get() *bytes.Buffer
	Put(*bytes.Buffer)
}

type Ctx

type Ctx map[string]interface{}

Ctx is a map of key/value pairs to pass as context to a log function Use this only if you really need greater safety around the arguments you pass to the logging functions.

type Format

type Format interface {
	Format(r *Record) []byte
}

func FormatFunc

func FormatFunc(f func(*Record) []byte) Format

FormatFunc returns a new Format object which uses the given function to perform record formatting.

func JsonFormat

func JsonFormat() Format

JsonFormat formats log records as JSON objects separated by newlines. It is the equivalent of JsonFormatEx(false, true).

func JsonFormatEx

func JsonFormatEx(pretty, lineSeparated bool) Format

JsonFormatEx formats log records as JSON objects. If pretty is true, records will be pretty-printed. If lineSeparated is true, records will be logged with a new line between each record.

func LogfmtFormat

func LogfmtFormat() Format

LogfmtFormat prints records in kvaluesfmt format, an easy machine-parseable but human-readable format for key/value pairs.

For more details see: https://pkg.go.dev/github.com/kr/logfmt

func TerminalFormat

func TerminalFormat() Format

TerminalFormat formats log records optimized for human readability on a terminal with color-coded level output and terser human friendly timestamp. This format should only be used for interactive programs or while developing.

[TIME] [LEVEL] MESAGE key=value key=value ...

Example:

[May 16 20:58:45] [DBUG] remove route ns=haproxy addr=127.0.0.1:50002

type Handler

type Handler interface {
	Log(r *Record) error
}

A Logger prints its log records by writing to a Handler. The Handler interface defines where and how log records are written. Handlers are composable, providing you great flexibility in combining them to achieve the logging structure that suits your applications.

func BufferedHandler

func BufferedHandler(bufSize int, h Handler) Handler

BufferedHandler writes all records to a buffered channel of the given size which flushes into the wrapped handler whenever it is available for writing. Since these writes happen asynchronously, all writes to a BufferedHandler never return an error and any errors from the wrapped handler are ignored.

func CallerFileHandler

func CallerFileHandler(h Handler) Handler

CallerFileHandler returns a Handler that adds the line number and file of the calling function to the context with key "caller".

func CallerFuncHandler

func CallerFuncHandler(h Handler) Handler

CallerFuncHandler returns a Handler that adds the calling function name to the context with key "fn".

func CallerStackHandler

func CallerStackHandler(format string, h Handler) Handler

CallerStackHandler returns a Handler that adds a stack trace to the context with key "stack". The stack trace is formated as a space separated list of call sites inside matching []'s. The most recent call site is listed first. Each call site is formatted according to format. See the documentation of package github.com/go-stack/stack for the list of supported formats.

func ChannelHandler

func ChannelHandler(recs chan<- *Record) Handler

ChannelHandler writes all records to the given channel. It blocks if the channel is full. Useful for async processing of log messages, it's used by BufferedHandler.

func DiscardHandler

func DiscardHandler() Handler

DiscardHandler reports success for all writes but does nothing. It is useful for dynamically disabling logging at runtime via a Logger's SetHandler method.

func FailoverHandler

func FailoverHandler(hs ...Handler) Handler

A FailoverHandler writes all log records to the first handler specified, but will failover and write to the second handler if the first handler has failed, and so on for all handlers specified. For example you might want to log to a network socket, but failover to writing to a file if the network fails, and then to standard out if the file write fails:

log.FailoverHandler(
    log.Must.NetHandler("tcp", ":9090", log.JsonFormat()),
    log.Must.FileHandler("/var/log/app.log", log.LogfmtFormat()),
    log.StdoutHandler)

All writes that do not go to the first handler will add context with keys of the form "failover_err_{idx}" which explain the error encountered while trying to write to the handlers before them in the list.

func FileHandler

func FileHandler(path string, fmtr Format) (Handler, error)

FileHandler returns a handler which writes log records to the give file using the given format. If the path already exists, FileHandler will append to the given file. If it does not, FileHandler will create the file with mode 0644.

func FileHandlerRotate

func FileHandlerRotate(output string, fmtr Format, options []RotateOptions) (Handler, error)

FileHandlerRotate add lumberjack lib

func FilterHandler

func FilterHandler(fn func(r *Record) bool, h Handler) Handler

FilterHandler returns a Handler that only writes records to the wrapped Handler if the given function evaluates true. For example, to only log records where the 'err' key is not nil:

logger.SetHandler(FilterHandler(func(r *Record) bool {
    for i := 0; i < len(r.Ctx); i += 2 {
        if r.Ctx[i] == "err" {
            return r.Ctx[i+1] != nil
        }
    }
    return false
}, h))

func FuncHandler

func FuncHandler(fn func(r *Record) error) Handler

FuncHandler returns a Handler that logs records with the given function.

func LazyHandler

func LazyHandler(h Handler) Handler

LazyHandler writes all values to the wrapped handler after evaluating any lazy functions in the record's context. It is already wrapped around StreamHandler and SyslogHandler in this library, you'll only need it if you write your own Handler.

func LvlFilterHandler

func LvlFilterHandler(maxLvl Level, h Handler) Handler

LvlFilterHandler returns a Handler that only writes records which are less than the given verbosity level to the wrapped Handler. For example, to only log Error/Crit records:

log.LvlFilterHandler(log.LvlError, log.StdoutHandler)

func MatchFilterHandler

func MatchFilterHandler(key string, value interface{}, h Handler) Handler

MatchFilterHandler returns a Handler that only writes records to the wrapped Handler if the given key in the logged context matches the value. For example, to only log records from your ui package:

log.MatchFilterHandler("pkg", "app/ui", log.StdoutHandler)

func MultiHandler

func MultiHandler(hs ...Handler) Handler

A MultiHandler dispatches any write to each of its handlers. This is useful for writing different types of log information to different locations. For example, to log to a file and standard error:

log.MultiHandler(
    log.Must.FileHandler("/var/log/app.log", log.LogfmtFormat()),
    log.StderrHandler)

func NetHandler

func NetHandler(network, addr string, fmtr Format) (Handler, error)

NetHandler opens a socket to the given address and writes records over the connection.

func StreamHandler

func StreamHandler(wr io.Writer, fmtr Format) Handler

StreamHandler writes log records to an io.Writer with the given format. StreamHandler can be used to easily begin writing log records to other outputs.

StreamHandler wraps itself with LazyHandler and SyncHandler to evaluate Lazy objects and perform safe concurrent writes.

func SyncHandler

func SyncHandler(h Handler) Handler

SyncHandler can be wrapped around a handler to guarantee that only a single Log operation can proceed at a time. It's necessary for thread-safe concurrent writes.

type Lazy

type Lazy struct {
	Fn interface{}
}

Lazy allows you to defer calculation of a logged value that is expensive to compute until it is certain that it must be evaluated with the given filters.

Lazy may also be used in conjunction with a Logger's New() function to generate a child logger which always reports the current value of changing state.

You may wrap any function which takes no arguments to Lazy. It may return any number of values of any type.

type Level

type Level int

Level 日志级别

func GetLogLevel

func GetLogLevel() Level

func (Level) String

func (l Level) String() string

Returns the name of a Level

type Logger

type Logger interface {
	// New returns a new Logger that has this logger's context plus the given context
	New(keyValues ...interface{}) Logger

	// GetHandler gets the handler associated with the logger.
	GetHandler() Handler

	// SetHandler updates the logger to write records to the specified handler.
	SetHandler(h Handler)

	// Set level value. only level below this can be output
	SetOutLevel(l Level)
	GetOutLevel() Level

	// Log a message at the given level with context key/value pairs
	Log(msg string, fields ...interface{})
	Debug(msg string, fields ...interface{})
	Info(msg string, fields ...interface{})
	Warn(msg string, fields ...interface{})
	Error(msg string, fields ...interface{})
	Fatal(msg string, fields ...interface{})

	// LogContext a message at the given level with context key/value pairs
	LogContext(ctx context.Context, msg string, fields ...interface{})
	DebugContext(ctx context.Context, msg string, fields ...interface{})
	InfoContext(ctx context.Context, msg string, fields ...interface{})
	WarnContext(ctx context.Context, msg string, fields ...interface{})
	ErrorContext(ctx context.Context, msg string, fields ...interface{})
	FatalContext(ctx context.Context, msg string, fields ...interface{})
}

A Logger writes key/value pairs to a Handler

func New

func New(keyValues ...interface{}) Logger

New returns a new logger with the given keyValues. New is a convenient alias for Root().New

func Root

func Root() Logger

Root returns the root logger

type Record

type Record struct {
	Time         time.Time
	Level        Level
	Msg          string
	KeyValues    []interface{}
	Ctx          context.Context
	Call         stack.Call
	CustomCaller string
	KeyNames     RecordKeyNames
}

A Record is what a Logger asks its handler to write

type RecordKeyNames

type RecordKeyNames struct {
	Time      string
	Msg       string
	Level     string
	Call      string
	RequestID string
}

RecordKeyNames 日志记录规则字段名

type RotateOptions

type RotateOptions func(*rotateOptions)

func SetCompress

func SetCompress(doesCompress bool) RotateOptions

func SetDayRotate

func SetDayRotate(dayrorate bool) RotateOptions

func SetMaxBackup

func SetMaxBackup(backup int) RotateOptions

func SetMaxSaveDay

func SetMaxSaveDay(day int) RotateOptions

func SetMaxSize

func SetMaxSize(max int) RotateOptions

func SetOutput

func SetOutput(output *lumberjack.Logger) RotateOptions

Directories

Path Synopsis
Package lumberjack provides a rolling logger.
Package lumberjack provides a rolling logger.

Jump to

Keyboard shortcuts

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