logger

package
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Jun 9, 2023 License: Apache-2.0 Imports: 17 Imported by: 0

README

go 日志模块

基础日志模块,基于 zap 封装

日志级别

// DebugLevel level. Usually only enabled when debugging. Very verbose logging.
DebugLevel = iota + 1
// InfoLevel is the default logging priority.
// General operational entries about what's going on inside the application.
InfoLevel
// WarnLevel level. Non-critical entries that deserve eyes.
WarnLevel
// ErrorLevel level. Logs. Used for errors that should definitely be noted.
ErrorLevel
// FatalLevel level. Logs and then calls `logger.Exit(1)`. highest level of severity.
FatalLevel

低于级别的日志不会输出,高于级别的日志会输出到对应的文件,建议 开发环境 日志级别设置为 DEBUG, 线上环境 日志级别设置为 INFO

简单使用

使用日志的时候注意尽量避免使用 Fatal 级别的日志,虽然提供了,但是不建议使用,使用 Fatal 记录消息后,直接调用 os.Exit(1),这意味着: 在其他 goroutine defer 语句不会被执行; 各种 buffers 不会被 flush,包括日志的; 临时文件或者目录不会被移除; 不要使用 fatal 记录日志,而是向调用者返回错误。如果错误一直持续到 main.main。main.main 那就是在退出之前做处理任何清理操作的正确位置。

日志初始化
logger.InitLogger(New(
    WithBasePath("../logs"),
    WithLevel(DebugLevel),
    WithConsole(true),
    WithFields(map[string]interface{}{
    "app_id":      "mt",
    "instance_id": "JeffreyBool",
    }),
))

上面会覆盖日志默认的行为,因为方便使用,默认调用就会初始化

各种级别日志输出
func TestDebug(t *testing.T) {
	logger.Debug("test debug logger")
	logger.Debugf("debug test time:%d", time.Now().Unix())
	logger.Sync()
}

func TestInfo(t *testing.T) {
	logger.Info("测试日志")
	logger.Infof("name:%s, age:%d", "pandatv", 14)
	logger.Infow("我们都是中国人", "age", 18, "name", "zhanggaoyuan")
    logger.Sync()
}

func TestWarn(t *testing.T) {
	logger.Warn("test warn logger")
	logger.Warnf("warn test time:%d", time.Now().Unix())
    logger.Sync()
}

func TestError(t *testing.T) {
	logger.Error("test error logger")
	logger.Errorf("error test time:%d", time.Now().Unix())
    logger.Sync()
}
日志多实例使用

多实例日志必须设置 WithFilename(xxx) 和普通日志区分,这种日志不需要指定级别,全部会输出到一个文件中

slow := New(
    WithBasePath("../logs"),
    WithConsole(true),
    WithFilename("slow"),
    WithFields(map[string]interface{}{
    "app_id":      "mt",
    "instance_id": "JeffreyBool",
    }),
)

slow.Info(msg)

需要外部自己保存日志的对象信息

注意事项

  • 不要使用 Fatal 级别日志
  • 日志使用完毕后一定要显式调用 Sync() 函数将日志落盘

Documentation

Index

Constants

View Source
const (
	// DebugLevel level. Usually only enabled when debugging. Very verbose logging.
	DebugLevel = iota + 1
	// InfoLevel is the default logging priority.
	// General operational entries about what's going on inside the application.
	InfoLevel
	// WarnLevel level. Non-critical entries that deserve eyes.
	WarnLevel
	// ErrorLevel level. Logs. Used for errors that should definitely be noted.
	ErrorLevel
	// FatalLevel level. Logs and then calls `logger.Exit(1)`. highest level of severity.
	FatalLevel
)
View Source
const (
	MonthlyRolling  RollingFormat = "200601"
	DailyRolling                  = "20060102"
	HourlyRolling                 = "2006010215"
	MinutelyRolling               = "200601021504"
	SecondlyRolling               = "20060102150405"
)

RollingFormats

Variables

View Source
var (
	ErrClosedRollingFile = errors.New("rolling file is closed")
	ErrBuffer            = errors.New("buffer exceeds the limit")
)

Errors

View Source
var (
	// ErrLogPathNotSet is an error that indicates the log path is not set.
	ErrLogPathNotSet = errors.New("log path must be set")
)

Functions

func CopyFields

func CopyFields(fields map[string]interface{}) []zap.Field

func Debug

func Debug(args ...interface{})

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

func Debugf

func Debugf(format string, args ...interface{})

Debugf uses fmt.Sprintf to log a templated message.

func Debugw

func Debugw(msg string, keysAndValues ...interface{})

Debugw logs a message with some additional context. The variadic key-value pairs are treated as they are in With.

When debug-level logging is disabled, this is much faster than

s.With(keysAndValues).Debug(msg)

func Error

func Error(args ...interface{})

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

func Errorf

func Errorf(format string, args ...interface{})

Errorf uses fmt.Sprintf to log a templated message.

func Errorw

func Errorw(msg string, keysAndValues ...interface{})

Errorw logs a message with some additional context. The variadic key-value pairs are treated as they are in With.

func Fatal

func Fatal(args ...interface{})

Fatal uses fmt.Sprint to construct and log a message, then calls os.Exit. Deprecated: 记录消息后,直接调用 os.Exit(1),这意味着: 在其他 goroutine defer 语句不会被执行; 各种 buffers 不会被 flush,包括日志的; 临时文件或者目录不会被移除; 不要使用 fatal 记录日志,而是向调用者返回错误。如果错误一直持续到 main.main。main.main 那就是在退出之前做处理任何清理操作的正确位置。

func Fatalf

func Fatalf(format string, args ...interface{})

Fatalf uses fmt.Sprintf to log a templated message, then calls os.Exit. Deprecated: 记录消息后,直接调用 os.Exit(1),这意味着: 在其他 goroutine defer 语句不会被执行; 各种 buffers 不会被 flush,包括日志的; 临时文件或者目录不会被移除; 不要使用 fatal 记录日志,而是向调用者返回错误。如果错误一直持续到 main.main。main.main 那就是在退出之前做处理任何清理操作的正确位置。

func Fatalw

func Fatalw(msg string, keysAndValues ...interface{})

Fatalw logs a message with some additional context, then calls os.Exit. The variadic key-value pairs are treated as they are in With. Deprecated: 记录消息后,直接调用 os.Exit(1),这意味着: 在其他 goroutine defer 语句不会被执行; 各种 buffers 不会被 flush,包括日志的; 临时文件或者目录不会被移除; 不要使用 fatal 记录日志,而是向调用者返回错误。如果错误一直持续到 main.main。main.main 那就是在退出之前做处理任何清理操作的正确位置。

func Info

func Info(args ...interface{})

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

func Infof

func Infof(format string, args ...interface{})

Infof uses fmt.Sprintf to log a templated message.

func Infow

func Infow(msg string, keysAndValues ...interface{})

Infow logs a message with some additional context. The variadic key-value pairs are treated as they are in With.

func InitLogger

func InitLogger(log Logger)

InitLogger Overriding the default log instance.

func Must

func Must(err error)

Must checks if err is nil, otherwise logs the err and exits.

func SetLevel

func SetLevel(lv Level)

SetLevel set logger level

func Sync

func Sync() error

Sync flushes any buffered log entries.

func Warn

func Warn(args ...interface{})

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

func Warnf

func Warnf(format string, args ...interface{})

Warnf uses fmt.Sprintf to log a templated message.

func Warnw

func Warnw(msg string, keysAndValues ...interface{})

Warnw logs a message with some additional context. The variadic key-value pairs are treated as they are in With.

Types

type Default

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

Default default logger achieve

func New

func New(opts ...Options) *Default

func (*Default) Debug

func (l *Default) Debug(args ...interface{})

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

func (*Default) Debugf

func (l *Default) Debugf(template string, args ...interface{})

Debugf uses fmt.Sprintf to log a templated message.

func (*Default) Debugw

func (l *Default) Debugw(msg string, keysAndValues ...interface{})

Debugw logs a message with some additional context. The variadic key-value pairs are treated as they are in With.

When debug-level logging is disabled, this is much faster than

s.With(keysAndValues).Debug(msg)

func (*Default) Error

func (l *Default) Error(args ...interface{})

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

func (*Default) Errorf

func (l *Default) Errorf(template string, args ...interface{})

Errorf uses fmt.Sprintf to log a templated message.

func (*Default) Errorw

func (l *Default) Errorw(msg string, keysAndValues ...interface{})

Errorw logs a message with some additional context. The variadic key-value pairs are treated as they are in With.

func (*Default) Fatal

func (l *Default) Fatal(args ...interface{})

Fatal uses fmt.Sprint to construct and log a message, then calls os.Exit. Deprecated: 记录消息后,直接调用 os.Exit(1),这意味着: 在其他 goroutine defer 语句不会被执行; 各种 buffers 不会被 flush,包括日志的; 临时文件或者目录不会被移除; 不要使用 fatal 记录日志,而是向调用者返回错误。如果错误一直持续到 main.main。main.main 那就是在退出之前做处理任何清理操作的正确位置。

func (*Default) Fatalf

func (l *Default) Fatalf(template string, args ...interface{})

Fatalf uses fmt.Sprintf to log a templated message, then calls os.Exit. Deprecated: 记录消息后,直接调用 os.Exit(1),这意味着: 在其他 goroutine defer 语句不会被执行; 各种 buffers 不会被 flush,包括日志的; 临时文件或者目录不会被移除; 不要使用 fatal 记录日志,而是向调用者返回错误。如果错误一直持续到 main.main。main.main 那就是在退出之前做处理任何清理操作的正确位置。

func (*Default) Fatalw

func (l *Default) Fatalw(msg string, keysAndValues ...interface{})

Fatalw logs a message with some additional context, then calls os.Exit. The variadic key-value pairs are treated as they are in With. Deprecated: 记录消息后,直接调用 os.Exit(1),这意味着: 在其他 goroutine defer 语句不会被执行; 各种 buffers 不会被 flush,包括日志的; 临时文件或者目录不会被移除; 不要使用 fatal 记录日志,而是向调用者返回错误。如果错误一直持续到 main.main。main.main 那就是在退出之前做处理任何清理操作的正确位置。

func (*Default) Info

func (l *Default) Info(args ...interface{})

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

func (*Default) Infof

func (l *Default) Infof(template string, args ...interface{})

Infof uses fmt.Sprintf to log a templated message.

func (*Default) Infow

func (l *Default) Infow(msg string, keysAndValues ...interface{})

Infow logs a message with some additional context. The variadic key-value pairs are treated as they are in With.

func (*Default) LevelEnablerFunc

func (l *Default) LevelEnablerFunc(level zapcore.Level) LevelEnablerFunc

func (*Default) Log

func (l *Default) Log(level Level, template string, fmtArgs []interface{}, context []interface{})

func (*Default) Options

func (l *Default) Options() Option

Options logger option value.

func (*Default) SetLevel

func (l *Default) SetLevel(lv Level)

func (*Default) StdLog

func (l *Default) StdLog() *std.Logger

func (*Default) Sync

func (l *Default) Sync() error

func (*Default) Warn

func (l *Default) Warn(args ...interface{})

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

func (*Default) Warnf

func (l *Default) Warnf(template string, args ...interface{})

Warnf uses fmt.Sprintf to log a templated message.

func (*Default) Warnw

func (l *Default) Warnw(msg string, keysAndValues ...interface{})

Warnw logs a message with some additional context. The variadic key-value pairs are treated as they are in With.

func (*Default) WithCallDepth

func (l *Default) WithCallDepth(callDepth int) Logger

WithCallDepth with logger call depth.

func (*Default) WithContext

func (l *Default) WithContext(ctx context.Context) Logger

WithContext with context

func (*Default) WithError

func (l *Default) WithError(err error) Logger

WithError with logger error

func (*Default) WithFields

func (l *Default) WithFields(fields map[string]interface{}) Logger

WithFields set fields to always be logged

type Encoder

type Encoder string
const (
	JsonEncoder    Encoder = "json"
	ConsoleEncoder Encoder = "console"
)

func (*Encoder) IsConsole

func (e *Encoder) IsConsole() bool

IsConsole Whether console encoder.

func (*Encoder) IsJson

func (e *Encoder) IsJson() bool

IsJson Whether json encoder.

func (*Encoder) String

func (e *Encoder) String() string

type Level

type Level int8

func ParseLevel

func ParseLevel(s string) Level

ParseLevel parses a level string into a logger Level value.

func (Level) Enabled

func (l Level) Enabled(lvl Level) bool

Enabled returns true if the given level is at or above this level.

func (Level) String

func (l Level) String() string

type LevelEnablerFunc

type LevelEnablerFunc func(zapcore.Level) bool

LevelEnablerFunc is a convenient way to implement zapcore.LevelEnabler with an anonymous function.

It's particularly useful when splitting log output between different outputs (e.g., standard error and standard out). For sample code, see the package-level AdvancedConfiguration example.

func (LevelEnablerFunc) Enabled

func (f LevelEnablerFunc) Enabled(lvl zapcore.Level) bool

Enabled calls the wrapped function.

type Logger

type Logger interface {
	// Options The Logger options
	Options() Option

	// SetLevel set logger level
	SetLevel(lv Level)

	// WithContext with context
	WithContext(ctx context.Context) Logger

	// WithFields set fields to always be logged
	WithFields(fields map[string]interface{}) Logger

	// WithCallDepth  with logger call depth.
	WithCallDepth(callDepth int) Logger

	// WithError with logger error
	WithError(err error) Logger

	// Debug uses fmt.Sprint to construct and log a message.
	Debug(args ...interface{})

	// Info uses fmt.Sprint to construct and log a message.
	Info(args ...interface{})

	// Warn uses fmt.Sprint to construct and log a message.
	Warn(args ...interface{})

	// Error uses fmt.Sprint to construct and log a message.
	Error(args ...interface{})

	// Fatal uses fmt.Sprint to construct and log a message, then calls os.Exit.
	Fatal(args ...interface{})

	// Debugf uses fmt.Sprintf to log a templated message.
	Debugf(template string, args ...interface{})

	// Infof uses fmt.Sprintf to log a templated message.
	Infof(template string, args ...interface{})

	// Warnf uses fmt.Sprintf to log a templated message.
	Warnf(template string, args ...interface{})

	// Errorf uses fmt.Sprintf to log a templated message.
	Errorf(template string, args ...interface{})

	// Fatalf uses fmt.Sprintf to log a templated message, then calls os.Exit.
	Fatalf(template string, args ...interface{})

	// Debugw logs a message with some additional context. The variadic key-value
	// pairs are treated as they are in With.
	//
	// When debug-level logging is disabled, this is much faster than
	//  s.With(keysAndValues).Debug(msg)
	Debugw(msg string, keysAndValues ...interface{})

	// Infow logs a message with some additional context. The variadic key-value
	// pairs are treated as they are in With.
	Infow(msg string, keysAndValues ...interface{})

	// Warnw logs a message with some additional context. The variadic key-value
	// pairs are treated as they are in With.
	Warnw(msg string, keysAndValues ...interface{})

	// Errorw logs a message with some additional context. The variadic key-value
	// pairs are treated as they are in With.
	Errorw(msg string, keysAndValues ...interface{})

	// Fatalw logs a message with some additional context, then calls os.Exit. The
	// variadic key-value pairs are treated as they are in With.
	Fatalw(msg string, keysAndValues ...interface{})

	// Log writes a log entry
	Log(level Level, template string, fmtArgs []interface{}, context []interface{})

	StdLog() *std.Logger

	// Sync logger sync
	Sync() error
}
var DefaultLogger Logger = New()

DefaultLogger is default logger.

func InitDefaultLogger

func InitDefaultLogger() Logger

func WithContext

func WithContext(ctx context.Context) Logger

WithContext returns a shallow copy of l with its context changed to ctx. The provided ctx must be non-nil.

type Option

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

func (Option) Level

func (o Option) Level() Level

Level Get log level.

type Options

type Options func(o *Option)

func WithBasePath

func WithBasePath(path string) Options

WithBasePath set base path.

func WithCallerSkip

func WithCallerSkip(skip int) Options

WithCallerSkip increases the number of callers skipped by caller annotation (as enabled by the AddCaller option). When building wrappers around the Logger and SugaredLogger, supplying this Option prevents base from always reporting the wrapper code as the caller.

func WithConsole

func WithConsole(enableConsole bool) Options

WithConsole enable console.

func WithDisableDisk

func WithDisableDisk(disableDisk bool) Options

WithDisableDisk disable disk.

func WithEncoder

func WithEncoder(encoder Encoder) Options

WithEncoder set logger Encoder

func WithEncoderConfig

func WithEncoderConfig(encoderConfig zapcore.EncoderConfig) Options

WithEncoderConfig set logger encoderConfig

func WithFields

func WithFields(fields map[string]interface{}) Options

WithFields set default fields for the logger

func WithFilename

func WithFilename(filename string) Options

WithFilename Logger filename.

func WithLevel

func WithLevel(lv Level) Options

WithLevel set base path.

func WithNamespace

func WithNamespace(name string) Options

WithNamespace creates a named, isolated scope within the logger's context. All subsequent fields will be added to the new namespace.

This helps prevent key collisions when injecting loggers into sub-components or third-party libraries.

type RollingFile

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

RollingFile : Defination of rolling

func NewRollingFile

func NewRollingFile(basePath string, rolling RollingFormat) (*RollingFile, error)

NewRollingFile create new rolling

func (*RollingFile) Close

func (r *RollingFile) Close() error

Close syncer file

func (*RollingFile) SetRolling

func (r *RollingFile) SetRolling(fmt RollingFormat)

SetRolling : Set rolling format

func (*RollingFile) Sync

func (r *RollingFile) Sync() error

Sync buffered data to writer

func (*RollingFile) Write

func (r *RollingFile) Write(b []byte) (n int, err error)

type RollingFormat

type RollingFormat string

RollingFormat : Type hinting

Jump to

Keyboard shortcuts

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