v1

package
v1.0.12 Latest Latest
Warning

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

Go to latest
Published: Jul 15, 2026 License: MIT Imports: 9 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.

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()

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.

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

Note: Multiple calls replace previous builder (last one wins) 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)
        return err
    }).
    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()

Jump to

Keyboard shortcuts

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