logging

package
v8.0.74 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: MIT Imports: 34 Imported by: 0

Documentation

Overview

Package logging provides Gin middleware for HTTP request logging and panic recovery. It integrates Gin web framework with logrus for structured logging of HTTP requests, responses, and error handling with panic recovery capabilities.

Package logging provides request logging functionality for the CLI Proxy API server. It handles capturing and storing detailed HTTP request and response data when enabled through configuration, supporting both regular and streaming responses.

Index

Constants

View Source
const (
	// MaxDeferredAPIRequestBodyBytes bounds total deferred upstream request bodies per HTTP request.
	MaxDeferredAPIRequestBodyBytes = 32 << 20 // 32 MiB
	// MaxDeferredAPIResponseBodyBytes bounds each upstream attempt's deferred response body.
	MaxDeferredAPIResponseBodyBytes = 64 << 10 // 64 KiB
	// MaxDeferredAPIResponseHeaderBytes bounds cloned response headers per upstream attempt.
	MaxDeferredAPIResponseHeaderBytes = 16 << 10 // 16 KiB
	// MaxDeferredAPIResponseErrorBytes bounds each recorded upstream error string.
	MaxDeferredAPIResponseErrorBytes = 16 << 10 // 16 KiB
	// MaxTotalDeferredAPIResponseBodyBytes bounds total deferred upstream response payload
	// (body chunks, headers, and error strings) across retries for a single HTTP request.
	MaxTotalDeferredAPIResponseBodyBytes = 512 << 10 // 512 KiB
	// MaxDeferredAPIResponseAttempts bounds the number of upstream response attempt slots retained per HTTP request.
	MaxDeferredAPIResponseAttempts = 16
)
View Source
const (
	WebsocketTimelineSourceContextKey    = "WEBSOCKET_TIMELINE_SOURCE"
	APIRequestSourceContextKey           = "API_REQUEST_SOURCE"
	DeferredAPIRequestContextKey         = "DEFERRED_API_REQUEST"
	DeferredAPIResponseContextKey        = "DEFERRED_API_RESPONSE"
	APIResponseSourceContextKey          = "API_RESPONSE_SOURCE"
	APIResponseCapturedContextKey        = "API_RESPONSE_CAPTURED"
	APIWebsocketTimelineSourceContextKey = "API_WEBSOCKET_TIMELINE_SOURCE"
)
View Source
const CPATraceIDHeader = "X-CPA-TRACE-ID"

CPATraceIDHeader is the downstream response header used to correlate requests with selected credentials.

Variables

This section is empty.

Functions

func CPATraceIDMiddleware

func CPATraceIDMiddleware() gin.HandlerFunc

CPATraceIDMiddleware injects a stored trace ID immediately before response headers are committed.

func ConfigureLogOutput

func ConfigureLogOutput(cfg *config.Config) error

ConfigureLogOutput switches the global log destination between rotating files and stdout. When logsMaxTotalSizeMB > 0, a background cleaner removes the oldest log files in the logs directory until the total size is within the limit.

func DeferredAPIRequestCaptureDisabled added in v8.0.48

func DeferredAPIRequestCaptureDisabled(ctx context.Context) bool

DeferredAPIRequestCaptureDisabled reports whether error-only capture is disabled.

func FormatCPATraceID

func FormatCPATraceID(selectedAt time.Time, authIndex, requestID string) string

FormatCPATraceID builds a CPA trace ID from the selection time, auth index, and request ID.

func GenerateRequestID

func GenerateRequestID() (string, error)

GenerateRequestID creates a new UUIDv7 request ID string using the default random source. It returns an error if the underlying random source fails.

func GenerateRequestIDFromReader added in v8.0.4

func GenerateRequestIDFromReader(r io.Reader) (string, error)

GenerateRequestIDFromReader creates a new UUIDv7 request ID string using the provided reader. If r is nil, the default crypto/rand source is used.

func GetEndpoint

func GetEndpoint(ctx context.Context) string

func GetGinCPATraceID

func GetGinCPATraceID(c *gin.Context) string

GetGinCPATraceID returns the trace ID stored for the current request.

func GetGinRequestID

func GetGinRequestID(c *gin.Context) string

GetGinRequestID retrieves the request ID from the Gin context.

func GetRequestID

func GetRequestID(ctx context.Context) string

GetRequestID retrieves the request ID from the context. Returns empty string if not found.

func GetResponseHeaders

func GetResponseHeaders(ctx context.Context) http.Header

func GetResponseStatus

func GetResponseStatus(ctx context.Context) int

func GinCPATraceIDCallback

func GinCPATraceIDCallback(c *gin.Context) func(string)

GinCPATraceIDCallback returns a callback that is safe to invoke after the Gin context is released.

func GinLogrusLogger

func GinLogrusLogger() gin.HandlerFunc

GinLogrusLogger returns a Gin middleware handler that logs HTTP requests and responses using logrus. It captures request details including method, path, status code, latency, client IP, and any error messages. Request ID is only added for AI API requests.

Output format (AI API): [2025-12-23 20:14:10] [info ] | a1b2c3d4 | 200 | 23.559s | ... Output format (others): [2025-12-23 20:14:10] [info ] | -------- | 200 | 23.559s | ...

Returns:

  • gin.HandlerFunc: A middleware handler for request logging

func GinLogrusRecovery

func GinLogrusRecovery() gin.HandlerFunc

GinLogrusRecovery returns a Gin middleware handler that recovers from panics and logs them using logrus. When a panic occurs, it captures the panic value, stack trace, and request path, then returns a 500 Internal Server Error response to the client.

Returns:

  • gin.HandlerFunc: A middleware handler for panic recovery

func InheritDeferredCapture added in v8.0.65

func InheritDeferredCapture(dst, src context.Context) context.Context

InheritDeferredCapture propagates error-only capture policy and any request-scoped DeferredAPICapture holder from src to dst.

func MergeResponseHeaders

func MergeResponseHeaders(ctx context.Context, headers http.Header)

MergeResponseHeaders adds headers observed after the initial HTTP response, such as quota metadata delivered in a websocket event.

func ResolveLogDirectory

func ResolveLogDirectory(cfg *config.Config) string

ResolveLogDirectory determines the directory used for application logs.

func SafeDiagnosticForLog

func SafeDiagnosticForLog(message string) string

SafeDiagnosticForLog returns a bounded, single-line diagnostic suitable for ordinary application logs. It preserves the access-token-expired signal while redacting credential values and URL userinfo.

func SafeErrorDiagnostic

func SafeErrorDiagnostic(err error) string

SafeErrorDiagnostic extracts only allowlisted failure signals from an arbitrary error. It never carries the original free-form error text.

func SetGinCPATraceID

func SetGinCPATraceID(c *gin.Context, authIndex string)

SetGinCPATraceID stores the trace ID until the downstream response headers are committed.

func SetGinRequestID

func SetGinRequestID(c *gin.Context, requestID string)

SetGinRequestID stores the request ID in the Gin context.

func SetResponseHeaders

func SetResponseHeaders(ctx context.Context, headers http.Header)

func SetResponseStatus

func SetResponseStatus(ctx context.Context, status int)

func SetupBaseLogger

func SetupBaseLogger()

SetupBaseLogger configures the shared logrus instance and Gin writers. It is safe to call multiple times; initialization happens only once.

func ShortRequestID added in v8.0.4

func ShortRequestID(requestID string) string

ShortRequestID returns the trailing 8 characters of a request ID. If requestID is 8 characters or shorter, it returns it unchanged.

func SkipGinRequestLogging

func SkipGinRequestLogging(c *gin.Context)

SkipGinRequestLogging marks the provided Gin context so that GinLogrusLogger will skip emitting a log line for the associated request.

func WithClientRequestMetadata

func WithClientRequestMetadata(ctx context.Context, metadata ClientRequestMetadata) context.Context

WithClientRequestMetadata stores a snapshot of downstream request metadata in ctx.

func WithDeferredAPICapture added in v8.0.65

func WithDeferredAPICapture(ctx context.Context, capture *DeferredAPICapture) context.Context

WithDeferredAPICapture attaches a request-scoped DeferredAPICapture to ctx so background stream producers record into the request's own synchronized holder without accessing a pooled Gin context.

func WithDeferredAPIRequestCaptureDisabled added in v8.0.48

func WithDeferredAPIRequestCaptureDisabled(ctx context.Context) context.Context

WithDeferredAPIRequestCaptureDisabled skips error-only upstream request and response capture for this context and its descendants. Full request logging is unaffected. Connection-scoped contexts keep this policy even when asynchronous callbacks outlive the handler and its pooled Gin context is reused.

func WithEndpoint

func WithEndpoint(ctx context.Context, endpoint string) context.Context

func WithFreshResponseHeadersHolder

func WithFreshResponseHeadersHolder(ctx context.Context) context.Context

WithFreshResponseHeadersHolder starts an isolated upstream response attempt. Unlike WithResponseHeadersHolder, it always shadows any holder inherited from the parent request so a later retry cannot observe headers from an earlier credential or model attempt.

func WithRequestID

func WithRequestID(ctx context.Context, requestID string) context.Context

WithRequestID returns a new context with the request ID attached.

func WithResponseHeadersHolder

func WithResponseHeadersHolder(ctx context.Context) context.Context

func WithResponseStatusHolder

func WithResponseStatusHolder(ctx context.Context) context.Context

Types

type ClientRequestMetadata

type ClientRequestMetadata struct {
	ClientIP         string
	ResolvedClientIP string
	XForwardedFor    string
	UserAgent        string
	SessionID        string
	ParentSessionID  string
	NodeKind         string
	IsFork           bool
	IsCompaction     bool
}

ClientRequestMetadata stores immutable downstream request metadata for asynchronous consumers.

func GetClientRequestMetadata

func GetClientRequestMetadata(ctx context.Context) ClientRequestMetadata

GetClientRequestMetadata returns downstream request metadata stored in ctx.

type DeferredAPICapture added in v8.0.65

type DeferredAPICapture struct {
	// contains filtered or unexported fields
}

DeferredAPICapture retains bounded upstream request and response details for a single HTTP request while full request logging is disabled. All operations are synchronized and become no-ops after Close so asynchronous stream workers cannot race with Finalize or leak into a reused Gin context.

func DeferredAPICaptureFromContext added in v8.0.65

func DeferredAPICaptureFromContext(ctx context.Context) *DeferredAPICapture

DeferredAPICaptureFromContext returns the request-scoped DeferredAPICapture carried by ctx, if any.

func NewDeferredAPICapture added in v8.0.65

func NewDeferredAPICapture() *DeferredAPICapture

NewDeferredAPICapture constructs a fresh request-scoped DeferredAPICapture.

func (*DeferredAPICapture) AppendResponseChunk added in v8.0.65

func (c *DeferredAPICapture) AppendResponseChunk(chunk []byte)

AppendResponseChunk appends a bounded response chunk to the latest attempt.

func (*DeferredAPICapture) AttemptBodyStats added in v8.0.65

func (c *DeferredAPICapture) AttemptBodyStats(i int) (length int, capacity int, truncated bool)

AttemptBodyStats returns the captured body length, slice capacity, and truncation flag for the given 0-based attempt slot.

func (*DeferredAPICapture) AttemptCapturedAt added in v8.0.65

func (c *DeferredAPICapture) AttemptCapturedAt(i int) time.Time

AttemptCapturedAt returns the captured response timestamp for the given 0-based attempt slot.

func (*DeferredAPICapture) AttemptCount added in v8.0.65

func (c *DeferredAPICapture) AttemptCount() int

AttemptCount returns the number of recorded response attempt slots.

func (*DeferredAPICapture) Close added in v8.0.65

func (c *DeferredAPICapture) Close()

Close marks the capture closed and releases buffered upstream payloads.

func (*DeferredAPICapture) HasPayload added in v8.0.65

func (c *DeferredAPICapture) HasPayload() bool

HasPayload reports whether any attempt recorded upstream response details.

func (*DeferredAPICapture) HasRequests added in v8.0.65

func (c *DeferredAPICapture) HasRequests() bool

HasRequests reports whether any deferred upstream requests were captured.

func (*DeferredAPICapture) IsClosed added in v8.0.65

func (c *DeferredAPICapture) IsClosed() bool

IsClosed reports whether Close has been called.

func (*DeferredAPICapture) RecordOrReplacePendingRequest added in v8.0.65

func (c *DeferredAPICapture) RecordOrReplacePendingRequest(body []byte, build func(index int, capturedAt time.Time, capturedBody []byte, bodyEmpty, bodyTruncated bool) DeferredAPIRequest) (DeferredAPIRequest, int, bool, bool)

RecordOrReplacePendingRequest replaces the trailing request builder when its paired response attempt has recorded no response details yet (for example when a websocket request is immediately rejected during its HTTP upgrade handshake), or appends a new request attempt otherwise.

func (*DeferredAPICapture) RecordRequest added in v8.0.65

func (c *DeferredAPICapture) RecordRequest(body []byte, build func(index int, capturedAt time.Time, capturedBody []byte, bodyEmpty, bodyTruncated bool) DeferredAPIRequest) (DeferredAPIRequest, int, bool)

RecordRequest stores a deferred upstream request builder within MaxDeferredAPIRequestBodyBytes and opens the paired upstream response attempt slot.

func (*DeferredAPICapture) RecordResponseError added in v8.0.65

func (c *DeferredAPICapture) RecordResponseError(err error)

RecordResponseError appends a bounded transport or stream error to the latest attempt.

func (*DeferredAPICapture) RecordResponseMetadata added in v8.0.65

func (c *DeferredAPICapture) RecordResponseMetadata(status int, headers http.Header)

RecordResponseMetadata records the HTTP status and bounded cloned headers for the latest attempt.

func (*DeferredAPICapture) RenderAPIRequests added in v8.0.65

func (c *DeferredAPICapture) RenderAPIRequests() []byte

RenderAPIRequests renders all captured upstream request sections.

func (*DeferredAPICapture) RenderAPIResponse added in v8.0.65

func (c *DeferredAPICapture) RenderAPIResponse() []byte

RenderAPIResponse formats captured upstream response attempts for error logs.

func (*DeferredAPICapture) TotalResponseBodyBytes added in v8.0.65

func (c *DeferredAPICapture) TotalResponseBodyBytes() int

TotalResponseBodyBytes returns the total captured upstream response bytes across attempts.

type DeferredAPIRequest

type DeferredAPIRequest func() []byte

DeferredAPIRequest builds an upstream request log only when an error log needs it.

type DeferredAPIResponse added in v8.0.65

type DeferredAPIResponse interface {
	// HasPayload reports whether any upstream response metadata, body, or error was captured.
	HasPayload() bool
	// RenderAPIResponse returns the formatted "=== API RESPONSE n ===" attempt
	// sections, or nil when no upstream response details were captured.
	RenderAPIResponse() []byte
}

DeferredAPIResponse renders the upstream response attempt sections of an error log from details captured while full request logging is disabled.

type FileBodySource

type FileBodySource struct {
	// contains filtered or unexported fields
}

FileBodySource stores large log sections as ordered temp-file parts.

func NewFileBodySourceInDir

func NewFileBodySourceInDir(baseDir string, prefix string) (*FileBodySource, error)

NewFileBodySourceInDir creates a temp-backed source under baseDir.

func (*FileBodySource) AppendBytes

func (s *FileBodySource) AppendBytes(data []byte) error

AppendBytes appends raw bytes to a single ordered part.

func (*FileBodySource) AppendPart

func (s *FileBodySource) AppendPart(data []byte) error

AppendPart appends one complete ordered part to the source.

func (*FileBodySource) Bytes

func (s *FileBodySource) Bytes() ([]byte, error)

Bytes merges all ordered parts into memory.

func (*FileBodySource) Cleanup

func (s *FileBodySource) Cleanup() error

Cleanup removes all temp detail parts and their directory.

func (*FileBodySource) CreatePart

func (s *FileBodySource) CreatePart(prefix string) (*os.File, error)

CreatePart creates one ordered detail log part.

func (*FileBodySource) HasPayload

func (s *FileBodySource) HasPayload() bool

HasPayload reports whether any detail parts were recorded.

func (*FileBodySource) Paths

func (s *FileBodySource) Paths() []string

Paths returns a copy of the ordered part paths.

func (*FileBodySource) WriteTo

func (s *FileBodySource) WriteTo(w io.Writer) (int64, error)

WriteTo merges all ordered parts into w.

type FileRequestLogger

type FileRequestLogger struct {
	// contains filtered or unexported fields
}

FileRequestLogger implements RequestLogger using file-based storage. It provides file-based logging functionality for HTTP requests and responses.

func NewFileRequestLogger

func NewFileRequestLogger(enabled bool, logsDir string, configDir string, errorLogsMaxFiles int) *FileRequestLogger

NewFileRequestLogger creates a new file-based request logger.

Parameters:

  • enabled: Whether request logging should be enabled
  • logsDir: The directory where log files should be stored (can be relative)
  • configDir: The directory of the configuration file; when logsDir is relative, it will be resolved relative to this directory
  • errorLogsMaxFiles: Maximum number of error log files to retain (0 = no cleanup)

Returns:

  • *FileRequestLogger: A new file-based request logger instance

func (*FileRequestLogger) IsEnabled

func (l *FileRequestLogger) IsEnabled() bool

IsEnabled returns whether request logging is currently enabled.

Returns:

  • bool: True if logging is enabled, false otherwise

func (*FileRequestLogger) LogRequest

func (l *FileRequestLogger) LogRequest(url, method string, requestHeaders map[string][]string, body []byte, statusCode int, responseHeaders map[string][]string, response, websocketTimeline, apiRequest, apiResponse, apiWebsocketTimeline []byte, apiResponseErrors []*interfaces.ErrorMessage, requestID string, requestTimestamp, apiResponseTimestamp time.Time) error

LogRequest logs a complete non-streaming request/response cycle to a file.

Parameters:

  • url: The request URL
  • method: The HTTP method
  • requestHeaders: The request headers
  • body: The request body
  • statusCode: The response status code
  • responseHeaders: The response headers
  • response: The raw response data
  • apiRequest: The API request data
  • apiResponse: The API response data
  • requestID: Optional request ID for log file naming
  • requestTimestamp: When the request was received
  • apiResponseTimestamp: When the API response was received

Returns:

  • error: An error if logging fails, nil otherwise

func (*FileRequestLogger) LogRequestWithOptions

func (l *FileRequestLogger) LogRequestWithOptions(url, method string, requestHeaders map[string][]string, body []byte, statusCode int, responseHeaders map[string][]string, response, websocketTimeline, apiRequest, apiResponse, apiWebsocketTimeline []byte, apiResponseErrors []*interfaces.ErrorMessage, force bool, requestID string, requestTimestamp, apiResponseTimestamp time.Time) error

LogRequestWithOptions logs a request with optional forced logging behavior. The force flag allows writing error logs even when regular request logging is disabled.

func (*FileRequestLogger) LogRequestWithOptionsAndAllSources

func (l *FileRequestLogger) LogRequestWithOptionsAndAllSources(url, method string, requestHeaders map[string][]string, body []byte, statusCode int, responseHeaders map[string][]string, response, websocketTimeline []byte, websocketTimelineSource *FileBodySource, apiRequest []byte, apiRequestSource *FileBodySource, apiResponse []byte, apiResponseSource *FileBodySource, apiWebsocketTimeline []byte, apiWebsocketTimelineSource *FileBodySource, apiResponseErrors []*interfaces.ErrorMessage, force bool, requestID string, requestTimestamp, apiResponseTimestamp time.Time) error

LogRequestWithOptionsAndAllSources logs a request with optional file-backed request and response sections.

func (*FileRequestLogger) LogRequestWithOptionsAndSources

func (l *FileRequestLogger) LogRequestWithOptionsAndSources(url, method string, requestHeaders map[string][]string, body []byte, statusCode int, responseHeaders map[string][]string, response, websocketTimeline []byte, websocketTimelineSource *FileBodySource, apiRequest, apiResponse, apiWebsocketTimeline []byte, apiWebsocketTimelineSource *FileBodySource, apiResponseErrors []*interfaces.ErrorMessage, force bool, requestID string, requestTimestamp, apiResponseTimestamp time.Time) error

LogRequestWithOptionsAndSources logs a request with optional file-backed large sections.

func (*FileRequestLogger) LogStreamingRequest

func (l *FileRequestLogger) LogStreamingRequest(url, method string, headers map[string][]string, body []byte, requestID string) (StreamingLogWriter, error)

LogStreamingRequest initiates logging for a streaming request.

Parameters:

  • url: The request URL
  • method: The HTTP method
  • headers: The request headers
  • body: The request body
  • requestID: Optional request ID for log file naming

Returns:

  • StreamingLogWriter: A writer for streaming response chunks
  • error: An error if logging initialization fails, nil otherwise

func (*FileRequestLogger) NewFileBodySource

func (l *FileRequestLogger) NewFileBodySource(prefix string) (*FileBodySource, error)

NewFileBodySource creates a temp-backed source under the request log directory.

func (*FileRequestLogger) SetEnabled

func (l *FileRequestLogger) SetEnabled(enabled bool)

SetEnabled updates the request logging enabled state. This method allows dynamic enabling/disabling of request logging.

Parameters:

  • enabled: Whether request logging should be enabled

func (*FileRequestLogger) SetErrorLogsMaxFiles

func (l *FileRequestLogger) SetErrorLogsMaxFiles(maxFiles int)

SetErrorLogsMaxFiles updates the maximum number of error log files to retain.

func (*FileRequestLogger) SetHomeEnabled

func (l *FileRequestLogger) SetHomeEnabled(enabled bool)

SetHomeEnabled toggles home request-log forwarding. When enabled, request logs are not written to disk and are instead forwarded to home via Redis RESP.

type FileStreamingLogWriter

type FileStreamingLogWriter struct {
	// contains filtered or unexported fields
}

FileStreamingLogWriter implements StreamingLogWriter for file-based streaming logs. It spools streaming response chunks to a temporary file to avoid retaining large responses in memory. The final log file is assembled when Close is called.

func (*FileStreamingLogWriter) Close

func (w *FileStreamingLogWriter) Close() error

Close finalizes the log file and cleans up resources. It writes all buffered data to the file in the correct order: API WEBSOCKET TIMELINE -> API REQUEST -> API RESPONSE -> RESPONSE (status, headers, body chunks)

Returns:

  • error: An error if closing fails, nil otherwise

func (*FileStreamingLogWriter) Discard added in v8.0.62

func (w *FileStreamingLogWriter) Discard() error

Discard stops the streaming writer and removes temporary files without creating a final log file.

func (*FileStreamingLogWriter) SetFirstChunkTimestamp

func (w *FileStreamingLogWriter) SetFirstChunkTimestamp(timestamp time.Time)

func (*FileStreamingLogWriter) WriteAPIRequest

func (w *FileStreamingLogWriter) WriteAPIRequest(apiRequest []byte) error

WriteAPIRequest buffers the upstream API request details for later writing.

Parameters:

  • apiRequest: The API request data (typically includes URL, headers, body sent upstream)

Returns:

  • error: Always returns nil (buffering cannot fail)

func (*FileStreamingLogWriter) WriteAPIRequestSource

func (w *FileStreamingLogWriter) WriteAPIRequestSource(apiRequestSource *FileBodySource) error

WriteAPIRequestSource buffers a file-backed upstream API request for final writing.

func (*FileStreamingLogWriter) WriteAPIResponse

func (w *FileStreamingLogWriter) WriteAPIResponse(apiResponse []byte) error

WriteAPIResponse buffers the upstream API response details for later writing.

Parameters:

  • apiResponse: The API response data

Returns:

  • error: Always returns nil (buffering cannot fail)

func (*FileStreamingLogWriter) WriteAPIResponseErrors added in v8.0.56

func (w *FileStreamingLogWriter) WriteAPIResponseErrors(errors []*interfaces.ErrorMessage) error

WriteAPIResponseErrors buffers upstream API error entries for final writing.

func (*FileStreamingLogWriter) WriteAPIResponseSource

func (w *FileStreamingLogWriter) WriteAPIResponseSource(apiResponseSource *FileBodySource) error

WriteAPIResponseSource buffers a file-backed upstream API response for final writing.

func (*FileStreamingLogWriter) WriteAPIWebsocketTimeline

func (w *FileStreamingLogWriter) WriteAPIWebsocketTimeline(apiWebsocketTimeline []byte) error

WriteAPIWebsocketTimeline buffers the upstream websocket timeline for later writing.

Parameters:

  • apiWebsocketTimeline: The upstream websocket event timeline

Returns:

  • error: Always returns nil (buffering cannot fail)

func (*FileStreamingLogWriter) WriteChunkAsync

func (w *FileStreamingLogWriter) WriteChunkAsync(chunk []byte)

WriteChunkAsync writes a response chunk asynchronously (non-blocking).

Parameters:

  • chunk: The response chunk to write

func (*FileStreamingLogWriter) WriteStatus

func (w *FileStreamingLogWriter) WriteStatus(status int, headers map[string][]string) error

WriteStatus buffers the response status and headers for later writing.

Parameters:

  • status: The response status code
  • headers: The response headers

Returns:

  • error: Always returns nil (buffering cannot fail)

type HomeAppLogForwarder

type HomeAppLogForwarder struct {
	// contains filtered or unexported fields
}

HomeAppLogForwarder forwards application logs to Home after the control connection is healthy.

func StartHomeAppLogForwarder

func StartHomeAppLogForwarder(queueSize int) *HomeAppLogForwarder

StartHomeAppLogForwarder registers a Home log forwarding target with the process-wide logrus hook.

func (*HomeAppLogForwarder) Bind

func (f *HomeAppLogForwarder) Bind(client *home.Client)

Bind activates forwarding to client.

func (*HomeAppLogForwarder) Deactivate

func (f *HomeAppLogForwarder) Deactivate(client *home.Client)

Deactivate stops forwarding only when client owns the forwarder.

func (*HomeAppLogForwarder) Fire

func (f *HomeAppLogForwarder) Fire(entry *log.Entry) error

Fire implements logrus.Hook.

func (*HomeAppLogForwarder) Levels

func (f *HomeAppLogForwarder) Levels() []log.Level

Levels implements logrus.Hook.

func (*HomeAppLogForwarder) Stop

func (f *HomeAppLogForwarder) Stop()

Stop disables forwarding and waits for the background sender to exit.

type LogFormatter

type LogFormatter struct{}

LogFormatter defines a custom log format for logrus. This formatter adds timestamp, level, request ID, and source location to each log entry. Format: [2025-12-23 20:14:04] debug [manager.go:524] | a1b2c3d4 | Use API key sk-9...0RHO for model gpt-5.2

func (*LogFormatter) Format

func (m *LogFormatter) Format(entry *log.Entry) ([]byte, error)

Format renders a single log entry with custom formatting.

type NoOpStreamingLogWriter

type NoOpStreamingLogWriter struct{}

NoOpStreamingLogWriter is a no-operation implementation for when logging is disabled. It implements the StreamingLogWriter interface but performs no actual logging operations.

func (*NoOpStreamingLogWriter) Close

func (w *NoOpStreamingLogWriter) Close() error

Close is a no-op implementation that does nothing and always returns nil.

Returns:

  • error: Always returns nil

func (*NoOpStreamingLogWriter) SetFirstChunkTimestamp

func (w *NoOpStreamingLogWriter) SetFirstChunkTimestamp(_ time.Time)

func (*NoOpStreamingLogWriter) WriteAPIRequest

func (w *NoOpStreamingLogWriter) WriteAPIRequest(_ []byte) error

WriteAPIRequest is a no-op implementation that does nothing and always returns nil.

Parameters:

  • apiRequest: The API request data (ignored)

Returns:

  • error: Always returns nil

func (*NoOpStreamingLogWriter) WriteAPIResponse

func (w *NoOpStreamingLogWriter) WriteAPIResponse(_ []byte) error

WriteAPIResponse is a no-op implementation that does nothing and always returns nil.

Parameters:

  • apiResponse: The API response data (ignored)

Returns:

  • error: Always returns nil

func (*NoOpStreamingLogWriter) WriteAPIResponseErrors added in v8.0.56

func (w *NoOpStreamingLogWriter) WriteAPIResponseErrors(_ []*interfaces.ErrorMessage) error

func (*NoOpStreamingLogWriter) WriteAPIWebsocketTimeline

func (w *NoOpStreamingLogWriter) WriteAPIWebsocketTimeline(_ []byte) error

WriteAPIWebsocketTimeline is a no-op implementation that does nothing and always returns nil.

Parameters:

  • apiWebsocketTimeline: The upstream websocket event timeline (ignored)

Returns:

  • error: Always returns nil

func (*NoOpStreamingLogWriter) WriteChunkAsync

func (w *NoOpStreamingLogWriter) WriteChunkAsync(_ []byte)

WriteChunkAsync is a no-op implementation that does nothing.

Parameters:

  • chunk: The response chunk (ignored)

func (*NoOpStreamingLogWriter) WriteStatus

func (w *NoOpStreamingLogWriter) WriteStatus(_ int, _ map[string][]string) error

WriteStatus is a no-op implementation that does nothing and always returns nil.

Parameters:

  • status: The response status code (ignored)
  • headers: The response headers (ignored)

Returns:

  • error: Always returns nil

type RequestLogger

type RequestLogger interface {
	// LogRequest logs a complete non-streaming request/response cycle.
	//
	// Parameters:
	//   - url: The request URL
	//   - method: The HTTP method
	//   - requestHeaders: The request headers
	//   - body: The request body
	//   - statusCode: The response status code
	//   - responseHeaders: The response headers
	//   - response: The raw response data
	//   - websocketTimeline: Optional downstream websocket event timeline
	//   - apiRequest: The API request data
	//   - apiResponse: The API response data
	//   - apiWebsocketTimeline: Optional upstream websocket event timeline
	//   - requestID: Optional request ID for log file naming
	//   - requestTimestamp: When the request was received
	//   - apiResponseTimestamp: When the API response was received
	//
	// Returns:
	//   - error: An error if logging fails, nil otherwise
	LogRequest(url, method string, requestHeaders map[string][]string, body []byte, statusCode int, responseHeaders map[string][]string, response, websocketTimeline, apiRequest, apiResponse, apiWebsocketTimeline []byte, apiResponseErrors []*interfaces.ErrorMessage, requestID string, requestTimestamp, apiResponseTimestamp time.Time) error

	// LogStreamingRequest initiates logging for a streaming request and returns a writer for chunks.
	//
	// Parameters:
	//   - url: The request URL
	//   - method: The HTTP method
	//   - headers: The request headers
	//   - body: The request body
	//   - requestID: Optional request ID for log file naming
	//
	// Returns:
	//   - StreamingLogWriter: A writer for streaming response chunks
	//   - error: An error if logging initialization fails, nil otherwise
	LogStreamingRequest(url, method string, headers map[string][]string, body []byte, requestID string) (StreamingLogWriter, error)

	// IsEnabled returns whether request logging is currently enabled.
	//
	// Returns:
	//   - bool: True if logging is enabled, false otherwise
	IsEnabled() bool
}

RequestLogger defines the interface for logging HTTP requests and responses. It provides methods for logging both regular and streaming HTTP request/response cycles.

type StreamingLogWriter

type StreamingLogWriter interface {
	// WriteChunkAsync writes a response chunk asynchronously (non-blocking).
	//
	// Parameters:
	//   - chunk: The response chunk to write
	WriteChunkAsync(chunk []byte)

	// WriteStatus writes the response status and headers to the log.
	//
	// Parameters:
	//   - status: The response status code
	//   - headers: The response headers
	//
	// Returns:
	//   - error: An error if writing fails, nil otherwise
	WriteStatus(status int, headers map[string][]string) error

	// WriteAPIRequest writes the upstream API request details to the log.
	// This should be called before WriteStatus to maintain proper log ordering.
	//
	// Parameters:
	//   - apiRequest: The API request data (typically includes URL, headers, body sent upstream)
	//
	// Returns:
	//   - error: An error if writing fails, nil otherwise
	WriteAPIRequest(apiRequest []byte) error

	// WriteAPIResponse writes the upstream API response details to the log.
	// This should be called after the streaming response is complete.
	//
	// Parameters:
	//   - apiResponse: The API response data
	//
	// Returns:
	//   - error: An error if writing fails, nil otherwise
	WriteAPIResponse(apiResponse []byte) error

	// WriteAPIWebsocketTimeline writes the upstream websocket timeline to the log.
	// This should be called when upstream communication happened over websocket.
	//
	// Parameters:
	//   - apiWebsocketTimeline: The upstream websocket event timeline
	//
	// Returns:
	//   - error: An error if writing fails, nil otherwise
	WriteAPIWebsocketTimeline(apiWebsocketTimeline []byte) error

	// WriteAPIResponseErrors writes upstream API error entries to the log.
	WriteAPIResponseErrors(errors []*interfaces.ErrorMessage) error

	// SetFirstChunkTimestamp sets the TTFB timestamp captured when first chunk was received.
	//
	// Parameters:
	//   - timestamp: The time when first response chunk was received
	SetFirstChunkTimestamp(timestamp time.Time)

	// Close finalizes the log file and cleans up resources.
	//
	// Returns:
	//   - error: An error if closing fails, nil otherwise
	Close() error
}

StreamingLogWriter handles real-time logging of streaming response chunks. It provides methods for writing streaming response data asynchronously.

Jump to

Keyboard shortcuts

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