logging

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Aug 16, 2025 License: MIT Imports: 9 Imported by: 0

README

Logging Infrastructure

This package provides structured logging infrastructure for the GraphQL service using Go's standard log/slog package.

Features

  • Structured Logging: JSON and text format support
  • Request Tracing: Request ID and correlation ID support
  • Layer-Specific Loggers: Specialized loggers for each architecture layer
  • Configurable Levels: Debug, Info, Warn, Error levels
  • Context Propagation: Request context flows through all layers

Usage

Basic Logger Setup
import "github.com/captain-corgi/go-graphql-example/internal/infrastructure/logging"

// Create logger factory
factory := logging.NewLoggerFactory(config.LoggingConfig{
    Level:  "info",
    Format: "json",
})

// Get base logger
logger := factory.GetLogger()
logger.Info("Application started")
Layer-Specific Loggers
// Domain layer
domainLogger := factory.GetDomainLogger()
domainLogger.LogEntityCreated(ctx, "User", "user-123")

// Application layer
appLogger := factory.GetApplicationLogger()
appLogger.LogUseCaseStarted(ctx, "CreateUser", map[string]interface{}{
    "email": "user@example.com",
})

// Infrastructure layer
infraLogger := factory.GetInfrastructureLogger()
infraLogger.LogDatabaseQuery(ctx, "SELECT * FROM users", time.Millisecond*50)

// Interface layer
interfaceLogger := factory.GetInterfaceLogger()
interfaceLogger.LogHTTPRequest(ctx, "POST", "/query", 200, time.Millisecond*100)
Request Tracing
// Add request ID to context
ctx = logging.WithRequestID(ctx, "req-12345")

// Add correlation ID to context
ctx = logging.WithCorrelationID(ctx, "corr-67890")

// Logger will automatically include these IDs
logger.WithRequestID(ctx).Info("Processing request")
Custom Fields
// Add custom fields to logger
logger.WithFields(map[string]interface{}{
    "user_id": "123",
    "action":  "create_post",
}).Info("User action performed")

// Chain multiple context additions
logger.WithRequestID(ctx).
    WithCorrelationID("corr-123").
    WithComponent("user-service").
    Info("Service operation completed")

Configuration

The logging system is configured through the LoggingConfig struct:

logging:
  level: "info"    # debug, info, warn, error
  format: "json"   # json, text

Environment variables can override configuration:

  • GRAPHQL_SERVICE_LOGGING_LEVEL
  • GRAPHQL_SERVICE_LOGGING_FORMAT

Log Levels

  • Debug: Detailed information for debugging
  • Info: General information about application flow
  • Warn: Warning messages for potentially harmful situations
  • Error: Error messages for failures that don't stop the application

Best Practices

  1. Use Layer-Specific Loggers: Each layer has specialized logging methods
  2. Include Context: Always pass context for request tracing
  3. Log at Appropriate Levels: Use debug for detailed info, error for failures
  4. Include Relevant Fields: Add structured data to make logs searchable
  5. Don't Log Sensitive Data: Avoid logging passwords, tokens, or PII

Request Flow Example

[INFO] interface: HTTP request received method=POST path=/query request_id=req-abc123
[INFO] application: Use case started use_case=CreateUser request_id=req-abc123
[DEBUG] infrastructure: Database query executed query="INSERT INTO users..." request_id=req-abc123
[INFO] domain: Domain entity created entity_type=User entity_id=user-456 request_id=req-abc123
[INFO] application: Use case completed use_case=CreateUser duration_ms=45 request_id=req-abc123
[INFO] interface: HTTP request processed status_code=200 duration_ms=50 request_id=req-abc123

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GenerateCorrelationID

func GenerateCorrelationID() string

GenerateCorrelationID generates a new correlation ID

func GenerateRequestID

func GenerateRequestID() string

GenerateRequestID generates a new request ID

func GetCorrelationID

func GetCorrelationID(ctx context.Context) string

GetCorrelationID retrieves correlation ID from context

func GetRequestID

func GetRequestID(ctx context.Context) string

GetRequestID retrieves request ID from context

func WithCorrelationID

func WithCorrelationID(ctx context.Context, correlationID string) context.Context

WithCorrelationID adds correlation ID to context

func WithRequestID

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

WithRequestID adds request ID to context

Types

type ApplicationLogger

type ApplicationLogger struct {
	*Logger
}

ApplicationLogger provides logging utilities for the application layer

func NewApplicationLogger

func NewApplicationLogger(logger *Logger) *ApplicationLogger

NewApplicationLogger creates a logger for application layer

func (*ApplicationLogger) LogUseCaseCompleted

func (l *ApplicationLogger) LogUseCaseCompleted(ctx context.Context, useCase string, duration time.Duration)

LogUseCaseCompleted logs when a use case completes successfully

func (*ApplicationLogger) LogUseCaseFailed

func (l *ApplicationLogger) LogUseCaseFailed(ctx context.Context, useCase string, err error, duration time.Duration)

LogUseCaseFailed logs when a use case fails

func (*ApplicationLogger) LogUseCaseStarted

func (l *ApplicationLogger) LogUseCaseStarted(ctx context.Context, useCase string, params map[string]interface{})

LogUseCaseStarted logs when a use case starts

type DomainLogger

type DomainLogger struct {
	*Logger
}

DomainLogger provides logging utilities for the domain layer

func NewDomainLogger

func NewDomainLogger(logger *Logger) *DomainLogger

NewDomainLogger creates a logger for domain layer

func (*DomainLogger) LogEntityCreated

func (l *DomainLogger) LogEntityCreated(ctx context.Context, entityType, entityID string)

LogEntityCreated logs when a domain entity is created

func (*DomainLogger) LogEntityDeleted

func (l *DomainLogger) LogEntityDeleted(ctx context.Context, entityType, entityID string)

LogEntityDeleted logs when a domain entity is deleted

func (*DomainLogger) LogEntityUpdated

func (l *DomainLogger) LogEntityUpdated(ctx context.Context, entityType, entityID string)

LogEntityUpdated logs when a domain entity is updated

func (*DomainLogger) LogValidationError

func (l *DomainLogger) LogValidationError(ctx context.Context, entityType string, err error)

LogValidationError logs domain validation errors

type InfrastructureLogger

type InfrastructureLogger struct {
	*Logger
}

InfrastructureLogger provides logging utilities for the infrastructure layer

func NewInfrastructureLogger

func NewInfrastructureLogger(logger *Logger) *InfrastructureLogger

NewInfrastructureLogger creates a logger for infrastructure layer

func (*InfrastructureLogger) LogDatabaseError

func (l *InfrastructureLogger) LogDatabaseError(ctx context.Context, operation string, err error)

LogDatabaseError logs database errors

func (*InfrastructureLogger) LogDatabaseQuery

func (l *InfrastructureLogger) LogDatabaseQuery(ctx context.Context, query string, duration time.Duration)

LogDatabaseQuery logs database queries

func (*InfrastructureLogger) LogExternalServiceCall

func (l *InfrastructureLogger) LogExternalServiceCall(ctx context.Context, service, endpoint string, duration time.Duration)

LogExternalServiceCall logs external service calls

func (*InfrastructureLogger) LogExternalServiceError

func (l *InfrastructureLogger) LogExternalServiceError(ctx context.Context, service string, err error)

LogExternalServiceError logs external service errors

type InterfaceLogger

type InterfaceLogger struct {
	*Logger
}

InterfaceLogger provides logging utilities for the interface layer

func NewInterfaceLogger

func NewInterfaceLogger(logger *Logger) *InterfaceLogger

NewInterfaceLogger creates a logger for interface layer

func (*InterfaceLogger) LogGraphQLError

func (l *InterfaceLogger) LogGraphQLError(ctx context.Context, operationName string, err error)

LogGraphQLError logs GraphQL errors

func (*InterfaceLogger) LogGraphQLOperation

func (l *InterfaceLogger) LogGraphQLOperation(ctx context.Context, operationType, operationName string, duration time.Duration)

LogGraphQLOperation logs GraphQL operations

func (*InterfaceLogger) LogHTTPRequest

func (l *InterfaceLogger) LogHTTPRequest(ctx context.Context, method, path string, statusCode int, duration time.Duration)

LogHTTPRequest logs HTTP requests

type Logger

type Logger struct {
	*slog.Logger
}

Logger wraps slog.Logger with additional functionality

func NewLogger

func NewLogger(cfg config.LoggingConfig) *Logger

NewLogger creates a new structured logger based on configuration

func (*Logger) WithComponent

func (l *Logger) WithComponent(component string) *Logger

WithComponent adds component name to logger context

func (*Logger) WithCorrelationID

func (l *Logger) WithCorrelationID(correlationID string) *Logger

WithCorrelationID adds correlation ID to logger context

func (*Logger) WithError

func (l *Logger) WithError(err error) *Logger

WithError adds error to logger context

func (*Logger) WithFields

func (l *Logger) WithFields(fields map[string]interface{}) *Logger

WithFields adds multiple fields to logger context

func (*Logger) WithRequestID

func (l *Logger) WithRequestID(ctx context.Context) *Logger

WithRequestID adds request ID to logger context

type LoggerFactory

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

LoggerFactory manages logger creation and configuration

func NewLoggerFactory

func NewLoggerFactory(cfg config.LoggingConfig) *LoggerFactory

NewLoggerFactory creates a new logger factory

func (*LoggerFactory) GetApplicationLogger

func (f *LoggerFactory) GetApplicationLogger() *ApplicationLogger

GetApplicationLogger returns a logger configured for application layer

func (*LoggerFactory) GetConfig

func (f *LoggerFactory) GetConfig() config.LoggingConfig

GetConfig returns the current logging configuration

func (*LoggerFactory) GetDomainLogger

func (f *LoggerFactory) GetDomainLogger() *DomainLogger

GetDomainLogger returns a logger configured for domain layer

func (*LoggerFactory) GetInfrastructureLogger

func (f *LoggerFactory) GetInfrastructureLogger() *InfrastructureLogger

GetInfrastructureLogger returns a logger configured for infrastructure layer

func (*LoggerFactory) GetInterfaceLogger

func (f *LoggerFactory) GetInterfaceLogger() *InterfaceLogger

GetInterfaceLogger returns a logger configured for interface layer

func (*LoggerFactory) GetLogger

func (f *LoggerFactory) GetLogger() *Logger

GetLogger returns the base logger

func (*LoggerFactory) UpdateConfig

func (f *LoggerFactory) UpdateConfig(cfg config.LoggingConfig)

UpdateConfig updates the logging configuration and recreates the logger

Jump to

Keyboard shortcuts

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