Documentation
¶
Overview ¶
Package slogcp provides a structured logging solution for Go applications that need to integrate cleanly with Google Cloud Logging. It builds on the standard library's log/slog package and emits JSON payloads that follow Cloud Logging conventions while writing to any io.Writer. The default destination is stdout, keeping the library container- and developer-friendly.
The primary entry point is NewHandler, which returns an slog.Handler configured with sensible defaults:
- Structured JSON output that emits Cloud Logging fields such as `severity`, `logging.googleapis.com/trace`, `httpRequest`, and runtime metadata discovered from Cloud Run, Cloud Functions, Cloud Run Jobs, App Engine, GKE, and Compute Engine environments.
- Optional source locations, explicit RFC3339 timestamps, and automatic stack traces triggered at or above a configurable level.
- Seamless trace correlation helpers that leverage the extended Level definitions (`DEBUG` through `EMERGENCY`) plus the ability to emit single-letter severity aliases when desired, defaulting to full names outside Cloud Run, Cloud Run Jobs, Cloud Functions, and App Engine.
- Timestamp emission that mirrors Cloud Logging expectations: omit the field on those managed runtimes and otherwise leave log/slog's JSONHandler default `time` field (a time.RFC3339Nano value) untouched so local and on-premise logs keep the native precision unless you override it.
- Middleware hooks that allow additional slog.Handler layers to enrich or filter records before they are encoded.
Handlers can be redirected to stderr, a file managed by slogcp, or a custom writer. When slogcp opens the file it also provides Handler.ReopenLogFile to cooperate with external rotation tools. The handler exposes Handler.LevelVar and Handler.SetLevel for dynamic severity adjustments and honours many environment variables (for example `SLOGCP_LEVEL` with a `LOG_LEVEL` fallback, `SLOGCP_STACK_TRACES`, or `SLOGCP_TARGET`) so the same binary can run locally and in production without code changes. ContextWithLogger and Logger store and retrieve request-scoped loggers so integrations can pass loggers through call stacks.
Subpackages ¶
- github.com/pjscruggs/slogcp/slogcphttp offers net/http middleware and client transports that derive request-scoped loggers, propagate trace context, record latency/size metadata, and expose Cloud Logging friendly helpers such as [slogcphttp.HTTPRequestAttr] and [slogcphttp.ScopeFromContext]. Legacy `X-Cloud-Trace-Context` handling is available when required.
- github.com/pjscruggs/slogcp/slogcpgrpc provides client and server interceptors that capture RPC metadata, surface errors with stack traces, and propagate trace context. Helper functions such as [slogcpgrpc.ServerOptions], [slogcpgrpc.DialOptions], and [slogcpgrpc.InfoFromContext] simplify wiring in both directions.
- github.com/pjscruggs/slogcp/slogcppubsub provides Pub/Sub helpers for injecting and extracting OpenTelemetry trace context via `pubsub.Message.Attributes`, deriving per-message loggers (so `slogcp.Logger(ctx)` works inside handlers), and optionally starting an application-level consumer span. It supports interoperability with the Go Pub/Sub client's `googclient_`-prefixed attribute keys when enabled.
Quick Start ¶
A basic logger only needs a handler and slog:
handler, err := slogcp.NewHandler(os.Stdout)
if err != nil {
log.Fatalf("create slogcp handler: %v", err)
}
defer handler.Close() // flushes buffered logs and owned writers
logger := slog.New(handler)
logger.Info("application started")
Configuration ¶
Use functional options such as WithLevel, WithSourceLocationEnabled, WithStackTraceEnabled, WithRedirectToFile, WithRedirectWriter, WithAdditionalHandlers, WithSeverityAliases, and WithTraceProjectID to adjust behaviour programmatically. Refer to the package documentation and configuration guide in docs/CONFIGURATION.md for the complete list of options, environment variables, and integration helpers. For trace propagation, applications can install slogcp's recommended composite propagator globally via EnsurePropagation, or construct it directly with NewCompositePropagator and pass it where needed.
Index ¶
- Constants
- Variables
- func AlertContext(ctx context.Context, logger *slog.Logger, msg string, args ...any)
- func BuildXCloudTraceContext(rawTraceID, spanIDHex string, sampled bool) string
- func CaptureStack(skipFn func(string) bool) (string, runtime.Frame)
- func ContextWithLogger(ctx context.Context, logger *slog.Logger) context.Context
- func ContextWithTraceProjectID(ctx context.Context, projectID string) context.Context
- func CriticalContext(ctx context.Context, logger *slog.Logger, msg string, args ...any)
- func Debug(logger *slog.Logger, msg string, args ...any)
- func DebugContext(ctx context.Context, logger *slog.Logger, msg string, args ...any)
- func Default(logger *slog.Logger, msg string, args ...any)
- func DefaultContext(ctx context.Context, logger *slog.Logger, msg string, args ...any)
- func EmergencyContext(ctx context.Context, logger *slog.Logger, msg string, args ...any)
- func EnsurePropagation()
- func Error(logger *slog.Logger, msg string, args ...any)
- func ErrorContext(ctx context.Context, logger *slog.Logger, msg string, args ...any)
- func ErrorReportingAttrs(err error, opts ...ErrorReportingOption) []slog.Attr
- func ExtractTraceSpan(ctx context.Context, projectID string) (formattedTraceID, rawTraceID, rawSpanID string, sampled bool, ...)
- func FormatTraceResource(projectID, rawTraceID string) string
- func GetVersion() string
- func HTTPRequestValue(builder func() *HTTPRequest) slog.Value
- func Info(logger *slog.Logger, msg string, args ...any)
- func InfoContext(ctx context.Context, logger *slog.Logger, msg string, args ...any)
- func Logger(ctx context.Context) *slog.Logger
- func NoticeContext(ctx context.Context, logger *slog.Logger, msg string, args ...any)
- func PrepareHTTPRequest(req *HTTPRequest)
- func ReportError(ctx context.Context, logger *slog.Logger, err error, msg string, ...)
- func SkipInternalStackFrame(funcName string) bool
- func SpanIDHexToDecimal(spanIDHex string) (string, bool)
- func TraceAttributes(ctx context.Context, projectID string) ([]slog.Attr, bool)
- func TraceProjectIDFromContext(ctx context.Context) (string, bool)
- func Warn(logger *slog.Logger, msg string, args ...any)
- func WarnContext(ctx context.Context, logger *slog.Logger, msg string, args ...any)
- type CloseTimeoutPolicy
- type CompositePropagator
- type ErrorReportingOption
- type HTTPRequest
- type Handler
- func (h *Handler) Abort(ctx context.Context) error
- func (h *Handler) Close() error
- func (h *Handler) Level() slog.Level
- func (h *Handler) LevelVar() *slog.LevelVar
- func (h *Handler) ReopenLogFile() error
- func (h *Handler) SetLevel(level slog.Level)
- func (h *Handler) Shutdown(ctx context.Context) error
- type Level
- type Middleware
- type Option
- func WithAdditionalHandlers(handlers ...slog.Handler) Option
- func WithAsync(opts ...slogcpasync.Option) Option
- func WithAsyncOnFile(opts ...slogcpasync.Option) Option
- func WithAttrs(attrs []slog.Attr) Option
- func WithCloseTimeoutPolicy(policy CloseTimeoutPolicy) Option
- func WithGroup(name string) Option
- func WithInternalLogger(logger *slog.Logger) Option
- func WithLevel(level slog.Level) Option
- func WithLevelVar(levelVar *slog.LevelVar) Option
- func WithMiddleware(mw Middleware) Option
- func WithRedirectToFile(path string) Option
- func WithRedirectToStderr() Option
- func WithRedirectToStdout() Option
- func WithRedirectWriter(writer io.Writer) Option
- func WithReplaceAttr(fn func([]string, slog.Attr) slog.Attr) Option
- func WithSeverityAliases(enabled bool) Option
- func WithSourceLocationEnabled(enabled bool) Option
- func WithStackTraceEnabled(enabled bool) Option
- func WithStackTraceLevel(level slog.Level) Option
- func WithTime(enabled bool) Option
- func WithTraceDiagnostics(mode TraceDiagnosticsMode) Option
- func WithTraceProjectID(id string) Option
- type RuntimeEnvironment
- type RuntimeInfo
- type SwitchableWriter
- type TraceDiagnosticsMode
Constants ¶
const ( // TraceKey is the field name for the formatted trace name. // The value must be "projects/PROJECT_ID/traces/TRACE_ID". TraceKey = "logging.googleapis.com/trace" // SpanKey is the field name for the hex span ID. SpanKey = "logging.googleapis.com/spanId" // SampledKey is the field name for the boolean sampling decision. SampledKey = "logging.googleapis.com/trace_sampled" )
Constants for trace-related keys used when adding trace information as attributes to structured log payloads. These specific keys are recognized by Google Cloud Logging for automatic correlation with Cloud Trace.
const (
// LabelsGroup is the Cloud Logging attribute group used for structured labels.
LabelsGroup = "logging.googleapis.com/labels"
)
Variables ¶
var ( // ErrInvalidRedirectTarget indicates an unsupported value for SLOGCP_TARGET or redirect options. ErrInvalidRedirectTarget = errors.New("slogcp: invalid redirect target") )
var UserAgent string
UserAgent identifies this library when helper components need to report a version string. It is initialized from Version and can be overridden at build time.
var Version = "v1.2.0"
Version is the current version of the slogcp library. Follows semantic versioning (https://semver.org/). It can be overridden at build time via -ldflags.
Functions ¶
func AlertContext ¶
AlertContext logs at alert severity to integrate with on-call workflows for non-recoverable issues.
func BuildXCloudTraceContext ¶
BuildXCloudTraceContext builds the value for the legacy X-Cloud-Trace-Context header from raw hex IDs and a sampled flag. The format is:
TRACE_ID[/SPAN_ID][;o=TRACE_TRUE]
where SPAN_ID is decimal and TRACE_TRUE is "1" when sampled, "0" otherwise.
If spanIDHex is empty or invalid, the "/SPAN_ID" portion is omitted.
func CaptureStack ¶
CaptureStack captures the current goroutine stack, trimming internal frames using skipFn (or SkipInternalStackFrame when nil). It returns the formatted stack trace string and the first remaining frame for use in report locations.
func ContextWithLogger ¶
ContextWithLogger returns a child context that stores logger so handlers can retrieve a request-scoped logger later in the call chain.
func ContextWithTraceProjectID ¶ added in v1.2.0
ContextWithTraceProjectID stores a normalized trace project ID on ctx so TraceAttributes can resolve project IDs without relying on process-global environment caching.
func CriticalContext ¶
CriticalContext logs a message at critical severity indicating immediate attention is required.
func Debug ¶
Debug logs a structured message at LevelDebug severity without requiring a context. It mirrors slog.Logger.Debug while guaranteeing Cloud Logging severity alignment.
func DebugContext ¶
DebugContext logs a message at LevelDebug severity while attaching contextual attributes from ctx.
func Default ¶
Default logs a structured message at LevelDefault severity without requiring a context value.
func DefaultContext ¶
DefaultContext logs a structured message at LevelDefault severity while attaching contextual attributes from ctx. It is suitable for routing application level events through Cloud Logging.
func EmergencyContext ¶
EmergencyContext logs at emergency severity highlighting application-wide failures that demand instant response.
func EnsurePropagation ¶
func EnsurePropagation()
EnsurePropagation configures a composite OpenTelemetry text map propagator that prefers the W3C Trace Context headers while accepting Google Cloud's legacy X-Cloud-Trace-Context header on ingress. The configuration is applied exactly once per process.
The installed propagator order is:
- CloudTraceOneWayPropagator (extracts X-Cloud-Trace-Context only)
- TraceContext (W3C traceparent/tracestate)
- Baggage
Applications remain free to override the global propagator afterwards by calling otel.SetTextMapPropagator with their own implementation.
func Error ¶
Error logs a structured message at LevelError severity without requiring a context, mirroring slog.Logger.Error.
func ErrorContext ¶
ErrorContext logs a message at LevelError severity while attaching contextual attributes from ctx.
func ErrorReportingAttrs ¶
func ErrorReportingAttrs(err error, opts ...ErrorReportingOption) []slog.Attr
ErrorReportingAttrs returns structured attributes that align with the Cloud Error Reporting ingestion format. The caller can append the returned attrs to any slog logging call.
func ExtractTraceSpan ¶
func ExtractTraceSpan(ctx context.Context, projectID string) (formattedTraceID, rawTraceID, rawSpanID string, sampled bool, otelCtx trace.SpanContext)
ExtractTraceSpan extracts OpenTelemetry trace details from ctx and, if a non-empty projectID is provided, formats a fully-qualified Cloud Trace name using "projects/{projectID}/traces/{traceID}".
It returns:
- formattedTraceID: "projects/<projectID>/traces/<traceID>" if projectID != "", else "".
- rawTraceID: 32-char lowercase hex trace ID.
- rawSpanID: 16-char lowercase hex span ID.
- sampled: whether the span context is sampled.
- otelCtx: the original span context (valid==true iff trace present).
This function is intentionally light-weight: it does not create spans, does not parse headers, and does not mutate context. Upstream middleware should populate the OTel span context (e.g., via OTel propagators or an X-Cloud-Trace-Context injector) before calling this helper.
For cross-project linking, pass the desired project that owns the trace as projectID. If empty, only raw IDs are returned.
func FormatTraceResource ¶
FormatTraceResource returns a fully-qualified Cloud Trace resource name:
projects/<projectID>/traces/<traceID>
Callers should pass a 32-char lowercase hex traceID (e.g., from OTel).
func HTTPRequestValue ¶
func HTTPRequestValue(builder func() *HTTPRequest) slog.Value
HTTPRequestValue constructs a slog.Value that lazily builds an HTTPRequest.
func Info ¶
Info logs a structured message at LevelInfo severity without requiring a context, mirroring slog.Logger.Info.
func InfoContext ¶
InfoContext logs a message at LevelInfo severity while attaching contextual attributes from ctx.
func Logger ¶
Logger retrieves a logger stored in ctx via ContextWithLogger. If no logger is found, slog.Default() is returned to ensure callers always receive a usable logger.
func NoticeContext ¶
NoticeContext logs a message at notice severity for operational events that should page responders but do not indicate an outage.
func PrepareHTTPRequest ¶
func PrepareHTTPRequest(req *HTTPRequest)
PrepareHTTPRequest normalizes an HTTPRequest for logging by ensuring derived fields are populated and by detaching the original *http.Request to avoid repeated expansion during JSON serialization. The function is safe to call multiple times.
func ReportError ¶
func ReportError(ctx context.Context, logger *slog.Logger, err error, msg string, opts ...ErrorReportingOption)
ReportError logs err using logger at error level, automatically attaching Cloud Error Reporting metadata. Additional attributes can be provided via opts.
func SkipInternalStackFrame ¶
SkipInternalStackFrame reports whether funcName refers to a frame that belongs to slogcp or runtime internals and should be hidden from user-facing stack traces.
func SpanIDHexToDecimal ¶
SpanIDHexToDecimal converts a 16-char hex span ID to its unsigned decimal representation as required by the legacy X-Cloud-Trace-Context header's SPAN_ID field.
It returns ("", false) if the value cannot be parsed.
func TraceAttributes ¶
TraceAttributes extracts Cloud Trace aware attributes from ctx. The returned slice can be supplied to logger.With to correlate logs with traces when emitting per-request loggers. When a project ID is known this helper emits the Cloud Logging correlation fields (`logging.googleapis.com/trace`, `logging.googleapis.com/spanId`, and `logging.googleapis.com/trace_sampled`). When no project ID can be determined it falls back to OpenTelemetry-style keys (`otel.trace_id`, `otel.span_id`, and `otel.trace_sampled`).
When projectID is empty, the helper resolves project IDs in this order: explicit argument, context override, then environment variables in the following order: SLOGCP_TRACE_PROJECT_ID, SLOGCP_PROJECT_ID, SLOGCP_GCP_PROJECT, GOOGLE_CLOUD_PROJECT, GCLOUD_PROJECT, and GCP_PROJECT.
func TraceProjectIDFromContext ¶ added in v1.2.0
TraceProjectIDFromContext returns the normalized trace project ID override stored in ctx, when present.
Types ¶
type CloseTimeoutPolicy ¶ added in v1.2.0
type CloseTimeoutPolicy int
CloseTimeoutPolicy controls what Handler.Close does when async graceful shutdown reaches its flush timeout.
const ( // CloseTimeoutAutoAbort keeps backward-compatible Close behavior: if // graceful async close times out, Close escalates to forceful abort before // closing owned resources. CloseTimeoutAutoAbort CloseTimeoutPolicy = iota // CloseTimeoutReturn keeps Close in graceful-only mode on timeout. Close // returns the timeout error and leaves owned resources open so in-flight // async workers are not interrupted by a concurrent sink close. CloseTimeoutReturn )
type CompositePropagator ¶ added in v1.2.0
type CompositePropagator struct {
// contains filtered or unexported fields
}
CompositePropagator wraps slogcp's recommended OpenTelemetry text map propagator composition.
func NewCompositePropagator ¶ added in v1.2.0
func NewCompositePropagator() CompositePropagator
NewCompositePropagator returns slogcp's recommended composite propagator.
The returned propagator:
- Extracts the legacy X-Cloud-Trace-Context header (read-only).
- Extracts and injects W3C Trace Context headers.
- Extracts and injects baggage.
This helper does not mutate process-wide OpenTelemetry globals.
func (CompositePropagator) Extract ¶ added in v1.2.0
func (p CompositePropagator) Extract(ctx context.Context, carrier propagation.TextMapCarrier) context.Context
Extract reads propagation fields from the supplied carrier into context.
func (CompositePropagator) Fields ¶ added in v1.2.0
func (p CompositePropagator) Fields() []string
Fields returns the set of headers this propagator reads or writes.
func (CompositePropagator) Inject ¶ added in v1.2.0
func (p CompositePropagator) Inject(ctx context.Context, carrier propagation.TextMapCarrier)
Inject writes propagation fields into the supplied carrier.
type ErrorReportingOption ¶
type ErrorReportingOption func(*errorReportingConfig)
ErrorReportingOption configures ErrorReportingAttrs and ReportError.
func WithErrorMessage ¶
func WithErrorMessage(msg string) ErrorReportingOption
WithErrorMessage overrides the message field embedded in the structured payload.
func WithErrorServiceContext ¶
func WithErrorServiceContext(service, version string) ErrorReportingOption
WithErrorServiceContext sets the service.name and version used for Cloud Error Reporting. When omitted slogcp attempts to infer these values from the execution environment (Cloud Run, Cloud Functions, etc).
type HTTPRequest ¶
type HTTPRequest struct {
// Request is the original HTTP request. It is used for extracting
// high-level details such as method, URL, headers, and protocol. The
// request body is not logged.
Request *http.Request
// RequestMethod is the HTTP method, if known. When Request is non-nil this
// is populated automatically.
RequestMethod string
// RequestURL is the full request URL string. When Request is non-nil this
// is derived from Request.URL.
RequestURL string
// RequestSize is the size of the request in bytes. When unknown, it may be
// set to -1.
RequestSize int64
// Status is the HTTP response status code.
Status int
// ResponseSize is the size of the response in bytes. When unknown, it may
// be set to -1.
ResponseSize int64
// Latency is the time between when the request was received and when the
// response was sent.
Latency time.Duration
// RemoteIP is the IP address of the client that sent the request.
RemoteIP string
// LocalIP is the IP address of the server that handled the request.
LocalIP string
// UserAgent is the user agent string of the client, if known.
UserAgent string
// Referer is the HTTP referer header of the request, if any.
Referer string
// Protocol is the protocol used for the request, such as "HTTP/1.1".
Protocol string
// CacheHit reports whether the response was served from cache.
CacheHit bool
// CacheValidatedWithOriginServer reports whether the cache entry was
// validated with the origin server before being served.
CacheValidatedWithOriginServer bool
// CacheFillBytes is the number of bytes inserted into cache as a result of
// the request.
CacheFillBytes int64
// CacheLookup reports whether the request was a cache lookup.
CacheLookup bool
}
HTTPRequest mirrors the Cloud Logging HTTP request payload stored in LogEntry.http_request / httpRequest. It is shaped after the google.logging.type.HttpRequest proto message (see Cloud Logging RPC) and matches the JSON schema described at Cloud Logging REST. The corresponding Go proto type is google.golang.org/genproto/googleapis/logging/type.HttpRequest.
func HTTPRequestFromRequest ¶
func HTTPRequestFromRequest(r *http.Request) *HTTPRequest
HTTPRequestFromRequest constructs an HTTPRequest from a standard library *http.Request, normalizing it via PrepareHTTPRequest. It is useful when you need to emit Cloud Logging-compatible httpRequest payloads without using the slogcphttp middleware helpers.
func (*HTTPRequest) LogValue ¶
func (req *HTTPRequest) LogValue() slog.Value
LogValue implements slog.LogValuer so HTTPRequest payloads render using the Cloud Logging httpRequest schema even when emitted through generic slog handlers.
type Handler ¶
Handler routes slog records to Google Cloud Logging with optional middlewares, stack traces and trace correlation.
JSON payload emission is best-effort. If a field value cannot be encoded by encoding/json, slogcp replaces the failing top-level field with a stable "!ERROR:<cause>" placeholder and retries once so one unsupported value does not drop the entire entry.
func NewHandler ¶
NewHandler builds a Google Cloud aware slog Handler. It inspects the environment for configuration overrides and then applies any provided Option values. The handler writes to defaultWriter unless a redirect option or environment override is provided. Encoding failures are handled with a single sanitize-and-retry pass described in Handler.
Example:
h, err := slogcp.NewHandler(os.Stdout,
slogcp.WithLevel(slog.LevelInfo),
)
if err != nil {
log.Fatal(err)
}
logger := slog.New(h)
logger.Info("ready")
func (*Handler) Abort ¶ added in v1.2.0
Abort performs forceful async shutdown (bounded by ctx) and then closes owned resources. When ctx expires first, Abort returns promptly while the underlying async abort may still be finishing in the background.
func (*Handler) Close ¶
Close releases any resources owned by the handler such as log files or writer implementations created by options. It first runs async shutdown via the configured flush timeout.
On timeout, behavior depends on CloseTimeoutPolicy:
- CloseTimeoutAutoAbort (default): Close escalates to abort, then closes owned resources.
- CloseTimeoutReturn: Close returns timeout errors without aborting and leaves owned resources open.
func (*Handler) LevelVar ¶
LevelVar returns the underlying slog.LevelVar used to gate records. It can be integrated with external configuration systems for dynamic level control.
func (*Handler) ReopenLogFile ¶
ReopenLogFile rotates the handler's file writer when logging to a file. If the handler is not writing to a file the method is a no-op.
type Level ¶
Level represents the severity of a log event, extending slog.Level to include all Google Cloud Logging severity levels. It maintains the underlying integer representation compatible with slog.Level.
Google Cloud Logging has 9 severity levels (DEFAULT, DEBUG, INFO, NOTICE, WARNING, ERROR, CRITICAL, ALERT, EMERGENCY) while standard slog has only 4 (DEBUG, INFO, WARN, ERROR). This type bridges that gap by defining additional levels that map directly to GCP severities, allowing applications to use the full range of GCP logging levels while remaining compatible with slog.
The integer values are chosen to maintain ordering and compatibility with the standard slog levels, allowing natural comparison operations.
const ( // LevelDebug maps to GCP DEBUG (100) severity, directly corresponding to // the standard slog.LevelDebug (-4). This level is used for detailed debugging // information that would be excessive at higher levels. LevelDebug Level = Level(slog.LevelDebug) // -4 // LevelInfo maps to GCP INFO (200) severity, directly corresponding to // the standard slog.LevelInfo (0). This is the default level for routine // operational messages confirming normal operation. LevelInfo Level = Level(slog.LevelInfo) // 0 // LevelNotice maps to GCP NOTICE (300) severity. This sits between Info and // Warn, used for significant but expected events worth highlighting. LevelNotice Level = 2 // LevelWarn maps to GCP WARNING (400) severity, directly corresponding to // the standard slog.LevelWarn (4). Used for potentially harmful situations // or unexpected states that might indicate a problem. LevelWarn Level = Level(slog.LevelWarn) // 4 // LevelError maps to GCP ERROR (500) severity, directly corresponding to // the standard slog.LevelError (8). Used for runtime errors that require // attention but don't necessarily impact overall application function. LevelError Level = Level(slog.LevelError) // 8 // LevelCritical maps to GCP CRITICAL (600) severity. This is more severe // than Error, used for severe runtime errors that prevent some function. LevelCritical Level = 12 // LevelAlert maps to GCP ALERT (700) severity. This indicates that action // must be taken immediately, such as when a component becomes unavailable. LevelAlert Level = 16 // LevelEmergency maps to GCP EMERGENCY (800) severity. The highest severity // level, used when the system is unusable or in a catastrophic failure. LevelEmergency Level = 20 // LevelDefault maps to GCP DEFAULT (0) severity. This is used for unspecified // or unknown severity and intentionally sorts above the other levels so that // default-severity entries are never filtered out by minimum level settings. LevelDefault Level = 30 )
Constants for GCP severity levels, mapped onto slog.Level integer values. The values are chosen to maintain order and provide some spacing, aligning with the slog philosophy while covering all GCP levels.
func (Level) Level ¶
Level returns the underlying slog.Level value. This method allows slogcp.Level to satisfy the slog.Leveler interface, enabling its use in places like slog.HandlerOptions.Level and the standard slog.Logger methods.
The slog.Leveler interface requires a Level() method that returns slog.Level. By implementing this method, Level can be used anywhere a standard slog level is expected. This seamless integration means you can pass a slogcp.Level to functions expecting a slog.Leveler, such as:
- As the Level field in slog.HandlerOptions
- When creating a new slog.LevelVar via Set()
- In comparison operations with standard slog levels
func (Level) String ¶
String returns the canonical string representation of the Level, matching Google Cloud Logging severity names where applicable (e.g., "DEBUG", "NOTICE", "ERROR"). For levels between defined constants, it returns the name of the nearest lower defined level plus the offset (e.g., "DEFAULT+1", "INFO+1", "NOTICE+1").
This representation is used by the JSON handler for the "severity" field and provides a human-readable form of the level for debugging and display. Note that when logging to GCP, the String representation is not used directly; the numeric value is mapped to the appropriate GCP severity.
type Middleware ¶
Middleware adapts a slog.Handler before it is exposed by Handler. Middleware functions run in the order they are supplied, wrapping the core handler pipeline from last to first to mirror idiomatic HTTP middleware composition.
type Option ¶
type Option func(*options)
Option mutates Handler construction behaviour when supplied to NewHandler.
Options follow the functional options pattern and are applied in the order they are provided by the caller.
func WithAdditionalHandlers ¶ added in v1.2.0
WithAdditionalHandlers fans out accepted records to additional handlers using slog.NewMultiHandler. Nil handlers are ignored.
Additional handlers are not owned by slogcp. If they require shutdown (for example, async wrappers), close them explicitly. Additional sinks are wrapped with sharedLevelHandler so they use slogcp's shared level threshold. When a sink fails, the wrapped error remains unwrappable (errors.Is/errors.As) and MultiHandler aggregates sink failures.
func WithAsync ¶
func WithAsync(opts ...slogcpasync.Option) Option
WithAsync wraps the constructed handler in slogcpasync using tuned per-mode defaults. Supply slogcpasync options to override queue, workers, drop mode, or batch size.
func WithAsyncOnFile ¶ added in v1.1.0
func WithAsyncOnFile(opts ...slogcpasync.Option) Option
WithAsyncOnFile applies slogcpasync only when logging to a file target. It keeps stdout/stderr handlers synchronous while letting callers tune (or disable) file buffering.
func WithAttrs ¶
WithAttrs preloads static attributes to be attached to every record emitted by the handler.
func WithCloseTimeoutPolicy ¶ added in v1.2.0
func WithCloseTimeoutPolicy(policy CloseTimeoutPolicy) Option
WithCloseTimeoutPolicy configures how Handler.Close behaves when async graceful shutdown reaches its flush timeout.
The default is CloseTimeoutAutoAbort. Use CloseTimeoutReturn to make Close return timeout errors without aborting or closing owned resources.
func WithInternalLogger ¶
WithInternalLogger injects an internal logger used for diagnostics during handler setup and lifecycle operations.
func WithLevelVar ¶
WithLevelVar shares the provided slog.LevelVar with the handler, allowing external code to adjust log levels at runtime while keeping slogcp's internal state in sync. When supplied, slogcp initialises the LevelVar to the resolved minimum level (defaults, environment, then WithLevel) during handler construction.
func WithMiddleware ¶
func WithMiddleware(mw Middleware) Option
WithMiddleware appends a middleware that can modify or short-circuit record handling.
func WithRedirectToFile ¶
WithRedirectToFile directs handler output to the file at path, creating it if necessary. The path is trimmed of surrounding whitespace and then passed verbatim to os.OpenFile in append mode; parent directories must already exist. When configuring the same behaviour via SLOGCP_TARGET use "file:<path>" with an OS-specific path string (for example, "file:/var/log/app.log" or "file:C:\\logs\\app.log").
func WithRedirectToStderr ¶
func WithRedirectToStderr() Option
WithRedirectToStderr forces the handler to emit logs to stderr.
func WithRedirectToStdout ¶
func WithRedirectToStdout() Option
WithRedirectToStdout forces the handler to emit logs to stdout.
func WithRedirectWriter ¶
WithRedirectWriter uses writer for log output without taking ownership of its lifecycle. Any file paths configured on the writer itself are interpreted by that writer; slogcp does not parse "file:" targets when this option is used.
func WithReplaceAttr ¶
WithReplaceAttr installs a slog attribute replacer mirroring slog.HandlerOptions.ReplaceAttr.
func WithSeverityAliases ¶
WithSeverityAliases configures whether the handler emits Cloud Logging severity aliases (for example, "I" for INFO) instead of the full severity names. Using the aliases trims roughly a nanosecond from JSON marshaling, and Cloud Logging still displays the canonical severity names after ingestion. On a detected GCP runtime the aliases remain enabled by default; otherwise they must be explicitly enabled through options or environment variables.
func WithSourceLocationEnabled ¶
WithSourceLocationEnabled toggles source location enrichment on emitted records when true.
func WithStackTraceEnabled ¶
WithStackTraceEnabled toggles automatic stack trace capture for error logs when enabled.
func WithStackTraceLevel ¶
WithStackTraceLevel captures stack traces for records at or above level. The handler defaults to slog.LevelError when this option is omitted.
func WithTime ¶
WithTime toggles emission of the top-level "time" field. By default slogcp omits timestamps on managed GCP runtimes such as Cloud Run or App Engine when writing to stdout/stderr, since Cloud Logging stamps entries automatically. File targets keep timestamps by default so rotated or shipped logs retain them. Enabling this option stops slogcp from suppressing `log/slog`'s default timestamp behavior.
func WithTraceDiagnostics ¶
func WithTraceDiagnostics(mode TraceDiagnosticsMode) Option
WithTraceDiagnostics adjusts how slogcp reports trace correlation issues.
func WithTraceProjectID ¶
WithTraceProjectID overrides the Cloud Trace project identifier used to format logging.googleapis.com/trace URLs.
type RuntimeEnvironment ¶
type RuntimeEnvironment int
RuntimeEnvironment describes the runtime platform detected for slogcp.
const ( // RuntimeEnvUnknown indicates slogcp could not detect a known hosting environment. RuntimeEnvUnknown RuntimeEnvironment = iota // RuntimeEnvCloudRunService indicates execution on Cloud Run fully managed. RuntimeEnvCloudRunService // RuntimeEnvCloudRunJob indicates execution on Cloud Run jobs. RuntimeEnvCloudRunJob // RuntimeEnvCloudFunctions indicates execution on Cloud Functions. RuntimeEnvCloudFunctions // RuntimeEnvAppEngineStandard indicates execution on App Engine standard. RuntimeEnvAppEngineStandard // RuntimeEnvAppEngineFlexible indicates execution on App Engine flexible. RuntimeEnvAppEngineFlexible // RuntimeEnvKubernetes indicates execution on Kubernetes (including Google Kubernetes Engine). RuntimeEnvKubernetes // RuntimeEnvComputeEngine indicates execution on Compute Engine. RuntimeEnvComputeEngine )
type RuntimeInfo ¶
type RuntimeInfo struct {
ProjectID string
Labels map[string]string
ServiceContext map[string]string
Environment RuntimeEnvironment
}
RuntimeInfo captures metadata about the current cloud environment.
func DetectRuntimeInfo ¶
func DetectRuntimeInfo() RuntimeInfo
DetectRuntimeInfo inspects well-known environment variables to infer platform-specific labels and service context. Results are cached for reuse.
type SwitchableWriter ¶
type SwitchableWriter struct {
// contains filtered or unexported fields
}
SwitchableWriter is an io.Writer that allows its underlying writer to be changed atomically. It is used internally when slogcp is configured to log to a specific file path (for example, via WithRedirectToFile) so that Handler.ReopenLogFile can update the output destination without rebuilding the entire handler chain.
SwitchableWriter also implements io.Closer. Its Close method attempts to close the underlying writer if it implements io.Closer and then sets the internal writer to io.Discard to prevent further writes. The actual closing of file resources managed by slogcp is handled by the Handler itself.
func NewSwitchableWriter ¶
func NewSwitchableWriter(initialWriter io.Writer) *SwitchableWriter
NewSwitchableWriter creates a new SwitchableWriter, initializing it with the provided initialWriter. If initialWriter is nil, the SwitchableWriter defaults to using io.Discard.
func (*SwitchableWriter) Close ¶
func (sw *SwitchableWriter) Close() error
Close attempts to close the current underlying writer if it implements io.Closer. After attempting to close the writer (or if it is not closable), the SwitchableWriter's internal writer is set to io.Discard to prevent further writes. This method is safe for concurrent use and idempotent.
func (*SwitchableWriter) GetCurrentWriter ¶
func (sw *SwitchableWriter) GetCurrentWriter() io.Writer
GetCurrentWriter returns the current underlying io.Writer that this SwitchableWriter is directing writes to. This method is safe for concurrent use but callers should avoid holding on to the returned writer across calls to SetWriter.
func (*SwitchableWriter) SetWriter ¶
func (sw *SwitchableWriter) SetWriter(newWriter io.Writer)
SetWriter atomically updates the underlying writer for this SwitchableWriter. The previously configured writer is not closed by this method; managing its lifecycle is the caller's responsibility. If newWriter is nil, the SwitchableWriter will subsequently direct writes to io.Discard.
func (*SwitchableWriter) Write ¶
func (sw *SwitchableWriter) Write(p []byte) (n int, err error)
Write directs the given bytes to the current underlying writer. It is safe for concurrent use. If the SwitchableWriter has been closed or its writer set to nil, Write may return an error (such as os.ErrClosed).
type TraceDiagnosticsMode ¶
type TraceDiagnosticsMode int
TraceDiagnosticsMode controls how slogcp surfaces trace correlation issues.
const ( // TraceDiagnosticsOff disables trace correlation diagnostics. TraceDiagnosticsOff TraceDiagnosticsMode = iota // TraceDiagnosticsWarnOnce emits a single warning when trace correlation cannot be established. TraceDiagnosticsWarnOnce // TraceDiagnosticsStrict fails handler construction when trace correlation cannot be established. TraceDiagnosticsStrict )
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package slogcpasync adds an opt-in async wrapper around slogcp's synchronous handler.
|
Package slogcpasync adds an opt-in async wrapper around slogcp's synchronous handler. |
|
Package slogcpgrpc provides gRPC interceptors that integrate slogcp with Google Cloud Logging and OpenTelemetry.
|
Package slogcpgrpc provides gRPC interceptors that integrate slogcp with Google Cloud Logging and OpenTelemetry. |
|
Package slogcphttp provides net/http integration for slogcp.
|
Package slogcphttp provides net/http integration for slogcp. |
|
Package slogcppubsub provides Pub/Sub helpers for slogcp.
|
Package slogcppubsub provides Pub/Sub helpers for slogcp. |