logcore

package module
v0.8.4 Latest Latest
Warning

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

Go to latest
Published: Jun 10, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package logcore is the framework-agnostic logging engine behind the logfiber (Fiber v2) and logfiberv3 (Fiber v3) adapters.

It builds a zap logger pre-wired for APM:

  • Error/Fatal log calls are auto-emitted as APM error events (via apmcore.WrapZapCore on top of apmzap.Core).
  • logcore.LogCtx(ctx) returns a logger decorated with trace.id / transaction.id / span.id when ctx has an active APM transaction.

The package keeps a process-global logger (logcore.Log / Logy / LogCtx) so handlers can call it without plumbing — and exposes logcore.New + SetGlobal for tests and apps that want to inject their own.

It also exports HTTPClientHook(), an adapter that plugs straight into httpclient.SetHook(...) and produces the same "outgoing" structured-log schema the Fiber incoming middlewares use, so requests are searchable in Kibana by req/res/responseTime regardless of direction.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AutobatchLogger added in v0.7.0

func AutobatchLogger(l *Logger) func(level autobatch.LogLevel, msg string, args ...any)

AutobatchLogger returns a function compatible with autobatch.Config.Logger that routes log entries to l (or the global logger when l is nil). The autobatch package documents its Logger args as slog/zap-sugared key-value pairs, which maps directly to zap's SugaredLogger.Infow etc.

db.Use(autobatch.New(autobatch.Config{
    Logger: logcore.AutobatchLogger(nil), // uses global logger
}))

func DecodeJSONBody

func DecodeJSONBody(raw []byte) any

DecodeJSONBody attempts to unmarshal raw as JSON. On failure (non-JSON payload, empty, malformed) it returns the raw bytes as a string so the log entry still carries something useful. nil bytes → nil.

func FlattenHeaders

func FlattenHeaders(h map[string][]string) any

FlattenHeaders converts a map[string][]string headers shape into a flat map[string]string by joining multi-valued entries with ",". Returns nil when the input is empty so the JSON encoder drops it.

func GSCoreGlobalLogger added in v0.7.0

func GSCoreGlobalLogger() gscoreLoggerIface

GSCoreGlobalLogger is a convenience wrapper that returns GSCoreLogger(nil), i.e. a gscore.Logger backed by the global logger.

func GSCoreLogger added in v0.7.0

func GSCoreLogger(l *Logger) gscoreLoggerIface

GSCoreLogger returns a gscore.Logger-compatible value backed by l. If l is nil the global logger is used. The returned value satisfies the real gscore.Logger interface via structural typing — no import of gscore is needed inside logcore.

func HTTPClientHook

func HTTPClientHook() httpclient.Hook

HTTPClientHook returns a httpclient.Hook that emits one structured log per attempt with the same shape the Fiber middlewares produce for incoming requests — Kibana queries like `outgoing.req.body.id` match regardless of direction.

Use it during bootstrap:

httpclient.SetHook(logcore.HTTPClientHook())

The log line uses the global logger decorated with apmcore trace fields (via LogCtx). For a custom logger, see HookFor.

func HookFor

func HookFor(l *Logger) httpclient.Hook

HookFor returns the same hook bound to l. Nil falls back to the global logger.

func InstallHTTPClientHook added in v0.7.0

func InstallHTTPClientHook()

InstallHTTPClientHook adds the global-logger hook to the httpclient hook chain. Uses AddHook (not SetHook) so it composes with any previously installed hook. Call once at boot.

func InstallHTTPClientHookFor added in v0.7.0

func InstallHTTPClientHookFor(l *Logger)

InstallHTTPClientHookFor is InstallHTTPClientHook bound to l.

func Log

func Log() *zap.Logger

Log returns the global logger, lazily constructing a production one the first time it's called. Safe for concurrent use.

func LogCtx

func LogCtx(ctx context.Context) *zap.Logger

LogCtx returns the global logger decorated with APM trace fields.

func Logy

func Logy() *zap.SugaredLogger

Logy returns the global sugared logger.

func RegisterGlobalWithManager added in v0.7.0

func RegisterGlobalWithManager(mgr CloserRegistrar, phase int, timeout time.Duration)

RegisterGlobalWithManager is RegisterWithManager applied to the global logger.

func SetGlobal

func SetGlobal(l *Logger)

SetGlobal replaces the process-wide logger. Passing nil restores the lazy default.

Types

type CloserRegistrar added in v0.7.0

type CloserRegistrar = gscore.CloserRegistrar

CloserRegistrar is the subset of gscore.Manager used by logcore helpers. It is a type alias for gscore.CloserRegistrar; *gscore.Manager satisfies it directly.

type Incoming

type Incoming struct {
	Req          *Req    `json:"req"`
	Res          *Res    `json:"res"`
	Error        *string `json:"error,omitempty"`
	ResponseTime string  `json:"responseTime"`
}

Incoming is the payload published under the "incoming" key by the Fiber middleware.

type Logger

type Logger struct{ *zap.Logger }

Logger wraps *zap.Logger so the package can attach helpers without shadowing zap's API.

func New

func New(opts Options) (*Logger, error)

New constructs a Logger configured per opts. The returned Logger is independent — call SetGlobal to make it the process-wide default.

func (*Logger) LogCtx

func (l *Logger) LogCtx(ctx context.Context) *zap.Logger

LogCtx returns a child logger decorated with the APM trace fields pulled from ctx — useful for any handler/service log call so the resulting line jumps back to its trace in Kibana.

func (*Logger) RegisterWithManager added in v0.7.0

func (l *Logger) RegisterWithManager(mgr CloserRegistrar, phase int, timeout time.Duration)

RegisterWithManager registers logger.Sync() as a closer on mgr so the zap OS write buffer is flushed before the process exits. Must be called after all other closers so log lines from shutdown itself are not lost.

phase must be gscore.PhasePostDB (value 4). Pass 0 to use PhasePostDB. timeout=0 defaults to 5s.

func (*Logger) Sugar

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

Sugar returns the sugared variant of the underlying logger.

type Options

type Options struct {
	// Level is the minimum log level. Default: InfoLevel.
	Level zapcore.Level

	// Encoding selects the zap encoder. "json" (default) or "console".
	Encoding string

	// DisableAPMCore turns off the apmzap.Core wrap. By default the
	// logger's core is wrapped so .Error/.Fatal calls are auto-emitted
	// as APM error events in Kibana → APM → Errors. Set to true to
	// disable (e.g. in tests where you don't want APM noise).
	DisableAPMCore bool

	// Service / Version / Environment are added as permanent fields on
	// every log line — useful as Kibana filters when many services
	// share an index.
	Service     string
	Version     string
	Environment string

	// Extra is appended to the zap.New options list. Use it for hooks,
	// custom AddCallerSkip, ReplaceCore, etc.
	Extra []zap.Option
}

Options tunes New. All fields are optional; sensible production defaults are applied when zero.

type Outgoing

type Outgoing struct {
	Req          *Req    `json:"req"`
	Res          *Res    `json:"res"`
	Error        *string `json:"error,omitempty"`
	ResponseTime string  `json:"responseTime"`
}

Outgoing is the payload published under the "outgoing" key by the httpclient hook.

type Req

type Req struct {
	Params      any `json:"params,omitempty"`
	QueryString any `json:"queryString,omitempty"`
	Headers     any `json:"headers,omitempty"`
	Body        any `json:"body,omitempty"`
}

Req is the request side of an incoming or outgoing log entry. Fields stay omitempty so the JSON in Kibana is compact.

type Res

type Res struct {
	Headers    any    `json:"headers,omitempty"`
	Body       any    `json:"body,omitempty"`
	StatusCode string `json:"statusCode"`
}

Res is the response side. StatusCode is a string ("Ø" when unknown) to match the pattern used in existing dashboards.

Jump to

Keyboard shortcuts

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