log

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Jul 29, 2026 License: Apache-2.0 Imports: 19 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ReqIDKey contextKey = "req_id"
)

Variables

This section is empty.

Functions

func BindCtx

func BindCtx(ctx context.Context) (release func())

BindCtx 把 ctx 中的 req_id 绑定到当前 goroutine。 推荐在每个对外入口(如 CacheDB.Transaction、CallBeforeQuery)调用一次:

release := log.BindCtx(ctx)
defer release()

即使 ctx 为 nil 或没有 req_id,也安全(返回 no-op release)。

func CatchPanic

func CatchPanic(panicCallback func(err interface{}))

CatchPanic 在当前 goroutine 内 recover 并打印完整栈。

用法:

go func() {
    defer log.CatchPanic(nil)
    // ... 业务代码
}()

panicCallback 可选;若不为 nil,会在日志打印之后被调用, 通常用于上报告警 / 释放资源。

注:本函数使用 log.Errorf / log.Error,因此 panic 日志会自动带上当前 goroutine 的 reqId。

func ClearReqId

func ClearReqId()

func Debug

func Debug(args ...interface{})

func Debugf

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

func DebugfCtx

func DebugfCtx(ctx context.Context, template string, args ...interface{})

func Debugw

func Debugw(msg string, kv ...any)

func DebugwCtx

func DebugwCtx(ctx context.Context, msg string, kv ...any)

func Error

func Error(args ...interface{})

func Errorf

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

func ErrorfCtx

func ErrorfCtx(ctx context.Context, template string, args ...interface{})

func Errorw

func Errorw(msg string, kv ...any)

func ErrorwCtx

func ErrorwCtx(ctx context.Context, msg string, kv ...any)

func Fatal

func Fatal(args ...interface{})

func Fatalf

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

func FormatError

func FormatError(err error) string

FormatError returns the error message followed by every captured source frame.

func GRPCError

func GRPCError(err error, code codes.Code, operation, message string) error

GRPCError adds source context while retaining the gRPC status code.

func GetReqId

func GetReqId() string

func Go

func Go(fn func())

Go 启动新 goroutine 并传递 reqId。

行为:

  • 父 goroutine 没有 reqId → 子 goroutine 也没有
  • 父 goroutine 有 reqId="req-abc" → 子 goroutine reqId="req-abc.1", 再启第二个子 → "req-abc.2",以此类推
  • 子 goroutine 内再调用 Go() → 孙子 reqId="req-abc.1.1",形成树状层级
  • 子 goroutine 退出时自动 ClearReqId,避免 goid 复用串号
  • 子 goroutine 内若 panic:自动 recover,打印完整栈与 reqId,**不会** 拖垮进程

Example:

log.SetReqId("req-abc")
log.Go(func() {
    log.Infow("child task")           // [req-abc.1]
    log.Go(func() {
        log.Infow("grandchild task")  // [req-abc.1.1]
    })
})

func GoSafe

func GoSafe(fn func(), onPanic func(err interface{}))

GoSafe 与 Go 行为一致,但允许传入 panic 回调(如告警 / metrics 上报)。

回调在日志打印 **之后** 执行,不会再次 panic 出去。

func Info

func Info(args ...interface{})

func Infof

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

func InfofCtx

func InfofCtx(ctx context.Context, template string, args ...interface{})

func Infow

func Infow(msg string, kv ...any)

func InfowCtx

func InfowCtx(ctx context.Context, msg string, kv ...any)

func Must

func Must(err error)

func NewError

func NewError(operation, format string, args ...any) error

NewError constructs an error and captures its construction site.

func PrintStack

func PrintStack(skip int)

func ResetChildCounter

func ResetChildCounter(reqId string)

ResetChildCounter 清理某个 parent reqId 的子计数器。可在请求结束时调用,避免长期累积。 不调用也不会影响功能(仅占少量内存)。

func SetErrorSourceRoot

func SetErrorSourceRoot(root string)

SetErrorSourceRoot controls how source paths are shortened by FormatError. An empty root uses the process working directory.

func SetLogLevel

func SetLogLevel(l Level)

func SetOutput

func SetOutput(w io.Writer)

SetOutput 用于测试或自定义日志去向(默认 os.Stdout)。并发安全。

func SetReqId

func SetReqId(reqId string)

func SetReqIdFromContext

func SetReqIdFromContext(ctx context.Context)

func Warn

func Warn(args ...interface{})

func Warnf

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

func WarnfCtx

func WarnfCtx(ctx context.Context, template string, args ...interface{})

func Warnw

func Warnw(msg string, kv ...any)

func WarnwCtx

func WarnwCtx(ctx context.Context, msg string, kv ...any)

func WithReqID

func WithReqID(ctx context.Context, reqId string) context.Context

WithReqID 返回携带 reqId 的子 context,供下游 ctx 版日志 API 与 BindCtx 读取。 reqId 为空时原样返回 ctx(不写入空值)。

func WrapError

func WrapError(err error, operation string) error

WrapError adds operation context and its call site while preserving errors.Is/As.

Types

type Field

type Field struct {
	Key string
	Val any
}

Field 是结构化日志的键值对。

func F

func F(key string, val any) Field

F 是 Field 的快捷构造器。

type GormLogger

type GormLogger struct {
	LogLevel                  logger.LogLevel
	SlowThreshold             time.Duration
	IgnoreRecordNotFoundError bool
	logger.Interface
}

GormLogger 封装gorm.logger以适应公共库的log风格

func (*GormLogger) Error

func (l *GormLogger) Error(ctx context.Context, msg string, data ...interface{})

Error print error messages

func (*GormLogger) Info

func (l *GormLogger) Info(ctx context.Context, msg string, data ...interface{})

Info print info

func (*GormLogger) LogMode

func (l *GormLogger) LogMode(level logger.LogLevel) logger.Interface

LogMode log mode

func (*GormLogger) Trace

func (l *GormLogger) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error)

func (*GormLogger) Warn

func (l *GormLogger) Warn(ctx context.Context, msg string, data ...interface{})

Warn print warn messages

type Level

type Level int8
const (
	DebugLevel Level = iota - 1
	InfoLevel
	WarnLevel
	ErrorLevel
	DPanicLevel
	PanicLevel
	FatalLevel
	ImportantLevel
	GORMLevel
)

func GetLogLevel

func GetLogLevel() Level

GetLogLevel 返回当前日志级别。

func (Level) Color

func (l Level) Color() string

func (Level) ShortString

func (l Level) ShortString() string

func (Level) String

func (l Level) String() string

type TracedError

type TracedError struct {
	Operation string
	File      string
	Line      int
	Err       error
}

TracedError is one contextual source frame in an error chain.

func (*TracedError) Error

func (e *TracedError) Error() string

func (*TracedError) Unwrap

func (e *TracedError) Unwrap() error

Jump to

Keyboard shortcuts

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