v1

package
v1.0.14 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: MIT Imports: 11 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

methodlog/v1

方法执行日志中间件:以流式 API 包装业务方法,自动输出方法名、耗时、结果文案、 错误与 panic 记录,并按 info / error / panic 自动分级。支持 HTTP 与 gRPC 的 上下文字段提取(客户端 IP 等)。

基本用法

err := methodlog.New(ctx, handler).
    Action(func(h Handler) error {
        return h.ServeHTTP(w, r)
    }).
    Result(func() string {
        return "request processed"
    }).
    Do()

带协议字段提取:

err := methodlog.New(ctx, handler, methodlog.WithFieldExtractor(methodlog.HTTPFieldExtractor)).
    Action(func(h Handler) error {
        return h.ServeHTTP(w, r)
    }).
    Do()

Result 闭包契约(重要)

Result / ResultWithError 的闭包在 Do 的 defer 阶段执行,此时 Do 尚未返回, 调用方 err = ...Do() 的赋值还没有发生。因此:

  • Result(func() string) 闭包若捕获调用方变量,该变量必须在 Action 内先赋值, 否则闭包恒读到旧值(通常是 nil):
var u *User
err := methodlog.New(ctx, getUser).
    Result(func() string {
        if u != nil {
            return fmt.Sprintf("user %s", u.Name)
        }
        return "not found"
    }).
    Action(func(m func(context.Context, int64) (*User, error)) error {
        var e error
        u, e = m(ctx, id) // 必须在 Action 内赋值,闭包才能看到
        return e
    }).
    Do()
  • 需要按最终错误分支结果文案时,推荐使用 ResultWithError:它直接接收 Do 自身的最终返回值,Action 内无需给外层变量赋值:
err := methodlog.New(ctx, method).
    Action(func(m MethodType) error {
        return m(args) // 直接返回即可
    }).
    ResultWithError(func(err error) string {
        if err != nil {
            return fmt.Sprintf("request failed: %v", err)
        }
        return "request processed"
    }).
    Do()

Result 与 ResultWithError 共用同一结果槽位,多次设置时后者覆盖前者。 action panic 时 ResultWithError 收到 nil(panic 由 panic 级日志单独记录)。

WithLogger:注入固定 logger

WithLogger 为本次 Do 注入固定 logger,覆盖默认的全局日志解析, 所有级别(含 panic 记录)都写入注入的 logger,常用于测试捕获:

err := methodlog.New(ctx, handler, methodlog.WithLogger(captureLogger)).
    Action(func(h Handler) error {
        return h.ServeHTTP(w, r)
    }).
    Do()

日志输出目的地跟随宿主 log.Init

各级 logger 在每次 Do 时惰性解析(经 log/v1 的 K() / V(-2) / V(-4)), 不再于包加载时一次性绑定。宿主进程在启动阶段调用 log.Init 重新初始化日志 (例如把输出从 stdout/stderr 切换到文件)后,后续 Do 的日志会写入新目的地。

并发注意:log/v1 的 Init 持锁替换全局 logger,而 K() / V() 无锁读取, 这是 log/v1 的既有竞态,不在本包修复范围内。宿主应在开始并发日志之前完成 log.Init(例如在 main/启动阶段一次性初始化)。

调用位置:caller 与 callsite

日志后端(zap)自带的 caller 字段是组件内部位置:日志在 Do 的 defer 闭包中经多层包装写出,caller 落在本包内部(当前为 Do 的 defer 闭包, builder.go;panic 即时记录路径则可能落在 runtime 帧),不指向业务代码。

为此,New 在构造时捕获业务调用点,每条日志(含 panic 即时记录与最终记录) 都携带 callsite 字段,短格式 包目录/文件名:行号(如 middleware/middleware.go:42),与 zap 的 caller 键不冲突:

{"method":"...GetClaimDetail-fm","callsite":"middleware/middleware.go:42", ...}

定位业务代码请优先使用 callsite 或 method(方法全名)字段;panic 日志另带 stacktrace 字段可查完整调用栈。注意:若业务再封装一层 New,callsite 指向封装层的调用行(所有调用点捕获方案的共同局限)。宿主日志配置开启 DisableCaller 时输出仅保留 callsite,更干净。

panic 语义

action panic 时,panic 记录经 panic 级 logger 立即输出。默认 panic 级 logger 为 zap PanicLevel,zap 在写完日志后会再次 panic(go-kit/zap 桥接的既有行为), 该二次 panic 会向外传播;本包保留此既有语义。使用 WithLogger 注入非 panic 级 logger 时,Do 吞掉 action panic 并返回 nil。

测试

go test -race ./pkg/methodlog/...

Documentation

Overview

Package v1 provides a fluent API for method execution logging with panic recovery. It supports HTTP and gRPC protocol-specific field extraction through functional options.

Basic usage:

err := methodlog.New(ctx, handler).
    Action(func(h Handler) error {
        return h.ServeHTTP(w, r)
    }).
    Result(func() string {
        return "request processed"
    }).
    Do()

With protocol-specific field extraction:

err := methodlog.New(ctx, handler, methodlog.WithFieldExtractor(methodlog.HTTPFieldExtractor)).
    Action(func(h Handler) error {
        return h.ServeHTTP(w, r)
    }).
    Do()

Result closure contract: Result/ResultWithError builders run inside Do's defer, BEFORE Do returns to the caller. When a closure captures the caller's own variable (e.g. the variable assigned by `err = ...Do()`), that assignment has not happened yet, so the closure must rely on values assigned INSIDE Action. To branch the result message on the final error returned by Do, prefer ResultWithError, which receives that error directly:

err := methodlog.New(ctx, method).
    Action(func(m MethodType) error {
        return m(args) // no outer assignment needed
    }).
    ResultWithError(func(err error) string {
        if err != nil {
            return "request failed"
        }
        return "request processed"
    }).
    Do()

Log output destinations follow the host's log.Init: level loggers are resolved lazily on each Do. Hosts should complete log.Init before starting concurrent logging (log/v1 Init/K() synchronization is out of scope here).

Caller semantics: The logging backend's own "caller" field reports a position INSIDE this package (the deferred closure in Do), not the business call site, because entries are emitted from Do's defer through several wrapper layers. New therefore captures the business call site up front and every entry carries it as the "callsite" field (package/file.go:line). Prefer "callsite" or "method" when locating business code.

Index

Constants

This section is empty.

Variables

View Source
var ErrActionNotSet = errors.New("methodlog: action not set")

ErrActionNotSet is returned when attempting to execute without configuring an action

View Source
var GRPCFieldExtractor = FieldExtractor(func(ctx context.Context) []interface{} {
	return []interface{}{
		"clientIp", getGRPCClientIP(ctx),
	}
})

GRPCFieldExtractor extracts gRPC-specific fields from context. It retrieves client IP from gRPC peer information.

Usage:

methodlog.New(ctx, handler, methodlog.WithFieldExtractor(methodlog.GRPCFieldExtractor)).Do()
View Source
var HTTPFieldExtractor = FieldExtractor(func(ctx context.Context) []interface{} {
	return []interface{}{
		"clientIp", getHTTPClientIP(ctx),
	}
})

HTTPFieldExtractor extracts HTTP-specific fields from context. It retrieves client IP from context (set by middleware using WithClientIP).

Usage:

methodlog.New(ctx, handler, methodlog.WithFieldExtractor(methodlog.HTTPFieldExtractor)).Do()

Functions

func WithClientIP

func WithClientIP(ctx context.Context, ip string) context.Context

WithClientIP returns a context with the client IP stored. Use this in HTTP middleware to propagate client IP to the logger.

Example:

ctx = methodlog.WithClientIP(r.Context(), "192.168.1.1")

Types

type Action

type Action[M any] func(method M) error

Action defines the signature for middleware action functions It receives a method and returns an error if execution fails

type Builder

type Builder[M any] struct {
	// contains filtered or unexported fields
}

Builder provides a fluent API for constructing logging middleware with panic recovery. Generic type M represents the method signature to be wrapped.

Example:

builder := methodlog.New(ctx, myHandler).
    Action(func(h Handler) error {
        return h.ServeHTTP(w, r)
    }).
    Result(func() string {
        return "success"
    })
err := builder.Do()

func New

func New[M any](ctx context.Context, method M, opts ...Option) *Builder[M]

New creates a new Builder instance with initialized executor. Optional opts can be provided to configure field extractors. It also captures the caller's position (the business call site) so log entries can carry it as the "callsite" field; see package docs on caller semantics. If New is wrapped by another helper, the captured position is that helper's call site.

func (*Builder[M]) Action

func (b *Builder[M]) Action(action Action[M]) *Builder[M]

Action configures the action function to be executed with logging The action receives the target method and should invoke it, returning any error Example:

builder.Action(func(method func(ctx context.Context, id int64) error) error {
    return method(ctx, 123)
})

func (*Builder[M]) AddInfos

func (b *Builder[M]) AddInfos(builder infosBuilder) *Builder[M]

AddInfos configures builders for dynamic log key-value pairs Each builder executes after method completion, capturing runtime state via closures Multiple calls compose builders - all execute in order during defer

Use cases: 1. Capture values modified during method execution 2. Access return values or state changes 3. Conditional logging based on execution results

Example - Static values (captured at call time):

methodlog.New(ctx, method).
    AddInfos(func() []interface{} {
        return []interface{}{"key", "value"}
    }).
    Do()

Example - Dynamic values (captured after execution):

var id int64
var name string
methodlog.New(ctx, method).
    AddInfos(func() []interface{} {
        return []interface{}{"id", id, "name", name}
    }).
    Action(func(m MethodType) error {
        id = 123
        name = "test"
        return m()
    }).
    Do()

func (*Builder[M]) Do

func (b *Builder[M]) Do() (err error)

Do wraps the configured action with logging, panic recovery, and error handling Execution flow: 1. Record start time 2. Execute action (via exec.action) 3. In defer: recover panics, set error, execute builders, output log

Returns error from action execution or ErrActionNotSet if action is nil

func (*Builder[M]) Result

func (b *Builder[M]) Result(builder resultBuilder) *Builder[M]

Result configures a dynamic result message builder The builder function executes after method completion in the defer block, allowing access to closure-captured variables modified during execution

Contract: the builder runs inside Do's defer, before Do returns. A closure capturing the caller's variable assigned by `err = ...Do()` still sees the old value (typically nil); captured variables must be assigned INSIDE Action. To branch on the final error without such assignment, use ResultWithError.

Note: Multiple calls replace previous builder (last one wins), shared with ResultWithError. For conditional logic, check b.formatter.err inside the builder if needed

Example:

var result *SomeType
methodlog.New(ctx, method).
    Result(func() string {
        if result != nil {
            return fmt.Sprintf("success, id: %d", result.ID)
        }
        return "success"
    }).
    Action(func(m MethodType) error {
        result, err = m(args) // assign inside Action so the closure sees it
        return err
    }).
    Do()

func (*Builder[M]) ResultWithError added in v1.0.14

func (b *Builder[M]) ResultWithError(builder func(err error) string) *Builder[M]

ResultWithError configures a result message builder that receives the final error returned by Do. Unlike Result, it does not require assigning captured variables inside Action: the builder is invoked in Do's defer with Do's own named return value, so `return method()` inside Action is enough.

The error is nil on success and when the action panicked (panics are logged separately via the panic logger). Shares the same result slot with Result: multiple calls replace the previous builder (last one wins).

Example:

err := methodlog.New(ctx, method).
    Action(func(m MethodType) error {
        return m(args)
    }).
    ResultWithError(func(err error) string {
        if err != nil {
            return fmt.Sprintf("request failed: %v", err)
        }
        return "request processed"
    }).
    Do()

type FieldExtractor

type FieldExtractor func(ctx context.Context) []interface{}

FieldExtractor defines a function that extracts log fields from context. It enables protocol-specific field extraction (HTTP, gRPC, etc.).

type Option

type Option func(*formatter)

Option defines a function that configures the formatter. Options are applied during formatter initialization.

func WithFieldExtractor

func WithFieldExtractor(extractor FieldExtractor) Option

WithFieldExtractor adds a custom field extractor to the formatter. Multiple extractors can be composed and are executed in order.

Example:

methodlog.New(ctx, handler,
    methodlog.WithFieldExtractor(methodlog.HTTPFieldExtractor),
    methodlog.WithFieldExtractor(customExtractor),
).Do()

func WithLogger added in v1.0.14

func WithLogger(logger kitlog.Logger) Option

WithLogger injects a fixed logger used for all log output of this Do, including the panic record, overriding the lazy per-Do resolution from the global log state. Useful for capturing log output in tests. A nil logger is ignored and lazy resolution applies.

Example:

methodlog.New(ctx, handler, methodlog.WithLogger(captureLogger)).Do()

Jump to

Keyboard shortcuts

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