### Basic Logging Examples (Go) Source: https://github.com/willibrandon/mtlog/blob/main/docs/template-syntax.md Illustrates basic logging using both traditional and Go template syntaxes for a simple string message in Go. ```go // Traditional logger.Information("Hello {Name}!", "World") // Go template logger.Information("Hello {{.Name}}!", "World") ``` -------------------------------- ### Basic HTTP Middleware Setup in Go Source: https://github.com/willibrandon/mtlog/blob/main/docs/quick-reference.html Provides basic examples of integrating mtlog's HTTP middleware with various Go web frameworks including net/http, Gin, Echo, Fiber, and Chi. ```go import ( "github.com/willibrandon/mtlog" "github.com/willibrandon/mtlog/adapters/middleware" ) logger := mtlog.New(mtlog.WithConsole()) // net/http mw := middleware.Middleware(middleware.DefaultOptions(logger)) handler := mw(yourHandler) // Gin router.Use(middleware.Gin(logger)) // Echo e.Use(middleware.Echo(logger)) // Fiber app.Use(middleware.Fiber(logger)) // Chi r.Use(middleware.Chi(logger)) ``` -------------------------------- ### Go: Pre-built Routes for Common Patterns Source: https://github.com/willibrandon/mtlog/blob/main/docs/sinks.md Provides examples of using pre-built route constructors for common logging scenarios like errors, audits, and metrics. These shortcuts simplify the setup of standard routing configurations. ```go // Common route patterns errorRoute := sinks.ErrorRoute("errors", errorSink) auditRoute := sinks.AuditRoute("audit", auditSink) metricRoute := sinks.MetricRoute("metrics", metricsSink) ``` -------------------------------- ### Run with Full Observability Stack Source: https://github.com/willibrandon/mtlog/blob/main/adapters/otel/examples/README.md Executes a script to start the OpenTelemetry Collector and Jaeger for comprehensive observability. This is the recommended setup for viewing traces and collector metrics. ```bash #!/bin/bash docker-compose up -d echo "OpenTelemetry Collector and Jaeger are running." echo "View traces in Jaeger UI: http://localhost:16686" echo "View collector metrics: http://localhost:8888/metrics" echo "View collector zpages: http://localhost:55679/debug/tracez" ``` -------------------------------- ### Logging with Properties Examples (Go) Source: https://github.com/willibrandon/mtlog/blob/main/docs/template-syntax.md Demonstrates logging messages with multiple properties using traditional, Go template, and mixed syntaxes in Go. This shows how to pass and reference variables within log messages. ```go // Traditional logger.Information("User {UserId} performed {Action} on {Resource}", userId, action, resource) // Go template logger.Information("User {{.UserId}} performed {{.Action}} on {{.Resource}}", userId, action, resource) // Mixed logger.Information("User {UserId} ({{.Username}}) performed {Action}", userId, username, action) ``` -------------------------------- ### Initialize and Use mtlog Logger Source: https://github.com/willibrandon/mtlog/blob/main/docs/blog/introducing-mtlog.html Demonstrates how to install the mtlog library using go get, create a new logger instance with console output, and log messages with structured data. ```go go get github.com/willibrandon/mtlog log := mtlog.New(mtlog.WithConsole()) log.Info("App started") log.Info("User {UserId} purchased {@Order}", 42, order) ``` -------------------------------- ### Setup Local Sentry Integration Test Source: https://github.com/willibrandon/mtlog/blob/main/adapters/sentry/examples/README.md This script sets up a local Sentry instance for integration testing. It handles the download, configuration, and initialization of Sentry containers using Docker Compose. Ensure Docker and Go are installed. ```bash # 1. Download and configure Sentry (one-time setup) ./adapters/sentry/scripts/setup-integration-test.sh # 2. Navigate to docker directory cd docker # 3. Start and initialize Sentry ../adapters/sentry/scripts/initialize-sentry-pipeline.sh # 4. Verify everything is working ../adapters/sentry/scripts/verify-sentry-pipeline.sh ``` -------------------------------- ### Example: API Endpoint Sampling using SampleGroup() in Go Source: https://github.com/willibrandon/mtlog/blob/main/docs/sampling-guide.md Demonstrates a practical example of sampling decisions on a per-API endpoint basis using `logger.SampleGroup(r.URL.Path, 100)`. It also shows how to ensure errors are always logged regardless of sampling. ```go package main import ( "log" "net/http" "github.com/willibrandon/mtlog" "github.com/willibrandon/mtlog/core" ) // Placeholder for base logger and request processing var baseLogger = mtlog.New(mtlog.WithConsole()) func processRequest(r *http.Request) error { // Simulate request processing that might return an error return nil } func handleRequest(w http.ResponseWriter, r *http.Request) { // Sample per endpoint logger := baseLogger.SampleGroup(r.URL.Path, 100) // Log request (sampled) logger.Info("Request {Method} {Path}", r.Method, r.URL.Path) // Always log errors if err := processRequest(r); err != nil { baseLogger.Error("Request failed: {Error}", err) } } func main() { http.HandleFunc("/", handleRequest) http.ListenAndServe(":8080", nil) } ``` -------------------------------- ### Install and Run mtlog-analyzer (Bash) Source: https://github.com/willibrandon/mtlog/blob/main/docs/troubleshooting.md Provides instructions for installing the mtlog-analyzer tool, which performs static analysis on mtlog usage to catch common programming errors at compile time. The guide shows how to integrate it into a Go project using `go vet`. ```bash # Install the analyzer go install github.com/willibrandon/mtlog/cmd/mtlog-analyzer@latest # Run before deployment go vet -vettool=$(which mtlog-analyzer) ./... ``` -------------------------------- ### Go: Multi-Strategy Sampling Configuration Source: https://github.com/willibrandon/mtlog/blob/main/docs/sampling-guide.md This Go example shows how to configure mtlog with multiple sampling strategies. It includes rate-based sampling, duration-based rate limiting, and conditional sampling based on business hours. This allows for fine-grained control over log volume. ```go logger := mtlog.New( mtlog.WithConsole(), mtlog.Sampling(). Rate(0.1). // 10% of messages Duration(100*time.Millisecond). // Rate limit to 10/sec When(func() bool { // Only during business hours h := time.Now().Hour() return h >= 9 && h <= 17 }, 1). Build(), ) ``` -------------------------------- ### Install mtlog logr Adapter Source: https://github.com/willibrandon/mtlog/blob/main/adapters/logr/README.md Install the mtlog logr adapter using go get. This command fetches the necessary package for integrating mtlog with the logr API. ```bash go get github.com/willibrandon/mtlog/adapters/logr ``` -------------------------------- ### Discovering Available Sampling Profiles with GetAvailableProfileDescriptions() in Go Source: https://github.com/willibrandon/mtlog/blob/main/docs/sampling-guide.md Illustrates how to retrieve a map of all available sampling profiles and their descriptions at runtime using `mtlog.GetAvailableProfileDescriptions()`. The example output shows various profile names and their intended use cases. ```go package main import ( "fmt" "github.com/willibrandon/mtlog" ) func main() { // Get all available profiles with descriptions profiles := mtlog.GetAvailableProfileDescriptions() for name, description := range profiles { fmt.Printf("%s: %s\n", name, description) } // Output: // HighTrafficAPI: Aggressive sampling for high-volume APIs (1% rate with rate limiting) // BackgroundWorker: Moderate sampling for background jobs (10% rate) // DebugVerbose: Minimal sampling for debug environments (first 100 + 50% rate) // ProductionErrors: Conservative error sampling with backoff // HealthChecks: Aggressive health check filtering (first 10 + 0.1% rate) // CriticalAlerts: No sampling for critical alerts } ``` -------------------------------- ### Log Message Examples (Go) Source: https://github.com/willibrandon/mtlog/blob/main/docs/quick-reference.html Illustrates various methods for logging messages at different levels using traditional, generic type-safe, and short method syntaxes. Includes examples with parameters and template rendering. ```Go // Traditional Methods logger.Verbose("Verbose message") logger.Debug("Debug: {Value}", value) logger.Information("Info: {User} {Action}", user, action) logger.Warning("Warning: {Count} items", count) logger.Error("Error: {Error}", err) logger.Fatal("Fatal: {Reason}", reason) // Generic Methods (Type-Safe) logger.VerboseT("Verbose message") logger.DebugT("Debug: {Value}", value) logger.InformationT("Info: {User} {Action}", user, action) logger.WarningT("Warning: {Count} items", count) logger.ErrorT("Error: {Error}", err) logger.FatalT("Fatal: {Reason}", reason) // Short Methods logger.V("Verbose") logger.D("Debug: {Value}", value) logger.I("Info: {Message}", msg) logger.W("Warning: {Issue}", issue) logger.E("Error: {Error}", err) logger.F("Fatal: {Reason}", reason) ``` -------------------------------- ### Ensure Early Context Logging for Percentage Thresholds in Go Source: https://github.com/willibrandon/mtlog/blob/main/docs/context-guide.md Highlights the importance of logging context early in its lifecycle for accurate percentage-based deadline calculations. This code snippet shows both a 'good' example where logging occurs immediately after context creation and a 'bad' example where logging is delayed, potentially skewing percentage calculations. ```go import ( "context" "time" "github.com/willibrandon/mtlog" ) // Good - log immediately after creating context ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) logger.InfoContext(ctx, "Starting operation") // Prime the cache // Bad - first log near deadline ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) time.Sleep(4*time.Second) logger.InfoContext(ctx, "Almost done") // Too late for percentage calculation ``` -------------------------------- ### Complex Example with Structs and Formatting (Go) Source: https://github.com/willibrandon/mtlog/blob/main/docs/template-syntax.md Presents a complex logging scenario in Go involving a struct, traditional syntax with formatting specifiers, and Go template syntax. This showcases logging complex data types and applying various formatters. ```go type Order struct { ID int Total float64 Items int Status string } order := Order{ID: 123, Total: 99.95, Items: 3, Status: "pending"} // Traditional with formatting logger.Information("Order {OrderId:000}: ${Total:F2} for {Items} items - {@Order}", order.ID, order.Total, order.Items, order) // Go template logger.Information("Order {{.OrderId}}: ${{.Total}} for {{.Items}} items - {{@.Order}}", order.ID, order.Total, order.Items, order) ``` -------------------------------- ### mtlog Health Check Handler Setup in Go Source: https://github.com/willibrandon/mtlog/blob/main/docs/quick-reference.md Provides examples of setting up comprehensive health check endpoints using mtlog middleware in Go. This includes creating a main health check handler with version and environment details, adding custom checks, and implementing simple liveness and readiness probes. ```go // Basic health check handler healthHandler := middleware.NewHealthCheckHandler(logger). WithVersion("1.0.0"). WithEnvironment("production"). WithMetrics(true) // Add custom checks healthHandler.AddCheck("database", func() middleware.Check { if err := db.Ping(); err != nil { return middleware.Check{ Status: "unhealthy", Error: err.Error(), } } return middleware.Check{Status: "healthy"} }) // Use as HTTP handler http.Handle("/health", healthHandler) // Simple liveness/readiness handlers http.HandleFunc("/liveness", middleware.LivenessHandler()) http.HandleFunc("/readiness", middleware.ReadinessHandler( middleware.DatabaseHealthChecker("postgres", db.Ping), middleware.HTTPHealthChecker("api", "http://api:8080/health", 5*time.Second), )) ``` -------------------------------- ### JSON Configuration Example Source: https://github.com/willibrandon/mtlog/blob/main/docs/quick-reference.md An example of a logging configuration file in JSON format, specifying minimum log level, sinks (output destinations), and enrichers. ```json { "minimumLevel": "Information", "sinks": [ {"type": "Console", "theme": "dark"}, {"type": "Seq", "serverUrl": "http://localhost:5341"} ], "enrichers": ["Timestamp", "MachineName"] } ``` -------------------------------- ### Install mtlog-analyzer using go install Source: https://github.com/willibrandon/mtlog/blob/main/cmd/mtlog-analyzer/README.md Installs the mtlog-analyzer tool using the go install command. Ensure your Go binary directory is in your PATH after installation. ```bash go install github.com/willibrandon/mtlog/cmd/mtlog-analyzer@latest # Add to your shell profile (.bashrc, .zshrc, etc.) export PATH="$PATH:$(go env GOPATH)/bin" # On Windows (PowerShell) $env:PATH += ";$(go env GOPATH)\bin" ``` -------------------------------- ### Install mtlog.nvim with packer.nvim Source: https://github.com/willibrandon/mtlog/blob/main/neovim-plugin/README.md Configures the mtlog.nvim plugin using the packer.nvim package manager. It specifies the runtime path to use and sets the plugin to load only for Go files. Includes a configuration callback for setup. ```lua use { 'willibrandon/mtlog', rtp = 'neovim-plugin', ft = { 'go' }, config = function() require('mtlog').setup({ -- your configuration }) end, } ``` -------------------------------- ### Configure Elasticsearch Sink in Go Source: https://github.com/willibrandon/mtlog/blob/main/docs/quick-reference.html Provides examples for configuring the Elasticsearch sink in mtlog. Covers basic setup with a single node, and advanced configuration with multiple nodes, custom index patterns, API keys, and batch size settings. ```go mtlog.WithElasticsearch("http://localhost:9200", "logs") mtlog.WithElasticsearchAdvanced( []string{"http://node1:9200", "http://node2:9200"}, sinks.WithElasticsearchIndex("logs-%{+yyyy.MM.dd}"), sinks.WithElasticsearchAPIKey("your-api-key"), sinks.WithElasticsearchBatchSize(100), ) ``` -------------------------------- ### Optimize Logging Performance with Simple Templates in Go Source: https://github.com/willibrandon/mtlog/blob/main/docs/troubleshooting.md This Go example contrasts a slow logging approach using complex templates with a fast approach using simple, static log messages. Using simpler templates for high-frequency logs can significantly improve performance. ```go // Slow: Complex template with multiple properties log.Debug("Processing request {RequestId} for user {UserId} at {Timestamp}") // Fast: Simple template log.Debug("Processing request") ``` -------------------------------- ### Go Testing Command-Line Interface Source: https://github.com/willibrandon/mtlog/blob/main/docs/testing.md Provides a collection of common Go command-line instructions for running tests, benchmarks, and managing test coverage. These commands facilitate various testing scenarios, including running all tests, enabling coverage, filtering tests by tags or names, and integrating with Docker Compose for environment setup. Ensure `go` is installed and accessible in your PATH. ```bash # Run all tests go test ./... # Run with coverage go test -cover ./... # Run only integration tests go test -tags=integration ./... # Run benchmarks go test -bench=. -benchmem ./... # Run with race detector go test -race ./... # Run specific test go test -run TestSeqIntegration ./... # Run tests with docker-compose docker-compose -f docker/docker-compose.test.yml up -d go test -tags=integration ./... docker-compose -f docker/docker-compose.test.yml down ``` -------------------------------- ### Setup and Run Go Project Tests and Benchmarks Source: https://github.com/willibrandon/mtlog/blob/main/CONTRIBUTING.md This snippet demonstrates how to set up a Go project by cloning the repository and running tests and benchmarks. It utilizes standard Go tooling and `golangci-lint` for code quality. ```bash git clone https://github.com/willibrandon/mtlog.git cd mtlog go test ./... go test -bench=. -benchmem ./... golangci-lint run ``` -------------------------------- ### Basic Mtlog Logger Setup (Go) Source: https://github.com/willibrandon/mtlog/blob/main/docs/quick-reference.md Demonstrates how to initialize a new Mtlog logger with different configurations. This includes a simple console logger and a production-ready logger with console output, Seq integration, and a specified minimum logging level. ```go import ( "github.com/willibrandon/mtlog" "github.com/willibrandon/mtlog/core" ) // Simple logger logger := mtlog.New(mtlog.WithConsole()) // Production logger logger := mtlog.New( mtlog.WithConsoleTheme("dark"), mtlog.WithSeq("http://localhost:5341", "api-key"), mtlog.WithMinimumLevel(core.InformationLevel), ) ``` -------------------------------- ### Install mtlog (Go) Source: https://github.com/willibrandon/mtlog/blob/main/docs/otel-integration.md Installs the mtlog library using go get. This is the basic installation without OpenTelemetry dependencies. ```bash go get github.com/willibrandon/mtlog ``` -------------------------------- ### Setup Logging in Go Application Lifecycle Source: https://github.com/willibrandon/mtlog/blob/main/docs/dynamic-levels.md This Go function `setupLogging` demonstrates how to initialize logging within an application's lifecycle. It sets up a logger with a level switch, console output, and Seq integration. It returns the logger, level switch, and a cleanup function to properly close resources. ```go func setupLogging() (*mtlog.Logger, *mtlog.LoggingLevelSwitch, func()) { levelSwitch := mtlog.NewLoggingLevelSwitch(core.InformationLevel) logger := mtlog.New( mtlog.WithLevelSwitch(levelSwitch), mtlog.WithConsole(), mtlog.WithSeq("http://seq:5341"), ) // Setup Seq level controller controller := mtlog.NewSeqLevelController(levelSwitch, seqSink, options) // Return cleanup function return logger, levelSwitch, func() { controller.Close() logger.Close() } } ``` -------------------------------- ### Install Sentry Adapter for mtlog Source: https://github.com/willibrandon/mtlog/blob/main/adapters/sentry/README.md Install the Sentry adapter for mtlog using the go get command. This command fetches and installs the necessary package for integrating Sentry with your mtlog application. ```bash go get github.com/willibrandon/mtlog/adapters/sentry ``` -------------------------------- ### Basic mtlog Middleware Setup for Go Web Frameworks Source: https://github.com/willibrandon/mtlog/blob/main/docs/quick-reference.md Demonstrates how to initialize the mtlog logger and apply its middleware to common Go web frameworks like net/http, Gin, Echo, Fiber, and Chi. This setup is crucial for enabling request logging and associated features. ```go import ( "github.com/willibrandon/mtlog" "github.com/willibrandon/mtlog/adapters/middleware" ) logger := mtlog.New(mtlog.WithConsole()) // net/http mw := middleware.Middleware(middleware.DefaultOptions(logger)) handler := mw(yourHandler) // Gin router.Use(middleware.Gin(logger)) // Echo e.Use(middleware.Echo(logger)) // Fiber app.Use(middleware.Fiber(logger)) // Chi r.Use(middleware.Chi(logger)) ``` -------------------------------- ### Set Sentry DSN and Run Basic Example Source: https://github.com/willibrandon/mtlog/blob/main/adapters/sentry/examples/README.md This example demonstrates how to set the Sentry Data Source Name (DSN) as an environment variable and then run a basic Go application that logs errors to Sentry. Ensure you have obtained the DSN from the Sentry setup script. ```bash # Set the DSN from Step 1 export SENTRY_DSN="http://[your-key]@localhost:9000/1" # Run an example cd adapters/sentry/examples/basic go run main.go ``` -------------------------------- ### Run Integration Tests with Manual Container Management (Bash) Source: https://github.com/willibrandon/mtlog/blob/main/docs/testing.md This snippet shows how to run integration tests by manually managing Docker containers for different logging and data services like Seq, Elasticsearch, and Splunk. Each example starts a container, runs the Go integration tests (tagged with `integration`), and then stops and removes the container. Ensure Docker is installed and the specified image tags are accessible. ```bash # Run integration tests with Seq docker run -d --name seq-test -e ACCEPT_EULA=Y -e SEQ_FIRSTRUN_NOAUTHENTICATION=true -p 8080:80 -p 5342:5341 datalust/seq go test -tags=integration ./... docker stop seq-test && docker rm seq-test # Run integration tests with Elasticsearch docker run -d --name es-test -e "discovery.type=single-node" -e "xpack.security.enabled=false" -p 9200:9200 docker.elastic.co/elasticsearch/elasticsearch:8.11.1 # Wait for Elasticsearch to be ready sleep 30 go test -tags=integration ./... docker stop es-test && docker rm es-test # Run integration tests with Splunk # Note: Port 8089 is required for Splunk management API used by tests # A non-default password is required to enable remote login docker run -d --name splunk-test -p 8000:8000 -p 8088:8088 -p 8089:8089 -e SPLUNK_START_ARGS="--accept-license" -e SPLUNK_PASSWORD="Admin123!" -e SPLUNK_HEC_TOKEN="eb6baeef-eeb3-4a35-ab73-e17a12523b10" splunk/splunk:latest # Wait for Splunk to be ready sleep 60 go test -tags=integration ./... docker stop splunk-test && docker rm splunk-test ``` -------------------------------- ### Install and Run mtlog-analyzer Source: https://github.com/willibrandon/mtlog/blob/main/docs/quick-reference.md Instructions for installing the mtlog-analyzer static analysis tool and running it with `go vet`. This tool helps catch common logging mistakes at compile time, improving code quality and preventing runtime errors. ```bash # Install go install github.com/willibrandon/mtlog/cmd/mtlog-analyzer@latest # Run with go vet go vet -vettool=$(which mtlog-analyzer) ./... ``` -------------------------------- ### Quick Start: Create logr Logger with mtlog Backend Source: https://github.com/willibrandon/mtlog/blob/main/adapters/logr/README.md Demonstrates how to create a logr-compatible logger that uses mtlog as its backend. This involves importing the necessary packages and initializing the logger with basic mtlog options like console output and a minimum log level. ```go import ( "github.com/willibrandon/mtlog" mtlogr "github.com/willibrandon/mtlog/adapters/logr" "github.com/willibrandon/mtlog/core" ) // Create a logr logger backed by mtlog logger := mtlogr.NewLogger( mtlog.WithConsole(), mtlog.WithMinimumLevel(core.DebugLevel), ) // Use standard logr API logger.Info("starting reconciliation", "namespace", "default", "name", "my-app") logger.V(1).Info("detailed info", "replicas", 3) logger.Error(err, "failed to update resource", "reason", "conflict") ``` -------------------------------- ### Configuring MTLog Filters Source: https://github.com/willibrandon/mtlog/blob/main/docs/configuration.md Illustrates how to apply filters to MTLog to control which log events are processed. This example sets a filter to only log events with a minimum level of 'Warning'. ```json { "Mtlog": { "Filter": [ { "Name": "ByLevel", "Args": { "minimumLevel": "Warning" } } ] } } ``` -------------------------------- ### Configuration Loading from JSON (Go) Source: https://github.com/willibrandon/mtlog/blob/main/docs/quick-reference.md Shows how to load logger configuration from a JSON file using the configuration.LoadFromFile function and then create a logger instance based on that configuration. ```go config, err := configuration.LoadFromFile("logging.json") logger := config.CreateLogger() ``` -------------------------------- ### Quick Start: Basic Go Logging with mtlog Source: https://github.com/willibrandon/mtlog/blob/main/README.md Demonstrates the basic usage of mtlog in Go. It shows how to create a logger with console output, log simple messages, and log messages with properties using template syntax. ```go package main import ( "github.com/willibrandon/mtlog" "github.com/willibrandon/mtlog/core" ) func main() { // Create a logger with console output log := mtlog.New( mtlog.WithConsole(), mtlog.WithMinimumLevel(core.InformationLevel), ) // Simple logging log.Info("Application started") // Message templates with properties userId := 123 log.Info("User {UserId} logged in", userId) // Capturing complex types order := Order{ID: 456, Total: 99.95} log.Info("Processing {@Order}", order) } // For libraries that need error handling: func NewLibraryLogger() (*mtlog.Logger, error) { return mtlog.Build( mtlog.WithConsoleTemplate("[${Timestamp:HH:mm:ss} ${Level:u3}] ${Message}"), mtlog.WithMinimumLevel(core.DebugLevel), ) } ``` -------------------------------- ### Run Simple Collector for Console Output Source: https://github.com/willibrandon/mtlog/blob/main/adapters/otel/examples/README.md Starts a minimal OpenTelemetry collector that outputs logs directly to the console. This is useful for debugging or when a full observability stack is not required. ```bash # Terminal 1: Start collector ./run-collector-simple.sh # Terminal 2: Run example go run -tags=otel main.go ``` -------------------------------- ### Context-Aware Logging in Go Source: https://github.com/willibrandon/mtlog/blob/main/docs/context-guide.md Demonstrates how to use context-aware logging methods provided by mtlog. These methods accept a `context.Context` and allow for contextual information to be passed with log entries. Standard and context-aware logging calls are shown, covering various log levels. ```go import "context" import "github.com/willibrandon/mtlog" // Assume logger is initialized and ctx is available var logger mtlog.Logger var ctx context.Context var err error // Standard methods logger.Info("User logged in") // Context-aware methods logger.InfoContext(ctx, "User logged in") logger.ErrorContext(ctx, "Operation failed: {Error}", err) ``` -------------------------------- ### Health Check Handler Setup in Go Source: https://github.com/willibrandon/mtlog/blob/main/docs/quick-reference.html Demonstrates setting up and configuring the `NewHealthCheckHandler` for monitoring application health. It includes adding version, environment, metrics, and custom health checks. ```go // Basic health handler healthHandler := middleware.NewHealthCheckHandler(logger). WithVersion("1.0.0"). WithEnvironment("production"). WithMetrics(true) // Add custom checks healthHandler.AddCheck("database", func() middleware.Check { if err := db.Ping(); err != nil { return middleware.Check{Status: "unhealthy", Error: err.Error()} } return middleware.Check{Status: "healthy"} }) http.Handle("/health", healthHandler) // Simple handlers http.HandleFunc("/liveness", middleware.LivenessHandler()) http.HandleFunc("/readiness", middleware.ReadinessHandler( middleware.DatabaseHealthChecker("postgres", db.Ping), )) ``` -------------------------------- ### Using Pre-configured Sampling Profiles in Go Source: https://github.com/willibrandon/mtlog/blob/main/docs/sampling-guide.md Applies pre-defined sampling configurations optimized for different use cases like development, production, or high-volume traffic. These profiles simplify setup for common scenarios. ```go // Development profile - verbose logging logger.SampleProfile("Development").Info("Dev message") // Production profile - balanced for production use logger.SampleProfile("Production").Info("Prod message") // HighVolume profile - aggressive sampling for very high traffic logger.SampleProfile("HighVolume").Info("High volume message") ``` -------------------------------- ### Basic mtlog Logging in Go Source: https://github.com/willibrandon/mtlog/blob/main/CLAUDE.md Demonstrates the basic setup and usage of the mtlog library for console and Seq logging. It shows how to create a logger instance and log messages with structured data. ```go log := mtlog.New( mtlog.WithConsole(), mtlog.WithSeq("http://localhost:5341"), ) log.Information("User {UserId} logged in", 123) log.Warning("Disk usage at {Percentage:P1}", 0.85) ``` -------------------------------- ### Configuring MTLog Minimum Logging Level Source: https://github.com/willibrandon/mtlog/blob/main/docs/configuration.md Provides an example of how to set the minimum logging level for MTLog using JSON configuration. This ensures that only log events at or above the specified level (e.g., 'Debug') are processed. ```json { "Mtlog": { "MinimumLevel": "Debug" } } ``` -------------------------------- ### Fluent Builder for Sampling Configuration in Go Source: https://github.com/willibrandon/mtlog/blob/main/docs/sampling-guide.md Demonstrates the fluent builder pattern for creating complex sampling configurations. Multiple sampling strategies like rate, duration, and first-N events can be chained together. The `Build()` method finalizes the configuration. ```go logger := mtlog.New( mtlog.WithConsole(), mtlog.Sampling(). Rate(0.5). // 50% sampling Duration(100*time.Millisecond). // At most 10/second First(1000). // Only first 1000 Build(), ) ``` -------------------------------- ### Install mtlog.nvim with vim-plug Source: https://github.com/willibrandon/mtlog/blob/main/neovim-plugin/README.md Configures the mtlog.nvim plugin using the vim-plug package manager. It specifies the runtime path and the file types for which the plugin should be used. A Lua call to setup the plugin is included. ```vim Plug 'willibrandon/mtlog', { 'rtp': 'neovim-plugin', 'for': 'go' } ``` ```lua lua require('mtlog').setup() ``` -------------------------------- ### mtlog OTEL Integration: Basic Trace Enrichment Example Source: https://github.com/willibrandon/mtlog/blob/main/adapters/otel/README.md Provides a complete Go example demonstrating basic trace enrichment with mtlog and OpenTelemetry. It shows how to set up a tracer, create a span, and then initialize a logger that automatically includes the active span's trace and span IDs in log messages. ```go import ( "context" "github.com/willibrandon/mtlog" otelmtlog "github.com/willibrandon/mtlog/adapters/otel" "go.opentelemetry.io/otel" ) // Setup tracer tracer := otel.Tracer("my-service") // Create span ctx, span := tracer.Start(context.Background(), "operation") defer span.End() // Create logger with OTEL trace enrichment logger := mtlog.New( otelmtlog.WithOTELEnricher(ctx), // Auto-adds trace.id, span.id mtlog.WithConsole(), ) logger.Information("Processing request") // Output includes: {trace.id="..." span.id="..."} ``` -------------------------------- ### Run Benchmarks and Analyze CPU Profiles in Go Source: https://github.com/willibrandon/mtlog/blob/main/docs/troubleshooting.md This bash command demonstrates how to run Go benchmarks, collect CPU profiling data, and then analyze the profile using the go tool pprof. This is a key step in identifying performance bottlenecks. ```bash cd benchmarks go test -bench=. -benchmem -cpuprofile=cpu.prof go tool pprof cpu.prof ``` -------------------------------- ### Traditional Syntax Formatting - Numbers (Go) Source: https://github.com/willibrandon/mtlog/blob/main/docs/template-syntax.md Provides examples of using format specifiers with the traditional syntax for numbers in Go, including zero-padding, decimal places for currency (F2), and percentage formatting (P0, P1). ```go // Zero-padding logger.Information("Order {Id:000}", 42) // "042" // Decimal places logger.Information("Price: ${Price:F2}", 99.9) // "$99.90" // Percentage logger.Information("CPU: {Usage:P0}", 0.65) // "65%" logger.Information("Memory: {Usage:P1}", 0.855) // "85.5%" ``` -------------------------------- ### Log Info Message with Structured Data Source: https://github.com/willibrandon/mtlog/blob/main/docs/blog/introducing-mtlog.html Shows an example of logging an informational message with placeholders for user ID and IP address, demonstrating mtlog's structured logging capabilities. ```go log.Info("User {UserId} logged in from {IP}", 123, "192.168.1.5") ``` -------------------------------- ### Initialize mtlog Plugin with Options (Lua) Source: https://github.com/willibrandon/mtlog/blob/main/neovim-plugin/README.md Initializes the mtlog plugin with optional configuration settings. This is the primary setup function and should be called early in the Neovim configuration. ```lua local mtlog = require('mtlog') -- Setup with configuration mtlog.setup(opts) ``` -------------------------------- ### Prometheus Metrics Export using PrometheusMetrics() in Go Source: https://github.com/willibrandon/mtlog/blob/main/docs/sampling-guide.md Explains how to convert mtlog metrics into a format compatible with Prometheus using the `PrometheusMetrics()` method. It lists available metric names and provides an example of exposing these metrics via an HTTP endpoint. ```go package main import ( "fmt" "net/http" "github.com/willibrandon/mtlog/core" ) // Assume getSamplingMetrics() is defined elsewhere to collect metrics func getSamplingMetrics() core.SamplingMetrics { // Placeholder for actual metric collection return core.SamplingMetrics{ TotalSampled: 1000, TotalSkipped: 9000, // ... other metrics } } func main() { // Convert to Prometheus-compatible metrics metrics := getSamplingMetrics() promMetrics := metrics.PrometheusMetrics() // Available metrics: // - mtlog_sampling_total_sampled // - mtlog_sampling_total_skipped // - mtlog_sampling_rate // - mtlog_sampling_group_cache_hits // - mtlog_sampling_group_cache_misses // - mtlog_sampling_group_cache_size // - mtlog_sampling_group_cache_evictions // - mtlog_sampling_group_cache_hit_rate // - mtlog_sampling_backoff_cache_hits // - mtlog_sampling_backoff_cache_misses // - mtlog_sampling_backoff_cache_size // - mtlog_sampling_backoff_cache_evictions // - mtlog_sampling_backoff_cache_hit_rate // - mtlog_sampling_adaptive_cache_hits // - mtlog_sampling_adaptive_cache_misses // - mtlog_sampling_adaptive_cache_size // - mtlog_sampling_adaptive_cache_hit_rate // Example: Expose via HTTP endpoint http.HandleFunc("/metrics", func(w http.ResponseWriter, r *http.Request) { metrics := getSamplingMetrics() // Your metrics collection for name, value := range metrics.PrometheusMetrics() { fmt.Fprintf(w, "%s %f\n", name, value) } }) http.ListenAndServe(":8080", nil) // Example server start } ``` -------------------------------- ### Filter Logs Early for Performance in Go Source: https://github.com/willibrandon/mtlog/blob/main/docs/troubleshooting.md This Go example demonstrates how to configure mtlog with filters to reduce the amount of data processed by expensive sinks. By filtering logs based on level or custom predicates early in the pipeline, performance can be improved. ```go // Filter before expensive operations log := mtlog.New( mtlog.WithFilter(filters.ByLevelThreshold(core.InformationLevel)), mtlog.WithFilter(filters.ByPredicate(func(e *core.LogEvent) bool { // Skip health check logs return !strings.Contains(e.MessageTemplate, "health") })), mtlog.WithSink(expensiveSink), ) ``` -------------------------------- ### Using Groups for Multi-Tenant Sampling in Go Source: https://github.com/willibrandon/mtlog/blob/main/docs/sampling-guide.md Shows how to apply sampling per tenant in multi-tenant systems using `SampleGroup`. This ensures fair sampling rates for each individual tenant, preventing one tenant's high log volume from impacting others. The tenant ID is used as the group key. ```go // Each tenant gets fair sampling logger.SampleGroup(tenantID, 100).Info("Tenant {TenantID} event", tenantID) ``` -------------------------------- ### Example Usage with Context Timeout in Go Source: https://github.com/willibrandon/mtlog/blob/main/docs/quick-reference.html Demonstrates how to use context with timeout for logging operations in Go. It shows logging messages at different stages of a process and highlights when a deadline is approaching. ```go ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) defer cancel() logger.InfoContext(ctx, "Starting operation") time.Sleep(350 * time.Millisecond) logger.InfoContext(ctx, "Still processing...") // WARNING: Deadline approaching! ``` -------------------------------- ### Standard Go Log Example (Before mtlog) Source: https://github.com/willibrandon/mtlog/blob/main/docs/blog/introducing-mtlog.html A typical log statement using the standard Go log package before adopting mtlog, demonstrating the manual inclusion of key-value pairs. ```go log.Info("user logged in", "user_id", 123, "ip", "192.168.1.5") ``` -------------------------------- ### Example CI Integration for mtlog-analyzer (YAML) Source: https://github.com/willibrandon/mtlog/blob/main/docs/troubleshooting.md Illustrates how to incorporate the mtlog-analyzer into a GitHub Actions CI workflow. This ensures that static analysis checks are automatically performed on every commit or pull request, preventing common mtlog-related bugs from reaching production. ```yaml # .github/workflows/ci.yml - name: Run mtlog-analyzer run: | go install github.com/willibrandon/mtlog/cmd/mtlog-analyzer@latest go vet -vettool=$(which mtlog-analyzer) ./... ``` -------------------------------- ### Configure Console Log Templates in Go Source: https://github.com/willibrandon/mtlog/blob/main/docs/quick-reference.html Demonstrates how to configure different console log templates using mtlog. WithConsoleTemplate allows customization of log output format, including levels, timestamps, source context, messages, and exceptions. Different predefined formats are shown, from simple to full details. ```go mtlog.WithConsoleTemplate("[${Level:u3}] ${Message}") mtlog.WithConsoleTemplate("[${Timestamp:HH:mm:ss} ${Level:u3}] ${Message}") mtlog.WithConsoleTemplate("[${Timestamp:yyyy-MM-dd HH:mm:ss} ${Level:u3}] {SourceContext}: ${Message}${NewLine}${Exception}") ``` -------------------------------- ### Sentry Performance Monitoring with Transactions and Spans Source: https://github.com/willibrandon/mtlog/blob/main/docs/sinks.md Demonstrates how to integrate Sentry's performance monitoring features within mtlog. This involves starting and finishing transactions for broader operations and adding spans to track specific sub-operations for detailed performance analysis. ```go import "github.com/willibrandon/mtlog/adapters/sentry" // Start a transaction ctx := sentry.StartTransaction(context.Background(), "ProcessOrder", "order.process") defer func() { if tx := sentry.GetTransaction(ctx); tx != nil { tx.Finish() } }() // Add spans for operations span := sentry.StartSpan(ctx, "db.query", "SELECT * FROM orders") // ... perform database query span.Finish() // Log within transaction context log.Information("Order processed successfully") ``` -------------------------------- ### Configure Sentry Sink in Go Source: https://github.com/willibrandon/mtlog/blob/main/docs/quick-reference.html Explains how to integrate the Sentry sink with mtlog for error tracking and performance monitoring. Examples cover basic setup, sampling for high-volume applications, and advanced configuration including environment, release, sampling rates, and retry policies. ```go import "github.com/willibrandon/mtlog/adapters/sentry" sink, _ := sentry.WithSentry("https://key@sentry.io/project") log := mtlog.New(mtlog.WithSink(sink)) sink, _ := sentry.WithSentry("https://key@sentry.io/project", sentry.WithFixedSampling(0.1), // 10% sampling ) sink, _ := sentry.WithSentry("https://key@sentry.io/project", sentry.WithEnvironment("production"), sentry.WithRelease("v1.2.3"), sentry.WithTracesSampleRate(0.2), sentry.WithProfilesSampleRate(0.1), sentry.WithAdaptiveSampling(0.01, 0.5), // 1% to 50% adaptive sentry.WithRetryPolicy(3, time.Second), sentry.WithStackTraceCache(1000), ) ``` -------------------------------- ### Propagate Context and Properties with mtlog in Go Source: https://github.com/willibrandon/mtlog/blob/main/docs/troubleshooting.md This Go example illustrates how to propagate context and custom properties through the logging system. It creates a background context, adds a 'RequestId' property to it, and then creates a logger associated with that context, ensuring all subsequent logs include the property. ```go // Ensure context flows through middleware ctx := context.Background() ctx = mtlog.PushProperty(ctx, "RequestId", requestId) logger := baseLogger.WithContext(ctx) // All logs will include RequestId ``` -------------------------------- ### Configure Capturer Depth and Size Limits in Go Source: https://github.com/willibrandon/mtlog/blob/main/docs/troubleshooting.md This Go code example illustrates how to configure the capturer to limit the depth of captured data, the maximum string length, and the number of items in collections. This can help mitigate performance issues related to slow capturing. ```go // Limit capturing depth capturer := capture.NewCapturer( 2, // Max depth (default: 3) 100, // Max string length 50, // Max collection items ) ``` -------------------------------- ### Setup Prometheus Metrics Export in Go Source: https://github.com/willibrandon/mtlog/blob/main/docs/routing-patterns.md Configures and starts a metrics server to export router statistics to Prometheus. It registers multiple routers and exposes metrics on port 9090. Assumes the 'sinks' package provides necessary router and exporter implementations. ```go func SetupMetricsExport() { // Create routers mainRouter := sinks.NewRouterSink(sinks.FirstMatch, routes...) auditRouter := sinks.NewRouterSink(sinks.AllMatch, auditRoutes...) // Create metrics exporter exporter := sinks.NewRouterMetricsExporter() exporter.RegisterRouter("main", mainRouter) exporter.RegisterRouter("audit", auditRouter) // Start metrics server go func() { if err := sinks.StartMetricsServer(":9090", exporter); err != nil { log.Printf("Failed to start metrics server: %v", err) } }() } ``` -------------------------------- ### Go: Control and Monitor Object Pooling Source: https://github.com/willibrandon/mtlog/blob/main/docs/quick-reference.md Demonstrates how to manage object pooling in Go. This includes enabling pooling globally, retrieving statistics on pool hits, resetting these statistics, and setting up a batch metrics recorder for efficient data flushing. ```go package main import ( "fmt" "time" "github.com/willibrandon/mtlog/middleware" ) func main() { // Pooling is enabled by default, can be controlled globally middleware.EnablePooling = true // Get pool statistics stats := middleware.GetPoolStats() fmt.Printf("Error pool hits: %d\n", stats.ErrorPoolHits) // Reset statistics middleware.ResetPoolStats() // Batch metrics for high-throughput batchRecorder := middleware.NewBatchMetricsRecorder( func(metrics []middleware.RequestMetric) { // Flush to your metrics backend fmt.Printf("Flushing %d metrics\n", len(metrics)) }, 5*time.Second, // Flush interval 1000, // Batch size ) defer batchRecorder.Close() // Assuming 'options' is a struct holding configuration // options.MetricsRecorder = batchRecorder } // Dummy types for compilation, replace with actual types from mtlog // type RequestMetric struct {} // type Options struct { MetricsRecorder interface{} } ``` -------------------------------- ### Enable CPU Profiling for Performance Analysis in Go Source: https://github.com/willibrandon/mtlog/blob/main/docs/troubleshooting.md This Go snippet demonstrates how to enable HTTP-based CPU profiling using the net/http/pprof package. It starts a local HTTP server that exposes profiling data, which can then be analyzed using the go tool pprof command. ```go import _ "net/http/pprof" go http.ListenAndServe("localhost:6060", nil) // go tool pprof http://localhost:6060/debug/pprof/profile ``` -------------------------------- ### Analyzing CPU Profiles in Go Source: https://github.com/willibrandon/mtlog/blob/main/docs/PERFORMANCE.md Illustrates the process of generating and analyzing CPU profiles for Go applications. This helps in pinpointing performance bottlenecks and optimizing CPU-intensive operations. ```bash go test -bench=BenchmarkSimpleLog -cpuprofile=cpu.prof go tool pprof cpu.prof ``` -------------------------------- ### Dynamic Log Level Control in Go Source: https://github.com/willibrandon/mtlog/blob/main/docs/quick-reference.html Illustrates how to dynamically control logging levels at runtime using mtlog. It covers manual initialization, changing levels, using a fluent interface, and checking if a level is enabled. ```go // Manual control levelSwitch := mtlog.NewLoggingLevelSwitch(core.InformationLevel) logger := mtlog.New( mtlog.WithLevelSwitch(levelSwitch), mtlog.WithConsole(), ) // Change at runtime levelSwitch.SetLevel(core.DebugLevel) // Fluent interface levelSwitch.Debug().Information().Warning() // Check if enabled if levelSwitch.IsEnabled(core.VerboseLevel) { // Expensive operation } ```