logging

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: May 15, 2025 License: Apache-2.0 Imports: 9 Imported by: 0

README

Logging Package

This package provides a structured logging implementation for the MCP Server SDK, built on top of Uber's zap library.

Features

  • Multiple log levels (Debug, Info, Warn, Error, Fatal, Panic)
  • Structured logging with fields
  • Context-aware logging
  • Printf-style logging
  • High performance JSON logging
  • Configurable output paths

Usage

Basic Logging
package main

import (
    "github.com/FreePeak/cortex/internal/infrastructure/logging"
)

func main() {
    // Create a development logger (with debug level enabled)
    logger, err := logging.NewDevelopment()
    if err != nil {
        panic(err)
    }
    defer logger.Sync() // Flushes buffer, if any

    // Simple logging
    logger.Debug("Debug message")
    logger.Info("Info message")
    logger.Warn("Warning message")
    logger.Error("Error message")
    // logger.Fatal("Fatal message") // This would exit the program
    // logger.Panic("Panic message") // This would panic
}
Structured Logging with Fields
logger.Info("User logged in", logging.Fields{
    "user_id": 123,
    "email":   "user@example.com",
})

// Create a logger with default fields
userLogger := logger.With(logging.Fields{
    "user_id": 123,
    "email":   "user@example.com",
})

userLogger.Info("User profile updated")
userLogger.Error("Failed to update password")
Context-Aware Logging
ctx := context.Background()
logger.InfoContext(ctx, "Starting operation")
logger.ErrorContext(ctx, "Operation failed", logging.Fields{
    "error": "connection timeout",
})
Formatted Logging
logger.Infof("User %d logged in from %s", 123, "192.168.1.1")
logger.Errorf("Failed to process payment: %v", fmt.Errorf("insufficient funds"))
Custom Configuration
// Create a custom logger configuration
config := logging.Config{
    Level:       logging.DebugLevel,
    Development: true,
    OutputPaths: []string{"stdout", "logs/app.log"},
    InitialFields: logging.Fields{
        "app": "example-app",
        "env": "testing",
    },
}

// Create a logger with custom config
logger, err := logging.New(config)
if err != nil {
    panic(err)
}
defer logger.Sync()

logger.Info("Application started")
Default Logger

The package provides a default logger that can be used throughout your application:

// Get the default logger (production level)
logger := logging.Default()
logger.Info("Using default logger")

// You can also replace the default logger
customLogger, _ := logging.NewDevelopment()
logging.SetDefault(customLogger)

Available Log Levels

  • DebugLevel: Debug information, most verbose
  • InfoLevel: General operational information
  • WarnLevel: Warning conditions, not critical but should be checked
  • ErrorLevel: Error conditions, likely requiring attention
  • FatalLevel: Fatal conditions, will call os.Exit(1)
  • PanicLevel: Panic conditions, will call panic()

Documentation

Overview

This file provides examples for integrating the logging package with the MCP server application.

Package logging provides a wrapper around zap for structured logging

Example
package main

import (
	"context"
	"fmt"

	"github.com/FreePeak/cortex/internal/infrastructure/logging"
)

func main() {
	// Create a development logger (with debug level enabled)
	logger, err := logging.NewDevelopment()
	if err != nil {
		panic(err)
	}
	defer func() {
		_ = logger.Sync() // Intentionally ignoring sync errors in examples
	}()

	// Simple logging
	logger.Debug("Debug message")
	logger.Info("Info message")
	logger.Warn("Warning message")
	logger.Error("Error message")
	// logger.Fatal("Fatal message") // This would exit the program
	// logger.Panic("Panic message") // This would panic

	// Logging with fields
	logger.Info("User logged in", logging.Fields{
		"user_id": 123,
		"email":   "user@example.com",
	})

	// Using With to create a logger with default fields
	userLogger := logger.With(logging.Fields{
		"user_id": 123,
		"email":   "user@example.com",
	})

	userLogger.Info("User profile updated")
	userLogger.Error("Failed to update password")

	// Formatted logging (using sugar)
	logger.Infof("User %d logged in from %s", 123, "192.168.1.1")
	logger.Errorf("Failed to process payment: %v", fmt.Errorf("insufficient funds"))

	// Context-aware logging
	ctx := context.Background()
	logger.InfoContext(ctx, "Starting operation")
	logger.ErrorContext(ctx, "Operation failed", logging.Fields{
		"error": "connection timeout",
	})

	// Using the default logger (production level)
	defaultLogger := logging.Default()
	defaultLogger.Info("Using default logger")
}
Example (CustomConfig)
package main

import (
	"github.com/FreePeak/cortex/internal/infrastructure/logging"
)

func main() {
	// Create a custom logger configuration
	config := logging.Config{
		Level:       logging.DebugLevel,
		Development: true,
		OutputPaths: []string{"stdout", "logs/app.log"},
		InitialFields: logging.Fields{
			"app": "example-app",
			"env": "testing",
		},
	}

	// Create a logger with custom config
	logger, err := logging.New(config)
	if err != nil {
		panic(err)
	}
	defer func() {
		_ = logger.Sync() // Intentionally ignoring sync errors in examples
	}()

	logger.Info("Application started")
}
Example (ProductionLogger)
package main

import (
	"github.com/FreePeak/cortex/internal/infrastructure/logging"
)

func main() {
	// Create a production logger
	logger, err := logging.NewProduction()
	if err != nil {
		panic(err)
	}
	defer func() {
		_ = logger.Sync() // Intentionally ignoring sync errors in examples
	}()

	// Production loggers typically use JSON format
	// and have DEBUG level disabled
	logger.Debug("This won't be logged in production") // Not shown
	logger.Info("System is running")
	logger.Error("Failed to connect to database", logging.Fields{
		"error":     "connection refused",
		"database":  "postgres",
		"reconnect": true,
	})
}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func LogJSONRPCRequest

func LogJSONRPCRequest(ctx context.Context, request domain.JSONRPCRequest)

LogJSONRPCRequest logs JSON-RPC request details

func LogJSONRPCResponse

func LogJSONRPCResponse(ctx context.Context, response domain.JSONRPCResponse)

LogJSONRPCResponse logs JSON-RPC response details

func Middleware

func Middleware(logger *Logger) func(http.Handler) http.Handler

Middleware creates an HTTP middleware that adds a logger to the request context.

func ServerStartupLogger

func ServerStartupLogger(logger *Logger, serverName, version, address string)

ServerStartupLogger logs server startup information

func SetDefault

func SetDefault(logger *Logger)

SetDefault sets the default logger

Types

type Config

type Config struct {
	Level         LogLevel
	Development   bool
	OutputPaths   []string
	InitialFields Fields
	LogToFile     bool
	LogDir        string
}

Config represents the logging configuration

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns a default configuration for the logger

func DevelopmentConfig

func DevelopmentConfig() Config

DevelopmentConfig returns a development configuration for the logger

func ProductionConfig

func ProductionConfig() Config

ProductionConfig returns a production configuration for the logger

type Fields

type Fields map[string]interface{}

Fields is a type alias for key-value pairs

type LogLevel

type LogLevel string

LogLevel represents the log severity level

const (
	DebugLevel LogLevel = "debug"
	InfoLevel  LogLevel = "info"
	WarnLevel  LogLevel = "warn"
	ErrorLevel LogLevel = "error"
	FatalLevel LogLevel = "fatal"
	PanicLevel LogLevel = "panic"
)

Available log levels

type Logger

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

Logger is a wrapper around zap.Logger providing a simplified API

func Default

func Default() *Logger

Default returns the default logger

func GetLogger

func GetLogger(ctx context.Context) *Logger

GetLogger retrieves the logger from the context. If no logger is found, returns a default logger.

func New

func New(config Config) (*Logger, error)

New creates a new logger with the given configuration

func NewDevelopment

func NewDevelopment() (*Logger, error)

NewDevelopment creates a new development logger

func NewProduction

func NewProduction() (*Logger, error)

NewProduction creates a new production logger

func WithRequestID

func WithRequestID(logger *Logger, requestID string) *Logger

WithRequestID returns a new logger with the request ID field

func (*Logger) Debug

func (l *Logger) Debug(msg string, fields ...Fields)

Debug logs a message at debug level with optional fields

func (*Logger) DebugContext

func (l *Logger) DebugContext(ctx context.Context, msg string, fields ...Fields)

DebugContext logs a message at debug level with context and optional fields

func (*Logger) Debugf

func (l *Logger) Debugf(format string, args ...interface{})

Debugf logs a formatted message at debug level

func (*Logger) Error

func (l *Logger) Error(msg string, fields ...Fields)

Error logs a message at error level with optional fields

func (*Logger) ErrorContext

func (l *Logger) ErrorContext(ctx context.Context, msg string, fields ...Fields)

ErrorContext logs a message at error level with context and optional fields

func (*Logger) Errorf

func (l *Logger) Errorf(format string, args ...interface{})

Errorf logs a formatted message at error level

func (*Logger) Fatal

func (l *Logger) Fatal(msg string, fields ...Fields)

Fatal logs a message at fatal level with optional fields and then calls os.Exit(1)

func (*Logger) FatalContext

func (l *Logger) FatalContext(ctx context.Context, msg string, fields ...Fields)

FatalContext logs a message at fatal level with context and optional fields and then calls os.Exit(1)

func (*Logger) Fatalf

func (l *Logger) Fatalf(format string, args ...interface{})

Fatalf logs a formatted message at fatal level and then calls os.Exit(1)

func (*Logger) Info

func (l *Logger) Info(msg string, fields ...Fields)

Info logs a message at info level with optional fields

func (*Logger) InfoContext

func (l *Logger) InfoContext(ctx context.Context, msg string, fields ...Fields)

InfoContext logs a message at info level with context and optional fields

func (*Logger) Infof

func (l *Logger) Infof(format string, args ...interface{})

Infof logs a formatted message at info level

func (*Logger) Panic

func (l *Logger) Panic(msg string, fields ...Fields)

Panic logs a message at panic level with optional fields and then panics

func (*Logger) PanicContext

func (l *Logger) PanicContext(ctx context.Context, msg string, fields ...Fields)

PanicContext logs a message at panic level with context and optional fields and then panics

func (*Logger) Panicf

func (l *Logger) Panicf(format string, args ...interface{})

Panicf logs a formatted message at panic level and then panics

func (*Logger) Sync

func (l *Logger) Sync() error

Sync flushes any buffered log entries

func (*Logger) Warn

func (l *Logger) Warn(msg string, fields ...Fields)

Warn logs a message at warn level with optional fields

func (*Logger) WarnContext

func (l *Logger) WarnContext(ctx context.Context, msg string, fields ...Fields)

WarnContext logs a message at warn level with context and optional fields

func (*Logger) Warnf

func (l *Logger) Warnf(format string, args ...interface{})

Warnf logs a formatted message at warn level

func (*Logger) With

func (l *Logger) With(fields Fields) *Logger

With returns a logger with the given fields

Jump to

Keyboard shortcuts

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