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 ¶
- Variables
- func WithClientIP(ctx context.Context, ip string) context.Context
- type Action
- type Builder
- func (b *Builder[M]) Action(action Action[M]) *Builder[M]
- func (b *Builder[M]) AddInfos(builder infosBuilder) *Builder[M]
- func (b *Builder[M]) Do() (err error)
- func (b *Builder[M]) Result(builder resultBuilder) *Builder[M]
- func (b *Builder[M]) ResultWithError(builder func(err error) string) *Builder[M]
- type FieldExtractor
- type Option
Constants ¶
This section is empty.
Variables ¶
var ErrActionNotSet = errors.New("methodlog: action not set")
ErrActionNotSet is returned when attempting to execute without configuring an action
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()
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 ¶
Types ¶
type Action ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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
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 ¶
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
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()