logger

package
v2.0.0 Latest Latest
Warning

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

Go to latest
Published: Apr 22, 2026 License: MIT Imports: 18 Imported by: 0

README

Zap Logger Wrapper

本封装提供一个基本的 zap logger 封装,其目的在于统一部分项目之间的日志形式。

基本使用

在具体模块中使用
package abc

import (
	"github.com/GuanceCloud/cliutils/logger"
)

var (
	// 最好在模块中将 log 初始化一下,这样比较保险
	log = logger.DefaultSLogger("abc")
)

// 模块初始化
func Init() {
	log = logger.SLogger("abc")
}

func foo() {
	log.Debug("this is debug message")
	log.Infof("this is info message from %d", 1024)
}
在项目中使用

一般而言,我在项目中使用,需要初始化一个 root-logger,该 root-logger 定义了全局的日志存放路径、日志等级等属性:

package main

import (
	"github.com/GuanceCloud/cliutils/logger"
)

func main() {
	r, err := logger.InitRoot(&logger.Option{
		Path: "/path/to/app/log", // 如果不填写路径,日志将出到 stdout
		Level: logger.DEBUG,      // 默认为 DEBUG
		Flags: logger.OPT_DEFAULT,// 开启了自动切割
	})
}
增加频率控制

如果某些日志比较高频但又不能完全移除,可以用带频率控制的日志函数。

import (
	"github.com/GuanceCloud/cliutils/logger"
)

logRate := 1.0
log = logger.SLogger("module-name", logger.WithRateLimiter(logRate, "")) // 每秒最多输出一条日志

// busy loop...
for {
    log.RLInfof(logRate, "this is high frequency log: %d", 1024)
    // 其它代码...
}

如果希望有多种频率,那么多加几个即可:

logRate1_0 := 1.0
logRate0_5 := .5
log = logger.SLogger("module-name",
        logger.WithRateLimiter(logRate1_0, ""),
        logger.WithRateLimiter(logRate0_5, ""))

for {
    log.RLInfof(logRate1_0, "this is 1 log/sec high frequency log: %d", 1024)
    log.RLInfof(logRate0_5, "this is 0.5 log/sec high frequency log: %d", 1024)
}

其它几个常规日志函数,只需加上 RL 前缀即可:

log.RLWarnf()
log.RLWarn()
log.RLDebugf()
log.RLDebug()
log.RLErrorf()
log.RLError()

注意事项:

  • 如果 logger 没有设置 rate limit,或者指定频率的 limiter 不存在,那么调用 RLXXX() 函数等价于调用 XXX()
  • 重复追加同样频率的控制,只有一个会生效

关于自动切割

默认情况下,会按照 32MB(大约) 一个文件来切割,最大保持 5 个切片,保存时长为 30 天。

提供环境变量来配置日志路径

调用 InitRoot() 时,如果传入的路径为空字符串,那么会尝试从 LOGGER_PATH 这个环境变量中获取有效的日志路径。某些情况下,可以将该路径设置成 /dev/null(UNIX) 或 nul(windows),用来屏蔽日志输出。

错误日志分离功能

支持将错误级别的日志写入单独的文件,便于日志组织和监控:

package main

import (
	"github.com/GuanceCloud/cliutils/logger"
)

func main() {
	r, err := logger.InitRoot(&logger.Option{
		Path:      "/var/log/app/main.log",    // 主日志文件
		ErrorPath: "/var/log/app/error.log",   // 单独的错误日志文件
		Level:     logger.DEBUG,               // 默认为 DEBUG
		Flags:     logger.OPT_DEFAULT,         // 开启了自动切割
	})
}
核心特性
  • 错误日志(ERROR, PANIC, FATAL, DPANIC)会同时写入主日志文件和单独的错误文件
  • 主日志文件接收所有达到配置级别的日志
  • 错误文件只接收错误级别及以上的日志
  • 两个文件都支持自动切割,可配置大小、备份数量和保存时长
  • 远程 TCP/UDP 日志会忽略 ErrorPath(所有日志都发送到同一端点)
配置选项
  • Path: 主日志文件路径
  • ErrorPath: 单独的错误日志文件路径(可选)
  • Level: 最小日志级别(debug, info, warn, error, panic, fatal, dpanic
  • Flags: 输出选项标志位(OPT_DEFAULT, OPT_COLOR, OPT_ROTATE 等)
  • MaxSize: 切割前的最大文件大小(MB,默认:32MB)
  • MaxBackups: 保留的旧日志文件最大数量(默认:5)
  • MaxAge: 保留旧日志文件的最大天数(默认:30)
  • Compress: 是否压缩切割后的日志文件(默认:false)

Documentation

Overview

Package logger wrapped zap as a basic logging implement.

Index

Constants

View Source
const (
	// 禁用 JSON 形式输出.
	OPT_ENC_CONSOLE = 1 //nolint:golint,stylecheck
	// 显示代码路径时,不显示全路径.
	OPT_SHORT_CALLER = 2 //nolint:stylecheck,golint
	// 日志写到 stdout.
	OPT_STDOUT = 4 //nolint:stylecheck,golint
	// 日志内容中追加颜色.
	OPT_COLOR = 8 //nolint:stylecheck,golint
	// 日志自动切割.
	OPT_ROTATE = 32 //nolint:stylecheck,golint
	// 默认日志 flags.
	OPT_DEFAULT = OPT_ENC_CONSOLE | OPT_SHORT_CALLER | OPT_ROTATE //nolint:stylecheck,golint

	DEBUG  = "debug"
	INFO   = "info"
	WARN   = "warn"
	ERROR  = "error"
	PANIC  = "panic"
	DPANIC = "dpanic"
	FATAL  = "fatal"
)
View Source
const (
	NameKeyMod   = "mod"
	NameKeyMsg   = "msg"
	NameKeyLevel = "lev"
	NameKeyTime  = "ts"
	NameKeyPos   = "pos"
)
View Source
const (
	STDOUT = "stdout" // log output to stdout
)

Variables

View Source
var (
	MaxSize    = 32 // MB
	MaxBackups = 5
	MaxAge     = 30 // day

)
View Source
var (
	SchemeTCP = "tcp"
	SchemeUDP = "udp"
)
View Source
var (
	StdoutColor bool
	StdoutLevel = DEBUG
)

Functions

func Close

func Close()

func InitCustomizeRoot

func InitCustomizeRoot(opt *Option) (*zap.Logger, error)

func InitRoot

func InitRoot(opt *Option) error

InitRoot used to setup global root logger, include

  • log level
  • log path
  • set to disk file(with or without rotate)
  • set to some remtoe TCP/UDP server
  • a bounch of other OPT_XXXs

func NewLoggerCtx

func NewLoggerCtx(opts ...CtxOption) *loggerCtx

func Reset

func Reset()

func SetGlobalRootLogger

func SetGlobalRootLogger(fpath, level string, options int) error

SetGlobalRootLogger deprecated, use InitRoot() instead.

func TotalSLoggers

func TotalSLoggers() int64

Types

type CtxOption

type CtxOption interface {
	// contains filtered or unexported methods
}

func EnableTrace

func EnableTrace() CtxOption

func WithParseTrace

func WithParseTrace(f ExtractTrace) CtxOption

func WithTraceKey

func WithTraceKey(tn string, sn string) CtxOption

func WithZapCore

func WithZapCore(core zapcore.Core) CtxOption

func WithZapOpts

func WithZapOpts(opts ...zap.Option) CtxOption

type ExtractTrace

type ExtractTrace func(ctx context.Context) Trace

type Logger

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

func DefaultSLogger

func DefaultSLogger(name string) *Logger

func DefaultSloggerSkipN

func DefaultSloggerSkipN(name string, callerSkip int) *Logger

func SLogger

func SLogger(name string, opts ...SLogerOpt) *Logger

func (*Logger) Debug

func (l *Logger) Debug(args ...any)

func (*Logger) Debugf

func (l *Logger) Debugf(fmt string, args ...any)

func (*Logger) Debugw

func (l *Logger) Debugw(fmt string, args ...any)

func (*Logger) Error

func (l *Logger) Error(args ...any)

func (*Logger) Errorf

func (l *Logger) Errorf(fmt string, args ...any)

func (*Logger) Errorw

func (l *Logger) Errorw(fmt string, args ...any)

func (*Logger) Fatal

func (l *Logger) Fatal(args ...any)

func (*Logger) Fatalf

func (l *Logger) Fatalf(fmt string, args ...any)

func (*Logger) Fatalw

func (l *Logger) Fatalw(fmt string, args ...any)

func (*Logger) Info

func (l *Logger) Info(args ...any)

func (*Logger) Infof

func (l *Logger) Infof(fmt string, args ...any)

func (*Logger) Infow

func (l *Logger) Infow(fmt string, args ...any)

func (*Logger) Level

func (l *Logger) Level() zapcore.Level

func (*Logger) Name

func (l *Logger) Name() string

func (*Logger) Panic

func (l *Logger) Panic(args ...any)

func (*Logger) Panicf

func (l *Logger) Panicf(fmt string, args ...any)

func (*Logger) Panicw

func (l *Logger) Panicw(fmt string, args ...any)

func (*Logger) RLDebug

func (l *Logger) RLDebug(r float64, args ...any)

func (*Logger) RLDebugf

func (l *Logger) RLDebugf(r float64, fmt string, args ...any)

func (*Logger) RLError

func (l *Logger) RLError(r float64, args ...any)

func (*Logger) RLErrorf

func (l *Logger) RLErrorf(r float64, fmt string, args ...any)

func (*Logger) RLInfo

func (l *Logger) RLInfo(r float64, args ...any)

func (*Logger) RLInfof

func (l *Logger) RLInfof(r float64, fmt string, args ...any)

func (*Logger) RLWarn

func (l *Logger) RLWarn(r float64, args ...any)

func (*Logger) RLWarnf

func (l *Logger) RLWarnf(r float64, fmt string, args ...any)

func (*Logger) SetSugar

func (l *Logger) SetSugar(sugar *zap.SugaredLogger)

func (*Logger) Sugar

func (l *Logger) Sugar() *zap.SugaredLogger

func (*Logger) Warn

func (l *Logger) Warn(args ...any)

func (*Logger) Warnf

func (l *Logger) Warnf(fmt string, args ...any)

func (*Logger) Warnw

func (l *Logger) Warnw(fmt string, args ...any)

type LoggerCtx

type LoggerCtx interface {
	Debugf(template string, args ...interface{})
	Infof(template string, args ...interface{})
	Warnf(template string, args ...interface{})
	Errorf(template string, args ...interface{})
	Debug(args ...interface{})
	Info(args ...interface{})
	Warn(args ...interface{})
	Error(args ...interface{})

	DebugfCtx(ctx context.Context, template string, args ...interface{})
	InfofCtx(ctx context.Context, template string, args ...interface{})
	WarnfCtx(ctx context.Context, template string, args ...interface{})
	ErrorfCtx(ctx context.Context, template string, args ...interface{})
	DebugCtx(ctx context.Context, template string, args ...interface{})
	InfoCtx(ctx context.Context, template string, args ...interface{})
	WarnCtx(ctx context.Context, template string, args ...interface{})
	ErrorCtx(ctx context.Context, template string, args ...interface{})

	Named(name string) LoggerCtx
	With(fields ...zap.Field) LoggerCtx
}

type Option

type Option struct {
	Path      string
	ErrorPath string
	Level     string
	MaxSize   int
	Flags     int
	Compress  bool
}

type SLogerOpt

type SLogerOpt func(*Logger)

func WithRateLimiter

func WithRateLimiter(n float64, hint string) SLogerOpt

WithRateLimiter set rate limit on current sloger, n limits the max logs can be written per second. The hint will injected to the log message like this:

2025-11-13T11:11:40.168+0800 INFO basic logger/logger_test.go:44 [<your-hint-here>] <your-origin-log-message>

If no hint set, the default seems like this(1 log/sec rate limited):

2025-11-13T11:11:40.168+0800 INFO basic logger/logger_test.go:44 [1.0-rl] <your-origin-log-message>

type Trace

type Trace struct {
	TraceID string
	SpanID  string
}

Jump to

Keyboard shortcuts

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