log

package
v0.4.3 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2023 License: MIT Imports: 20 Imported by: 26

Documentation

Index

Constants

View Source
const (
	StacktraceKey = "stacktrace"
	CallerSkip    = 1

	TraceIDKey = "trace_id"

	ComponentKey      = "component"
	WebComponentName  = "web"
	GrpcComponentName = "grpc"
)

Variables

View Source
var (
	GetLoggerWithCtx = func(ctx context.Context, l *Logger) *LoggerWithCtx {
		lc := loggerWithCtxPool.Get().(*LoggerWithCtx)
		lc.ctx = ctx
		lc.l = l
		return lc
	}
	PutLoggerWithCtx = func(lc *LoggerWithCtx) {
		lc.ctx = nil
		lc.l = nil
		loggerWithCtxPool.Put(lc)
	}
)

loggerWithCtxPool

Functions

func AppendToIncomingContext added in v0.1.0

func AppendToIncomingContext(ctx context.Context, fields ...zap.Field)

AppendToIncomingContext appends zap field to context logger

func DPanic

func DPanic(args ...any)

DPanic uses fmt.Sprint to construct and log a message. In development, the logger then panics. (See DPanicLevel for details.)

func DPanicf

func DPanicf(template string, args ...any)

DPanicf uses fmt.Sprintf to log a templated message. In development, the logger then panics. (See DPanicLevel for details.)

func Debug

func Debug(args ...any)

Debug uses fmt.Sprint to construct and log a message.

func Debugf

func Debugf(template string, args ...any)

Debugf uses fmt.Sprintf to log a templated message.

func DefaultTimeEncoder added in v0.0.3

func DefaultTimeEncoder(t time.Time, enc zapcore.PrimitiveArrayEncoder)

DefaultTimeEncoder serializes time.Time to a human-readable formatted string

func Error

func Error(args ...any)

Error uses fmt.Sprint to construct and log a message.

func Errorf

func Errorf(template string, args ...any)

Errorf uses fmt.Sprintf to log a templated message.

func Fatal

func Fatal(args ...any)

Fatal uses fmt.Sprint to construct and log a message, then calls os.Exit.

func Fatalf

func Fatalf(template string, args ...any)

Fatalf uses fmt.Sprintf to log a templated message, then calls os.Exit.

func Info

func Info(args ...any)

Info uses fmt.Sprint to construct and log a message.

func Infof

func Infof(template string, args ...any)

Infof uses fmt.Sprintf to log a templated message.

func NewIncomingContext added in v0.1.0

func NewIncomingContext(ctx context.Context, carrier *FieldCarrier, fields ...zap.Field) context.Context

NewIncomingContext creates a new context with logger carrier.

func Panic

func Panic(args ...any)

Panic uses fmt.Sprint to construct and log a message, then panics.

func Panicf

func Panicf(template string, args ...any)

Panicf uses fmt.Sprintf to log a templated message, then panics.

func PrintLogo()

func Printf added in v0.3.0

func Printf(format string, v ...any)

Printf wrapper native log.Printf

func Println added in v0.3.0

func Println(v ...any)

Println wrapper native log.Println

func ShortCallerEncoder added in v0.0.3

func ShortCallerEncoder(caller zapcore.EntryCaller, enc zapcore.PrimitiveArrayEncoder)

ShortCallerEncoder serializes a caller in file:line format.

func Sync added in v0.0.3

func Sync() error

Sync calls the underlying Core's Sync method, flushing any buffered log entries. Applications should take care to call Sync before exiting.

func Warn

func Warn(args ...any)

Warn uses fmt.Sprint to construct and log a message.

func Warnf

func Warnf(template string, args ...any)

Warnf uses fmt.Sprintf to log a templated message.

Types

type ComponentLogger added in v0.0.3

type ComponentLogger interface {
	// Logger return component's logger and init it if not exist.
	// The logger will be lazy init before logger SetLogger or use AsGlobal,
	// so you can call Logger() to init yourself in some scene,it will use global logger by default.
	// Notice GetComponentLoggerOption
	//   if you want to get the original logger, you can use WithOriginalLogger() option.
	//   If you want to get the logger with context, you can use WithContextLogger() option.
	//   otherwise, you will get the logger with build in fields.
	Logger(opts ...GetComponentLoggerOption) *Logger
	SetLogger(logger *Logger)
	Debug(msg string, fields ...zap.Field)
	Info(msg string, fields ...zap.Field)
	Warn(msg string, fields ...zap.Field)
	Error(msg string, fields ...zap.Field)
	DPanic(msg string, fields ...zap.Field)
	Panic(msg string, fields ...zap.Field)
	Fatal(msg string, fields ...zap.Field)
	Ctx(ctx context.Context) *LoggerWithCtx
}

ComponentLogger is sample and base using for component that also carries a context.Context. It uses the global logger.

func Component added in v0.0.3

func Component(name string, fields ...zap.Field) ComponentLogger

Component return a logger with name option base on a logger.

The logger will be lazy set up,Using the global logger by default.

func Global

func Global() ComponentLogger

Global return struct logger if you want to use zap style logging.

type Config

type Config struct {
	// ZapConfigs is for initial zap multi core
	ZapConfigs []zap.Config `json:"cores" yaml:"cores"`
	// Rotate is for log rotate
	Rotate *rotate `json:"rotate" yaml:"rotate"`
	// DisableSampling disables sampling for all the loggers
	DisableSampling bool `json:"disableSampling" yaml:"disableSampling"`
	// Disable automatic timestamps in output if use TextEncoder
	DisableTimestamp bool `json:"disableTimestamp" yaml:"disableTimestamp"`
	// DisableErrorVerbose stops annotating logs with the full verbose error
	// message.
	DisableErrorVerbose bool `json:"disableErrorVerbose" yaml:"disableErrorVerbose"`
	// WithTraceID configures the logger to add `trace_id` field to structured log messages.
	WithTraceID bool `json:"withTraceID" yaml:"withTraceID"`
	// TraceIDKey is the key used to store the trace ID. defaults to "trace_id".
	TraceIDKey string `json:"traceIDKey" yaml:"traceIDKey"`
	// contains filtered or unexported fields
}

Config is logger schema ZapConfigs use as zap advance,such as zapcore.NewTee() Sole use as one zap logger core

func NewConfig

func NewConfig(cnf *conf.Configuration) (*Config, error)

NewConfig return a Config instance

func (*Config) BuildZap

func (c *Config) BuildZap(opts ...zap.Option) (zl *zap.Logger, err error)

BuildZap build a zap.Logger by Config

type ContextLogger added in v0.1.0

type ContextLogger interface {
	// LogFields defined how to log field with context
	LogFields(logger *Logger, ctx context.Context, lvl zapcore.Level, msg string, fields []zap.Field)
}

ContextLogger is functions to help ContextLogger logging,the functions are called each ComponentLogger call the logging method

type DefaultContextLogger added in v0.1.0

type DefaultContextLogger struct {
}

DefaultContextLogger is hold a nothing

func (*DefaultContextLogger) LogFields added in v0.1.0

func (n *DefaultContextLogger) LogFields(log *Logger, _ context.Context, lvl zapcore.Level, msg string, fields []zap.Field)

type FieldCarrier added in v0.1.0

type FieldCarrier struct {
	Fields []zapcore.Field
}

FieldCarrier sample to carry context log, the carrier's fields will log by demand.

func FromIncomingContext added in v0.1.0

func FromIncomingContext(ctx context.Context) (*FieldCarrier, bool)

FromIncomingContext returns the logger stored in ctx, if any.

func NewCarrier added in v0.1.0

func NewCarrier() *FieldCarrier

NewCarrier create a new logger carrier

type GetComponentLoggerOption added in v0.1.0

type GetComponentLoggerOption func(*GetComponentLoggerOptions)

ComponentLogger is sample and base using for component that also carries a context.Context. It uses the global logger.

func WithContextLogger added in v0.1.0

func WithContextLogger() GetComponentLoggerOption

WithContextLogger returns the logger with context in the ComponentLogger.

func WithOriginalLogger added in v0.1.0

func WithOriginalLogger() GetComponentLoggerOption

WithOriginalLogger returns the original logger in the ComponentLogger.

type GetComponentLoggerOptions added in v0.1.0

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

ComponentLogger is sample and base using for component that also carries a context.Context. It uses the global logger.

type Logger

type Logger struct {
	*zap.Logger
	WithTraceID bool
	TraceIDKey  string
	// contains filtered or unexported fields
}

Logger integrate the Uber Zap library to use in woocoo

if you prefer to golang builtin log style,use log.Info or log.Infof, if zap style,you should use log.Operator().Info() if you want to clone Logger,you can call WithOption WithTraceID indicate whether to add trace_id field to the log.

  • web: from X-Request-Id header
  • grpc: from metadata key "trace_id"

func InitGlobalLogger added in v0.1.0

func InitGlobalLogger() *Logger

func New

func New(zl *zap.Logger) *Logger

New create an Instance from zap

func NewBuiltIn

func NewBuiltIn() *Logger

NewBuiltIn create a logger by configuration path "log", it will be set as global logger but run only once.

func (*Logger) Apply

func (l *Logger) Apply(cfg *conf.Configuration)

Apply implement Configurable interface which can initial from a file used in JSON,YAML Logger init trough Apply method will be set as Global.

func (*Logger) AsGlobal

func (l *Logger) AsGlobal() *Logger

AsGlobal set the Logger as global logger

func (*Logger) ContextLogger added in v0.1.0

func (l *Logger) ContextLogger() ContextLogger

ContextLogger return contextLogger field

func (*Logger) Ctx added in v0.1.0

func (l *Logger) Ctx(ctx context.Context) *LoggerWithCtx

Ctx returns a new logger with the context.

func (*Logger) IOWriter added in v0.4.0

func (l *Logger) IOWriter(level zapcore.Level) io.Writer

IOWriter wrap to Io.Writer which can be used in golang builtin log. Level is the log level which will be written.

func (*Logger) Operator

func (l *Logger) Operator() *zap.Logger

Operator returns the underlying zap logger.

func (*Logger) SetContextLogger added in v0.1.0

func (l *Logger) SetContextLogger(f ContextLogger)

SetContextLogger set contextLogger field,if you use the contextLogger,can set or override it.

func (*Logger) With

func (l *Logger) With(fields ...zap.Field) *Logger

With creates a child logger and adds structured context to it. Fields added to the child don't affect the parent, and vice versa.

func (*Logger) WithOptions added in v0.1.0

func (l *Logger) WithOptions(opts ...zap.Option) *Logger

WithOptions clones the current Logger, applies the supplied Options, and returns the resulting Logger. It's safe to use concurrently.

type LoggerWithCtx added in v0.1.0

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

LoggerWithCtx is a wrapper for Logger that also carries a context.Context.

func NewLoggerWithCtx added in v0.1.0

func NewLoggerWithCtx(ctx context.Context, l *Logger) *LoggerWithCtx

NewLoggerWithCtx get a logger with context from pool

func (*LoggerWithCtx) DPanic added in v0.1.0

func (c *LoggerWithCtx) DPanic(msg string, fields ...zap.Field)

func (*LoggerWithCtx) Debug added in v0.1.0

func (c *LoggerWithCtx) Debug(msg string, fields ...zap.Field)

func (*LoggerWithCtx) Error added in v0.1.0

func (c *LoggerWithCtx) Error(msg string, fields ...zap.Field)

func (*LoggerWithCtx) Fatal added in v0.1.0

func (c *LoggerWithCtx) Fatal(msg string, fields ...zap.Field)

func (*LoggerWithCtx) Info added in v0.1.0

func (c *LoggerWithCtx) Info(msg string, fields ...zap.Field)

func (*LoggerWithCtx) Log added in v0.1.0

func (c *LoggerWithCtx) Log(lvl zapcore.Level, msg string, fields []zap.Field)

func (*LoggerWithCtx) Panic added in v0.1.0

func (c *LoggerWithCtx) Panic(msg string, fields ...zap.Field)

func (*LoggerWithCtx) Warn added in v0.1.0

func (c *LoggerWithCtx) Warn(msg string, fields ...zap.Field)

func (*LoggerWithCtx) WithOptions added in v0.1.0

func (c *LoggerWithCtx) WithOptions(opts ...zap.Option) *LoggerWithCtx

WithOptions reset the logger with options.

type TextEncoder

type TextEncoder struct {
	*zapcore.EncoderConfig
	// contains filtered or unexported fields
}

func NewTextEncoder

func NewTextEncoder(config zapcore.EncoderConfig, disableErrorVerbose, disableTimestamp, needQuotes bool) *TextEncoder

NewTextEncoder creates a fast, low-allocation Text encoder. The encoder appropriately escapes all field keys and values. log format see https://github.com/tikv/rfcs/blob/master/text/0018-unified-log-format.md#log-fields-section. in same scenarios, you can use needQuotes=false to remove quotes if no need followed log-format.

func (*TextEncoder) AddArray

func (enc *TextEncoder) AddArray(key string, arr zapcore.ArrayMarshaler) error

func (*TextEncoder) AddBinary

func (enc *TextEncoder) AddBinary(key string, val []byte)

func (*TextEncoder) AddBool

func (enc *TextEncoder) AddBool(key string, val bool)

func (*TextEncoder) AddByteString

func (enc *TextEncoder) AddByteString(key string, val []byte)

func (*TextEncoder) AddComplex128

func (enc *TextEncoder) AddComplex128(key string, val complex128)

func (*TextEncoder) AddComplex64

func (enc *TextEncoder) AddComplex64(k string, v complex64)

func (*TextEncoder) AddDuration

func (enc *TextEncoder) AddDuration(key string, val time.Duration)

func (*TextEncoder) AddFloat32

func (enc *TextEncoder) AddFloat32(k string, v float32)

func (*TextEncoder) AddFloat64

func (enc *TextEncoder) AddFloat64(key string, val float64)

func (*TextEncoder) AddInt

func (enc *TextEncoder) AddInt(k string, v int)

func (*TextEncoder) AddInt16

func (enc *TextEncoder) AddInt16(k string, v int16)

func (*TextEncoder) AddInt32

func (enc *TextEncoder) AddInt32(k string, v int32)

func (*TextEncoder) AddInt64

func (enc *TextEncoder) AddInt64(key string, val int64)

func (*TextEncoder) AddInt8

func (enc *TextEncoder) AddInt8(k string, v int8)

func (*TextEncoder) AddObject

func (enc *TextEncoder) AddObject(key string, obj zapcore.ObjectMarshaler) error

func (*TextEncoder) AddReflected

func (enc *TextEncoder) AddReflected(key string, obj any) error

func (*TextEncoder) AddString

func (enc *TextEncoder) AddString(key, val string)

func (*TextEncoder) AddTime

func (enc *TextEncoder) AddTime(key string, val time.Time)

func (*TextEncoder) AddUint

func (enc *TextEncoder) AddUint(k string, v uint)

func (*TextEncoder) AddUint16

func (enc *TextEncoder) AddUint16(k string, v uint16)

func (*TextEncoder) AddUint32

func (enc *TextEncoder) AddUint32(k string, v uint32)

func (*TextEncoder) AddUint64

func (enc *TextEncoder) AddUint64(key string, val uint64)

func (*TextEncoder) AddUint8

func (enc *TextEncoder) AddUint8(k string, v uint8)

func (*TextEncoder) AddUintptr

func (enc *TextEncoder) AddUintptr(k string, v uintptr)

func (*TextEncoder) AppendArray

func (enc *TextEncoder) AppendArray(arr zapcore.ArrayMarshaler) error

func (*TextEncoder) AppendBool

func (enc *TextEncoder) AppendBool(val bool)

func (*TextEncoder) AppendByteString

func (enc *TextEncoder) AppendByteString(val []byte)

func (*TextEncoder) AppendComplex128

func (enc *TextEncoder) AppendComplex128(val complex128)

func (*TextEncoder) AppendComplex64

func (enc *TextEncoder) AppendComplex64(v complex64)

func (*TextEncoder) AppendDuration

func (enc *TextEncoder) AppendDuration(val time.Duration)

func (*TextEncoder) AppendFloat32

func (enc *TextEncoder) AppendFloat32(v float32)

func (*TextEncoder) AppendFloat64

func (enc *TextEncoder) AppendFloat64(v float64)

func (*TextEncoder) AppendInt

func (enc *TextEncoder) AppendInt(v int)

func (*TextEncoder) AppendInt16

func (enc *TextEncoder) AppendInt16(v int16)

func (*TextEncoder) AppendInt32

func (enc *TextEncoder) AppendInt32(v int32)

func (*TextEncoder) AppendInt64

func (enc *TextEncoder) AppendInt64(val int64)

func (*TextEncoder) AppendInt8

func (enc *TextEncoder) AppendInt8(v int8)

func (*TextEncoder) AppendObject

func (enc *TextEncoder) AppendObject(obj zapcore.ObjectMarshaler) error

func (*TextEncoder) AppendReflected

func (enc *TextEncoder) AppendReflected(val any) error

func (*TextEncoder) AppendString

func (enc *TextEncoder) AppendString(val string)

func (*TextEncoder) AppendTime

func (enc *TextEncoder) AppendTime(val time.Time)

func (*TextEncoder) AppendUint

func (enc *TextEncoder) AppendUint(v uint)

func (*TextEncoder) AppendUint16

func (enc *TextEncoder) AppendUint16(v uint16)

func (*TextEncoder) AppendUint32

func (enc *TextEncoder) AppendUint32(v uint32)

func (*TextEncoder) AppendUint64

func (enc *TextEncoder) AppendUint64(val uint64)

func (*TextEncoder) AppendUint8

func (enc *TextEncoder) AppendUint8(v uint8)

func (*TextEncoder) AppendUintptr

func (enc *TextEncoder) AppendUintptr(v uintptr)

func (*TextEncoder) Clone

func (enc *TextEncoder) Clone() zapcore.Encoder

func (*TextEncoder) EncodeEntry

func (enc *TextEncoder) EncodeEntry(ent zapcore.Entry, fields []zapcore.Field) (*buffer.Buffer, error)

func (*TextEncoder) OpenNamespace

func (enc *TextEncoder) OpenNamespace(key string)

func (*TextEncoder) String added in v0.3.0

func (enc *TextEncoder) String() string

String returns the encoded log message.

func (*TextEncoder) Truncate added in v0.3.0

func (enc *TextEncoder) Truncate()

type Writer added in v0.4.0

type Writer struct {
	Log *zap.Logger

	// Default log level for the messages which can't inspect a level.
	//
	// If unspecified, defaults to Info.
	Level zapcore.Level
	// contains filtered or unexported fields
}

Writer is an io.Writer that writes to the provided Zap logger. It is inspirited zapio.Writer

func (*Writer) Check added in v0.4.0

func (w *Writer) Check(bs []byte) (lvl zapcore.Level, miss bool, msgIndex int)

func (*Writer) Close added in v0.4.0

func (w *Writer) Close() error

func (*Writer) Sync added in v0.4.0

func (w *Writer) Sync() error

Sync flushes buffered data to the logger as a new log entry even if it doesn't contain a newline. This stage use default level.

func (*Writer) Write added in v0.4.0

func (w *Writer) Write(bs []byte) (n int, err error)

Write writes the provided bytes to the underlying logger at the configured log level and returns the length of the bytes.

Write will split the input on newlines and post each line as a new log entry to the logger.

Jump to

Keyboard shortcuts

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