log4go

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Aug 31, 2022 License: MIT Imports: 11 Imported by: 0

README

log4go

logging in Go, based on zap.

Installation

go get github.com/rumis/log4go

Note that log4go only supports the two most recent minor versions of Go, Because of zap.

Quick Start

ctx := context.TODO()
consoleLogger := log4go.NewConsoleLogger()
log4go.SetDefaultLogger(consoleLogger)
defer log4go.Sync(ctx)
log4go.Info(ctx, "failed to fetch URL",
    log4go.String("url",url),
    log4go.Int("attempt", 3),
    log4go.Duration("backoff", time.Second))

See the documentation for more details.


Released under the MIT License.

Documentation

Index

Constants

View Source
const (
	// UnknownType is the default field type. Attempting to add it to an encoder will panic.
	UnknownType = zapcore.UnknownType
	// BoolType indicates that the field carries a bool.
	BoolType = zapcore.BoolType
	// ByteStringType indicates that the field carries UTF-8 encoded bytes.
	ByteStringType = zapcore.ByteStringType
	// DurationType indicates that the field carries a time.Duration.
	DurationType = zapcore.DurationType
	// Float64Type indicates that the field carries a float64.
	Float64Type = zapcore.Float64Type
	// Int64Type indicates that the field carries an int64.
	Int64Type = zapcore.Int64Type
	// StringType indicates that the field carries a string.
	StringType = zapcore.StringType
	TimeType   = zapcore.TimeType
	// TimeFullType indicates that the field carries a time.Time stored as-is.
	TimeFullType = zapcore.TimeFullType
	// Uint64Type indicates that the field carries a uint64.
	Uint64Type = zapcore.Uint64Type
	// ErrorType indicates that the field carries an error.
	ErrorType = zapcore.ErrorType
)
View Source
const (
	// DebugLevel logs are typically voluminous, and are usually disabled in
	// production.
	DebugLevel = zapcore.DebugLevel
	// InfoLevel is the default logging priority.
	InfoLevel = zapcore.InfoLevel
	// WarnLevel logs are more important than Info, but don't need individual
	// human review.
	WarnLevel = zapcore.WarnLevel
	// ErrorLevel logs are high-priority. If an application is running smoothly,
	// it shouldn't generate any error-level logs.
	ErrorLevel = zapcore.ErrorLevel
	// PanicLevel logs a message, then panics.
	PanicLevel = zapcore.PanicLevel
	// FatalLevel logs a message, then calls os.Exit(1).
	FatalLevel = zapcore.FatalLevel
)

Variables

View Source
var ContextFieldsKey = ContextField{}

ContextFieldsKey key of context extend fields

Functions

func Debug

func Debug(ctx context.Context, msg string, fields ...Field)

Debug logs a message at DebugLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

func Error

func Error(ctx context.Context, msg string, fields ...Field)

Error logs a message at ErrorLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

func Fatal

func Fatal(ctx context.Context, msg string, fields ...Field)

Fatal logs a message at FatalLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

The logger then calls os.Exit(1), even if logging at FatalLevel is disabled.

func FieldsConvert

func FieldsConvert(fields []Field) []zapcore.Field

FieldsConvert convert Field to zapcore.Field

func FullCallerEncoder

func FullCallerEncoder(caller EntryCaller, enc PrimitiveArrayEncoder)

FullCallerEncoder serializes a caller in /full/path/to/package/file:line format.

func FullNameEncoder

func FullNameEncoder(loggerName string, enc PrimitiveArrayEncoder)

FullNameEncoder serializes the logger name as-is.

func Info

func Info(ctx context.Context, msg string, fields ...Field)

Info logs a message at InfoLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

func LowercaseLevelEncoder

func LowercaseLevelEncoder(l Level, enc PrimitiveArrayEncoder)

LowercaseLevelEncoder serializes a Level to a lowercase string. For example, InfoLevel is serialized to "info".

func MillisDurationEncoder

func MillisDurationEncoder(d time.Duration, enc PrimitiveArrayEncoder)

MillisDurationEncoder serializes a time.Duration to an integer number of milliseconds elapsed.

func Panic

func Panic(ctx context.Context, msg string, fields ...Field)

Panic logs a message at PanicLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

The logger then panics, even if logging at PanicLevel is disabled.

func SetDefaultLogger

func SetDefaultLogger(dlog Logger)

SetDefaultLogger 设置默认Logger

func SetLogger

func SetLogger(name string, log Logger)

SetLogger set logger

func Sync

func Sync(ctx context.Context)

Sync flushing any buffered log entries.

Applications should take care to call Sync before exiting.

func Warn

func Warn(ctx context.Context, msg string, fields ...Field)

Warn logs a message at WarnLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

Types

type CallerEncoder

type CallerEncoder func(EntryCaller, PrimitiveArrayEncoder)

A CallerEncoder serializes an EntryCaller to a primitive type.

type ConsoleLogger

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

ConsoleLogger console logger base on zap

func NewConsoleLogger

func NewConsoleLogger(oh ...OptionHandler) *ConsoleLogger

NewConsoleLogger create a new ConsoleLogger

func (*ConsoleLogger) Debug

func (c *ConsoleLogger) Debug(ctx context.Context, msg string, fields ...Field)

Debug logs a message at DebugLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

func (*ConsoleLogger) Error

func (c *ConsoleLogger) Error(ctx context.Context, msg string, fields ...Field)

Error logs a message at ErrorLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

func (*ConsoleLogger) Fatal

func (c *ConsoleLogger) Fatal(ctx context.Context, msg string, fields ...Field)

Fatal logs a message at FatalLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

The logger then calls os.Exit(1), even if logging at FatalLevel is disabled.

func (*ConsoleLogger) Info

func (c *ConsoleLogger) Info(ctx context.Context, msg string, fields ...Field)

Info logs a message at InfoLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

func (*ConsoleLogger) Log

func (c *ConsoleLogger) Log(ctx context.Context, lvl Level, msg string, fields ...Field)

Log logs a message at the specified level. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

func (*ConsoleLogger) Panic

func (c *ConsoleLogger) Panic(ctx context.Context, msg string, fields ...Field)

Panic logs a message at PanicLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

The logger then panics, even if logging at PanicLevel is disabled.

func (*ConsoleLogger) Sync

func (c *ConsoleLogger) Sync(ctx context.Context)

Sync flushing any buffered log entries.

Applications should take care to call Sync before exiting.

func (*ConsoleLogger) Warn

func (c *ConsoleLogger) Warn(ctx context.Context, msg string, fields ...Field)

Warn logs a message at WarnLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

type ContextField

type ContextField struct{}

type DurationEncoder

type DurationEncoder func(time.Duration, PrimitiveArrayEncoder)

A DurationEncoder serializes a time.Duration to a primitive type.

type EntryCaller

type EntryCaller zapcore.EntryCaller

type Field

type Field zapcore.Field

func Bool

func Bool(key string, val bool) Field

Bool constructs a field that carries a bool.

func ByteString

func ByteString(key string, val []byte) Field

ByteString constructs a field that carries UTF-8 encoded text as a []byte. To log opaque binary blobs (which aren't necessarily valid UTF-8), use Binary.

func Duration

func Duration(key string, val time.Duration) Field

Duration constructs a field with the given key and value. The encoder controls how the duration is serialized.

func Float64

func Float64(key string, val float64) Field

Float64 constructs a field that carries a float64. The way the floating-point value is represented is encoder-dependent, so marshaling is necessarily lazy.

func Int

func Int(key string, val int) Field

Int constructs a field with the given key and value.

func Int64

func Int64(key string, val int64) Field

Int64 constructs a field with the given key and value.

func String

func String(key string, val string) Field

String constructs a field with the given key and value.

func Time

func Time(key string, val time.Time) Field

Time constructs a Field with the given key and value. The encoder controls how the time is serialized.

func Uint

func Uint(key string, val uint) Field

Uint constructs a field with the given key and value.

func Uint64

func Uint64(key string, val uint64) Field

Uint64 constructs a field with the given key and value.

type Fields

type Fields []zapcore.Field

type FileLogger

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

FileLogger file log base zap

func NewFileLogger

func NewFileLogger(oh ...OptionHandler) *FileLogger

NewFileLogger create new file logger

func (*FileLogger) Debug

func (f *FileLogger) Debug(ctx context.Context, msg string, fields ...Field)

Debug logs a message at DebugLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

func (*FileLogger) Error

func (f *FileLogger) Error(ctx context.Context, msg string, fields ...Field)

Error logs a message at ErrorLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

func (*FileLogger) Fatal

func (f *FileLogger) Fatal(ctx context.Context, msg string, fields ...Field)

Fatal logs a message at FatalLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

The logger then calls os.Exit(1), even if logging at FatalLevel is disabled.

func (*FileLogger) Info

func (f *FileLogger) Info(ctx context.Context, msg string, fields ...Field)

Info logs a message at InfoLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

func (*FileLogger) Log

func (f *FileLogger) Log(ctx context.Context, lvl Level, msg string, fields ...Field)

Log logs a message at the specified level. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

func (*FileLogger) Panic

func (f *FileLogger) Panic(ctx context.Context, msg string, fields ...Field)

Panic logs a message at PanicLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

The logger then panics, even if logging at PanicLevel is disabled.

func (*FileLogger) Sync

func (f *FileLogger) Sync(ctx context.Context)

Sync flushing any buffered log entries.

Applications should take care to call Sync before exiting.

func (*FileLogger) Warn

func (f *FileLogger) Warn(ctx context.Context, msg string, fields ...Field)

Warn logs a message at WarnLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

type GroupLogger

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

GroupLogger multi logger

func NewGroupLogger

func NewGroupLogger(logger ...Logger) *GroupLogger

NewGroupLogger new multi logger

func (*GroupLogger) Debug

func (g *GroupLogger) Debug(ctx context.Context, msg string, fields ...Field)

Debug logs a message at DebugLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

func (*GroupLogger) Error

func (g *GroupLogger) Error(ctx context.Context, msg string, fields ...Field)

Error logs a message at ErrorLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

func (*GroupLogger) Fatal

func (g *GroupLogger) Fatal(ctx context.Context, msg string, fields ...Field)

Fatal logs a message at FatalLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

The logger then calls os.Exit(1), even if logging at FatalLevel is disabled.

func (*GroupLogger) Info

func (g *GroupLogger) Info(ctx context.Context, msg string, fields ...Field)

Info logs a message at InfoLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

func (*GroupLogger) Panic

func (g *GroupLogger) Panic(ctx context.Context, msg string, fields ...Field)

Panic logs a message at PanicLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

The logger then panics, even if logging at PanicLevel is disabled.

func (*GroupLogger) Sync

func (g *GroupLogger) Sync(ctx context.Context)

Sync flushing any buffered log entries.

Applications should take care to call Sync before exiting.

func (*GroupLogger) Warn

func (g *GroupLogger) Warn(ctx context.Context, msg string, fields ...Field)

Warn logs a message at WarnLevel. The message includes any fields passed at the log site, as well as any fields accumulated on the logger.

type Level

type Level = zapcore.Level

type LevelEncoder

type LevelEncoder func(Level, PrimitiveArrayEncoder)

A LevelEncoder serializes a Level to a primitive type.

type Logger

type Logger interface {
	// Info logs a message at InfoLevel. The message includes any fields passed
	// at the log site, as well as any fields accumulated on the logger.
	Info(ctx context.Context, msg string, fields ...Field)

	// Debug logs a message at DebugLevel. The message includes any fields passed
	// at the log site, as well as any fields accumulated on the logger.
	Debug(ctx context.Context, msg string, fields ...Field)

	// Warn logs a message at WarnLevel. The message includes any fields passed
	// at the log site, as well as any fields accumulated on the logger.
	Warn(ctx context.Context, msg string, fields ...Field)

	// Error logs a message at ErrorLevel. The message includes any fields passed
	// at the log site, as well as any fields accumulated on the logger.
	Error(ctx context.Context, msg string, fields ...Field)

	// Panic logs a message at PanicLevel. The message includes any fields passed
	// at the log site, as well as any fields accumulated on the logger.
	//
	// The logger then panics, even if logging at PanicLevel is disabled.
	Panic(ctx context.Context, msg string, fields ...Field)

	// Fatal logs a message at FatalLevel. The message includes any fields passed
	// at the log site, as well as any fields accumulated on the logger.
	//
	// The logger then calls os.Exit(1), even if logging at FatalLevel is
	// disabled.
	Fatal(ctx context.Context, msg string, fields ...Field)

	// Sync flushing any buffered log entries.
	//
	// Applications should take care to call Sync before exiting.
	Sync(ctx context.Context)
}

Logger logger

func GetLogger

func GetLogger(name string) Logger

GetLogger get Logger

type NameEncoder

type NameEncoder func(string, PrimitiveArrayEncoder)

A NameEncoder serializes a period-separated logger name to a primitive type.

type OptionHandler

type OptionHandler func(opt *Options)

func WithCaller

func WithCaller(caller bool) OptionHandler

func WithCallerEncoder

func WithCallerEncoder(enc CallerEncoder) OptionHandler

func WithCallerKey

func WithCallerKey(key string) OptionHandler

func WithCompress

func WithCompress(compress bool) OptionHandler

func WithConsoleSeparator

func WithConsoleSeparator(sep string) OptionHandler

func WithDurationEncoder

func WithDurationEncoder(enc DurationEncoder) OptionHandler

func WithExtendFields

func WithExtendFields(fields ...Field) OptionHandler

func WithFileName

func WithFileName(filepath string) OptionHandler

func WithFunctionKey

func WithFunctionKey(key string) OptionHandler

func WithLevel

func WithLevel(level string) OptionHandler

func WithLevelEncoder

func WithLevelEncoder(enc LevelEncoder) OptionHandler

func WithLevelKey

func WithLevelKey(key string) OptionHandler

func WithLineEnding

func WithLineEnding(end string) OptionHandler

func WithLocalTime

func WithLocalTime(lc bool) OptionHandler

func WithMaxAge

func WithMaxAge(age int) OptionHandler

func WithMaxBackups

func WithMaxBackups(maxb int) OptionHandler

func WithMaxSize

func WithMaxSize(size int) OptionHandler

func WithMessageKey

func WithMessageKey(key string) OptionHandler

func WithNameEncoder

func WithNameEncoder(enc NameEncoder) OptionHandler

func WithNameKey

func WithNameKey(key string) OptionHandler

func WithReflectedEncoder

func WithReflectedEncoder(fn func(io.Writer) ReflectedEncoder) OptionHandler

func WithSkipLineEnding

func WithSkipLineEnding(skip bool) OptionHandler

func WithStack

func WithStack(stack bool) OptionHandler

func WithStacktraceKey

func WithStacktraceKey(key string) OptionHandler

func WithTimeEncoder

func WithTimeEncoder(enc TimeEncoder) OptionHandler

func WithTimeKey

func WithTimeKey(key string) OptionHandler

type Options

type Options struct {
	MessageKey     string
	LevelKey       string
	TimeKey        string
	NameKey        string
	CallerKey      string
	FunctionKey    string
	StacktraceKey  string
	SkipLineEnding bool
	LineEnding     string
	// Configure the primitive representations of common complex types. For
	// example, some users may want all time.Times serialized as floating-point
	// seconds since epoch, while others may prefer ISO8601 strings.
	EncodeLevel    LevelEncoder
	EncodeTime     TimeEncoder
	EncodeDuration DurationEncoder
	EncodeCaller   CallerEncoder

	// Unlike the other primitive type encoders, EncodeName is optional. The
	// zero value falls back to FullNameEncoder.
	EncodeName NameEncoder

	// Configure the encoder for interface{} type objects.
	// If not provided, objects are encoded using json.Encoder
	NewReflectedEncoder func(io.Writer) ReflectedEncoder

	// Configures the field separator used by the console encoder. Defaults
	// to tab.
	ConsoleSeparator string

	// Level level
	Level Level

	// WithStack configures the Logger to record a stack trace for all messages at
	// or above a given level.
	WithStack bool

	// WithCaller configures the Logger to annotate each message with the filename,
	// line number, and function name of caller.
	WithCaller bool

	// Filename is the file to write logs to.  Backup log files will be retained
	// in the same directory.  It uses <processname>-lumberjack.log in
	// os.TempDir() if empty.
	Filename string

	// MaxSize is the maximum size in megabytes of the log file before it gets
	// rotated. It defaults to 100 megabytes.
	MaxSize int

	// MaxAge is the maximum number of days to retain old log files based on the
	// timestamp encoded in their filename.  Note that a day is defined as 24
	// hours and may not exactly correspond to calendar days due to daylight
	// savings, leap seconds, etc. The default is not to remove old log files
	// based on age.
	MaxAge int

	// MaxBackups is the maximum number of old log files to retain.  The default
	// is to retain all old log files (though MaxAge may still cause them to get
	// deleted.)
	MaxBackups int

	// LocalTime determines if the time used for formatting the timestamps in
	// backup files is the computer's local time.  The default is to use UTC
	// time.
	LocalTime bool

	// Compress determines if the rotated log files should be compressed
	// using gzip. The default is not to perform compression.
	Compress bool

	// ExtFields configures the Logger to annotate each message with the extend fields.
	ExtFields []Field
}

func DefaultOption

func DefaultOption() Options

DefaultOption default options

type PrimitiveArrayEncoder

type PrimitiveArrayEncoder zapcore.PrimitiveArrayEncoder

PrimitiveArrayEncoder is the subset of the ArrayEncoder interface that deals only in Go's built-in types. It's included only so that Duration- and TimeEncoders cannot trigger infinite recursion.

type ReflectedEncoder

type ReflectedEncoder interface {
	// Encode encodes and writes to the underlying data stream.
	Encode(interface{}) error
}

ReflectedEncoder serializes log fields that can't be serialized with Zap's JSON encoder. These have the ReflectType field type. Use EncoderConfig.NewReflectedEncoder to set this.

func DefaultReflectedEncoder

func DefaultReflectedEncoder(w io.Writer) ReflectedEncoder

DefaultReflectedEncoder serializes the log in json

type TimeEncoder

type TimeEncoder func(time.Time, PrimitiveArrayEncoder)

A TimeEncoder serializes a time.Time to a primitive type.

func StandTimeEncoder

func StandTimeEncoder() TimeEncoder

StandTimeEncoder return TimeEncoder wich serializes a time.Time using layout 2006-01-02 15:04:05

func TimeEncoderOfLayout

func TimeEncoderOfLayout(layout string) TimeEncoder

TimeEncoderOfLayout returns TimeEncoder which serializes a time.Time using given layout.

Jump to

Keyboard shortcuts

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