### Global Installation Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/api-reference/rspec-helpers.md Installs all helpers into RSpec configuration and validates the appender setup. ```APIDOC ## Helpers.install! ### Description Installs all helpers into RSpec configuration and validates the appender setup. ### Method `Helpers.install!` ### Returns nil ### Installation Steps 1. **Configures RSpec** (via `configure_rspec!`): - Includes `LoggingHelpers` in all specs - Adds `before(:suite)` appender validation - Adds `around` hook for LOG env var support 2. **Patches TestProf** (if present): - Prepends `LoggingHelpers` onto `TestProf::Rails::LoggingHelpers` - Ensures compatibility with TestProf's own logging helpers ### Example ```ruby # Call once in spec_helper.rb RailsSemanticLogging::RSpec::Helpers.install! ``` ``` -------------------------------- ### Development Setup and Testing Source: https://github.com/fabn/rails_semantic_logging/blob/main/README.md Instructions for setting up the development environment, cloning the repository, installing dependencies, and running tests and code style checks. ```bash git clone https://github.com/fabn/rails_semantic_logging.git cd rails_semantic_logging bundle install bundle exec rspec bundle exec rubocop ``` -------------------------------- ### Run Specific Example by Line Number Source: https://github.com/fabn/rails_semantic_logging/blob/main/CLAUDE.md Execute a specific test example within a file using its line number. ```bash bundle exec rspec spec/path:42 ``` -------------------------------- ### Install Dependencies with Bundler Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/api-reference/module-entry-point.md Run this command after updating your Gemfile to install the gem and its dependencies. ```bash bundle install ``` -------------------------------- ### Configuration Precedence Example Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/configuration.md Demonstrates configuration precedence where environment variables override YAML files, which in turn override programmatic configuration. The example shows how an ENV var setting for production formatter takes precedence. ```ruby RailsSemanticLogging.configure do |config| config.production_formatter = :json end # YAML File: # production: # production_formatter: datadog # ENV var: # RAILS_SEMANTIC_LOGGING_PRODUCTION_FORMATTER=json # Result: ENV var wins → JSON formatter used ``` -------------------------------- ### Install RSpec Helpers Globally Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/api-reference/rspec-helpers.md Call this method once in your `spec_helper.rb` to install all semantic logging RSpec helpers and validate your appender setup. ```ruby # Call once in spec_helper.rb RailsSemanticLogging::RSpec::Helpers.install! ``` -------------------------------- ### RSpec Setup for Rails Semantic Logging Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/api-reference/rspec-helpers.md Install and configure RSpec helpers and matchers for Rails Semantic Logging. Ensure SemanticLogger is configured and RSpec is set up with the provided helpers. ```ruby # Gemfile gem 'rails_semantic_logging' gem 'rspec-rails' # spec/rails_helper.rb require 'rails_semantic_logging/rspec/helpers' require 'rails_semantic_logging/rspec/matchers' RailsSemanticLogging::RSpec::Helpers.install! RSpec.configure do |config| config.include RailsSemanticLogging::RSpec::Matchers end ``` -------------------------------- ### Install RailsSemanticLogging RSpec Helpers Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/api-reference/rspec-helpers.md Include all RSpec helpers by calling `RailsSemanticLogging::RSpec::Helpers.install!` in your spec_helper or rails_helper file. This setup enables LOG environment variable support and patches TestProf if present. ```ruby # spec/spec_helper.rb or spec/rails_helper.rb require 'rails_semantic_semantic_logging/rspec/helpers' RailsSemanticLogging::RSpec::Helpers.install! ``` -------------------------------- ### Configure with Multiple Settings Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/api-reference/module-entry-point.md Example demonstrating various configuration options including application name, environment, formatters, and custom log tags. Useful for setting up the gem in different environments. ```ruby RailsSemanticLogging.configure do |config| config.application_name = 'BikeRental' config.environment_name = ENV.fetch('NAMESPACE', Rails.env) if Rails.env.production? config.production_formatter = :datadog else config.development_formatter = :color end config.default_payload = true config.quiet_assets = true config.sync_in_test = true config.custom_log_tags = { tenant_id: ->(request) { request.headers['X-Tenant-ID'] }, user_id: ->(request) { current_user(request)&.id } } end ``` -------------------------------- ### ActiveJob Queue Adapter Configuration Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/api-reference/datadog-log-injection.md Configure your ActiveJob queue adapter in `config/application.rb`. This example uses Sidekiq. ```ruby # config/application.rb config.active_job.queue_adapter = :sidekiq ``` -------------------------------- ### Setup RSpec Matchers and Helpers Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/00-START-HERE.md Include RSpec matchers and helpers for testing log output in your specs. Ensure these are required in your `rails_helper.rb`. ```ruby # spec/rails_helper.rb require 'rails_semantic_logging/rspec/matchers' require 'rails_semantic_logging/rspec/helpers' RSpec.configure do |config| config.include RailsSemanticLogging::RSpec::Matchers RailsSemanticLogging::RSpec::Helpers.install! end ``` -------------------------------- ### Install Logging Helpers Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/api-reference/rspec-helpers.md Prepends `LoggingHelpers` to `TestProf::Rails::LoggingHelpers` to ensure consistent behavior and method availability for TestProf users. ```ruby TestProf::Rails::LoggingHelpers.prepend(LoggingHelpers) ``` -------------------------------- ### LOG Environment Variable Support Example Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/api-reference/rspec-helpers.md Examples demonstrating how to use the LOG environment variable to control logging output during RSpec runs, including showing all logs or only ActiveRecord logs. ```bash # Show all logs during test run LOG=all bundle exec rspec spec/path.rb ``` ```bash # Show only ActiveRecord logs LOG=ar bundle exec rspec spec/path.rb ``` ```bash # Control log level (default: trace) LOG_LEVEL=debug bundle exec rspec spec/path.rb ``` -------------------------------- ### Example Job Class with Logging Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/api-reference/job-logging-patches.md Demonstrates how the ActiveJob patch automatically intercepts logger calls within a job. No explicit setup is required in the job code itself. ```ruby class MyJob < ActiveJob::Base def perform(arg) # tag_logger is automatically intercepted by the patch logger.info("Processing") end end ``` -------------------------------- ### Rails Semantic Logging Configuration Example Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/api-reference/module-entry-point.md Configure semantic logging before the Railtie initializes the logger. This example shows how to set application name, environment, default payload, formatters, and custom log tags. ```ruby ```ruby # config/application.rb require_relative 'boot' require 'rails/all' require 'rails_semantic_logging' # Explicit require (optional; Bundler auto-requires) Bundler.require(*Rails.groups) module BikeRental class Application < Rails::Application config.load_defaults 7.1 # Configure semantic logging BEFORE the Railtie initializes the logger RailsSemanticLogging.configure do |config| config.application_name = 'BikeRental' config.environment_name = ENV.fetch('NAMESPACE', Rails.env) config.default_payload = true config.quiet_assets = true config.sync_in_test = true config.production_formatter = :datadog config.development_formatter = :color config.custom_log_tags = { tenant_id: ->(request) { request.headers['X-Tenant-ID'] }, user_id: ->(request) { current_user(request)&.id }, region: ->(request) { request.headers['X-Region'] || 'us-east-1' } } end end end ``` ``` -------------------------------- ### JSON Formatter Example Source: https://github.com/fabn/rails_semantic_logging/blob/main/README.md Plain structured JSON output without Datadog-specific field mapping. Useful for non-Datadog log pipelines. ```json { "timestamp": "2025-10-26T10:30:45.123Z", "level": "info", "host": "server-1", "name": "Rails", "message": "Processing request", "duration_ms": 42.5 } ``` -------------------------------- ### Run Entire Suite with Rails Framework Logs Only Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/api-reference/rspec-helpers.md Example command to execute the entire RSpec suite, filtering logs to only show Rails framework logs by setting LOG to 'all'. ```bash # Run entire suite with Rails framework logs only LOG=all bundle exec rspec ``` -------------------------------- ### ActionController Payload Enrichment Example Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/api-reference/action-controller-default-payload.md This example shows the structure of the payload enrichment performed by the `append_info_to_payload` method. It details the fields added and their sources within the request object. ```ruby # Called automatically by Rails ActionController instrumentation # No need to call directly — just include the concern # The payload receives: # payload[:full_path] = "/api/v1/bikes?limit=10" # payload[:host] = "api.example.com" # payload[:user_agent] = "Mozilla/5.0 (iPhone; iOS 17)" # payload[:referer] = "https://app.example.com/dashboard" ``` -------------------------------- ### Original Rails Log Example Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/api-reference/action-controller-default-payload.md This JSON represents a standard Rails log entry before enrichment with DefaultPayload. ```json { "timestamp": "2025-10-26T10:30:45.123Z", "level": "info", "message": "Completed 200 OK in 42ms", "status": 200, "method": "GET", "path": "/api/v1/bikes" } ``` -------------------------------- ### Configure RailsSemanticLogging with Block Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/api-reference/module-entry-point.md Use block-style setup for idiomatic configuration. This method yields the Configuration instance for modification. Must be called before the logger is initialized. ```ruby # In config/application.rb RailsSemanticLogging.configure do |config| config.application_name = 'MyApp' config.environment_name = ENV.fetch('NAMESPACE', Rails.env) config.production_formatter = :datadog config.custom_log_tags = { user_id: ->(request) { extract_user(request)&.id } } end ``` -------------------------------- ### Install Rails Semantic Logging Gem Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/00-START-HERE.md Add the gem to your Gemfile to include it in your project. ```ruby # Gemfile gem 'rails_semantic_logging' ``` -------------------------------- ### Install Rails Semantic Logging Gem Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/README.md Add the gem to your Gemfile and configure the application name in your application's configuration file. ```ruby # Gemfile gem 'rails_semantic_logging' # config/application.rb RailsSemanticLogging.configure do |config| config.application_name = 'MyApp' end ``` -------------------------------- ### Show Database Queries at Debug Level Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/api-reference/rspec-helpers.md Example command to run a specific spec file while showing only ActiveRecord logs at the debug level by setting LOG_LEVEL and LOG. ```bash # Show database queries at debug level LOG_LEVEL=debug LOG=ar bundle exec rspec spec/models/bike_spec.rb ``` -------------------------------- ### Sidekiq Patch Installation in Railtie Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/api-reference/job-logging-patches.md Shows how the RailsSemanticLogging Sidekiq patch is automatically applied by prepending it to Sidekiq::JobLogger when Sidekiq is loaded. No manual setup is required. ```ruby # lib/rails_semantic_logging/railtie.rb:62-67 if defined?(::Sidekiq::JobLogger) require 'sidekiq/job_logger' require 'rails_semantic_logging/job_logging/sidekiq_patch' ::Sidekiq::JobLogger.prepend(RailsSemanticLogging::JobLogging::SidekiqPatch) end ``` -------------------------------- ### Request Log Example (Production with Datadog Formatter) Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/README.md This JSON log entry represents a typical production request log. It includes details about the HTTP request, response status, duration, and client information, formatted for easy parsing by log aggregation tools. ```json { "timestamp": "2025-10-26T10:30:45.123Z", "status": "info", "host": "web-01", "logger.name": "Rails", "message": "GET /api/v1/bikes JSON 200 42.5ms", "duration": 42500000, "duration_human": "42.5ms", "http": { "status_code": 200, "method": "GET", "url": "/api/v1/bikes?limit=10", "request_id": "abc-123-def-456", "url_details": { "path": "/api/v1/bikes", "queryString": { "limit": "10" }, "host": "api.example.com" }, "useragent": "Mozilla/5.0 (iPhone; iOS 17)", "referer": "https://app.example.com/dashboard" }, "network": { "client": { "ip": "203.0.113.42" } } } ``` -------------------------------- ### Debug Single Spec with All Logs Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/api-reference/rspec-helpers.md Example command to debug a specific spec file and line number, showing all logs at the trace level by setting LOG to 'all'. ```bash # Debug a single spec with all logs at trace level LOG=all bundle exec rspec spec/models/bike_spec.rb:42 ``` -------------------------------- ### Install RSpec Helpers for Appender Validation Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/configuration.md Install RSpec helpers to validate appender configuration at trace level. This will raise an error if the appender configuration is incorrect. ```ruby RailsSemanticLogging::RSpec::Helpers.install! # Raises if appender config is wrong ``` -------------------------------- ### Test Railtie with Specific Rails Version Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/api-reference/railtie.md Install dependencies and run the RSpec suite, specifying a particular Rails version for testing. ```bash RAILS_VERSION=7.1 bundle install && bundle exec rspec ``` -------------------------------- ### Log Output With Sidekiq Patch Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/api-reference/job-logging-patches.md Example of log output after the Sidekiq patch is applied, demonstrating that job class, job ID, and queue are correctly included in the 'named_tags' field. ```json { "timestamp": "2025-10-26T10:31:00.456Z", "status": "info", "message": "Performing ImportBikesJob from Sidekiq(default)", "named_tags": { "job_class": "ImportBikesJob", "job_id": "ead18b6be7cef9b3b8e9", "queue": "default" } } ``` -------------------------------- ### RailsSemanticLogging.configure Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/api-reference/configuration.md Yields the global configuration object, allowing for block-style setup of configuration parameters. This is a convenient way to set multiple configuration options at once. ```APIDOC ## `RailsSemanticLogging.configure { |config| ... }` Yields the global configuration for block-style setup. ```ruby RailsSemanticLogging.configure do |config| config.application_name = 'MyApp' config.production_formatter = :json config.custom_log_tags = { user_id: ->(request) { request.env['warden'].user&.id } } end ``` ``` -------------------------------- ### Background Job Log Example Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/README.md This JSON log entry details a background job being performed. It includes information about the job class, ID, queue, and execution count, useful for monitoring job processing. ```json { "timestamp": "2025-10-26T10:31:00.456Z", "status": "info", "host": "worker-01", "logger.name": "Rails", "message": "Performing ImportBikesJob from Sidekiq(default)", "named_tags": { "job_class": "ImportBikesJob", "job_id": "abc-123-def-456", "queue": "default", "executions": 0, "provider_job_id": "9632" } } ``` -------------------------------- ### Log Output Before Sidekiq Patch Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/api-reference/job-logging-patches.md Example of log output before the Sidekiq patch is applied, showing that job-specific named tags are lost and appear as an empty object. ```json { "timestamp": "2025-10-26T10:31:00.456Z", "status": "info", "message": "Performing ImportBikesJob", "named_tags": {} } ``` -------------------------------- ### Get Formatter for Environment Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/api-reference/configuration.md Determine the appropriate formatter for a given Rails environment. Defaults to Datadog for production and color for development, but can be customized. ```ruby config = RailsSemanticLogging.config config.formatter_for('production') # => RailsSemanticLogging::Formatters::Datadog instance (default) config.formatter_for('development') # => :color (default) ``` -------------------------------- ### Datadog Production Request Log Example Source: https://github.com/fabn/rails_semantic_logging/blob/main/README.md This JSON represents a complete request log for a production environment, including HTTP details and Datadog trace correlation. Ensure the :datadog formatter is enabled for this mapping. ```json { "timestamp": "2025-10-26T10:30:45.123Z", "status": "info", "host": "web-01", "logger.name": "Rails", "message": "Completed 200 OK in 42ms", "duration": 42500000, "http.status_code": 200, "http.method": "GET", "http.url": "/api/v1/bikes", "http.url_details.host": "api.example.com", "http.useragent": "Mozilla/5.0 (iPhone; iOS 17.0)", "http.referer": "https://app.example.com/dashboard", "dd.trace_id": "1234567890", "dd.span_id": "9876543210" } ``` -------------------------------- ### RSpec Configuration for Semantic Logging Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/README.md Includes the necessary RSpec matchers and helpers for Rails Semantic Logging. This setup is optional and should be included in your RSpec configuration. ```ruby require 'rails_semantic_logging/rspec/matchers' require 'rails_semantic_logging/rspec/helpers' RSpec.configure do |config| config.include RailsSemanticLogging::RSpec::Matchers RailsSemanticLogging::RSpec::Helpers.install! end ``` -------------------------------- ### Testing Log Output with `log_semantic` Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/api-reference/rspec-matchers.md These examples showcase various scenarios for using the `log_semantic` matcher, including testing for specific log levels, message content (using regex), payload data, and named tags associated with jobs. ```ruby # Test that a service logs an info message service = MyService.new expect { service.perform }.to log_semantic(level: :info, message: "Completed") # Test payload contents expect { service.import_items(3) } .to log_semantic(level: :info, payload: { items_imported: 3 }) # Test job tags ActiveJob.perform_later(MyJob) expect { MyJob.perform_now(42) } .to log_semantic(named_tags: { job_class: 'MyJob', executions: 0 }) # Regex matching expect { logger.warn("deprecation warning") } .to log_semantic(level: :warn, message: /deprecation/) ``` -------------------------------- ### Example Structured Job Log Output Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/api-reference/job-logging-patches.md This JSON object demonstrates the expected structured log output after applying the ActiveJob patch. It includes named tags for job details, improving filterability in log analysis tools. ```json { "timestamp": "2025-10-26T10:31:00.456Z", "status": "info", "message": "Performing ImportBikesJob from Sidekiq(default)", "named_tags": { "job_class": "ImportBikesJob", "job_id": "abc-123-def-456", "queue": "default", "executions": 0, "provider_job_id": "9632" } } ``` -------------------------------- ### Error Log with Exception Details Example Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/README.md This JSON log entry captures an error event, including the error type, message, and a stack trace. This is crucial for debugging application failures. ```json { "timestamp": "2025-10-26T10:32:15.789Z", "status": "error", "host": "web-01", "logger.name": "BikeService", "message": "Failed to import bike", "error": { "kind": "ActiveRecord::RecordInvalid", "message": "Validation failed: VIN is not unique", "stack": "app/services/bike_service.rb:42:in `import'\napp/jobs/import_job.rb:12:in `perform'\n..." } } ``` -------------------------------- ### Trace Correlation Output Example Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/api-reference/datadog-log-injection.md This JSON structure illustrates the log output when trace correlation is active. It includes trace and span IDs, environment, service, and version for Datadog to correlate logs with traces and metrics. ```json { "timestamp": "2025-10-26T10:31:00.456Z", "status": "info", "message": "Performing ImportBikesJob", "named_tags": { "job_class": "ImportBikesJob", "job_id": "abc-123", "queue": "default" }, "dd": { "trace_id": "1234567890", "span_id": "9876543210", "env": "production", "service": "rails_app", "version": "1.0.0" } } ``` -------------------------------- ### Detailed `log_semantic` Matcher Usage Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/api-reference/rspec-matchers.md This example demonstrates a more detailed usage of the `log_semantic` matcher, specifying level, message, and payload criteria. The matcher captures logs emitted within the block and checks if any meet all criteria. ```ruby expect { logger.info("hello", key: "val") } .to log_semantic(level: :info, message: /hello/, payload: { key: "val" }) ``` -------------------------------- ### Datadog Error Log Example Source: https://github.com/fabn/rails_semantic_logging/blob/main/README.md This JSON illustrates an error log entry, capturing exception details like 'error.kind', 'error.message', and 'error.stack'. This format ensures errors are properly parsed and correlated in Datadog. ```json { "timestamp": "2025-10-26T10:32:15.789Z", "status": "error", "host": "web-01", "logger.name": "BikeService", "message": "Failed to import bike", "error.kind": "ActiveRecord::RecordInvalid", "error.message": "Validation failed: VIN is not unique", "error.stack": "app/services/bike_service.rb:42:in `import'\n..." } ``` -------------------------------- ### Run Full Test Suite Source: https://github.com/fabn/rails_semantic_logging/blob/main/CLAUDE.md Execute the complete test suite for the project. ```bash bundle exec rspec ``` -------------------------------- ### Datadog Background Job Log Example Source: https://github.com/fabn/rails_semantic_logging/blob/main/README.md This JSON shows a log entry for a background job, including job-specific named tags. The 'executions' field tracks ActiveJob attempts, and 'provider_job_id' links to the job in Mission Control or backend tables. ```json { "timestamp": "2025-10-26T10:31:00.456Z", "status": "info", "host": "worker-01", "logger.name": "Rails", "message": "Performing ImportBikesJob from Sidekiq(default)", "named_tags": { "job_class": "ImportBikesJob", "job_id": "abc-123", "queue": "default", "executions": 0, "provider_job_id": "9632" } } ``` -------------------------------- ### Instantiate Configuration Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/api-reference/configuration.md Instantiate a new Configuration object with default values and set application-specific settings. ```ruby config = RailsSemanticLogging::Configuration.new config.application_name = 'MyApp' ``` -------------------------------- ### Datadog Formatter Initialization Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/INDEX.md Shows how to initialize the Datadog formatter with specific time formatting options. ```ruby RailsSemanticLogging::Formatters::Datadog #new(time_format:, time_key:, **args) #call(log, logger) ``` -------------------------------- ### Instantiate Custom Formatter Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/EXPORTS.md Demonstrates how to create a new instance of the Datadog formatter for custom log formatting. ```ruby RailsSemanticLogging::Formatters::Datadog.new ``` -------------------------------- ### RailsSemanticLogging::Configuration#new Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/api-reference/configuration.md Instantiates a new Configuration object with default values. This is the entry point for setting up custom configurations. ```APIDOC ## RailsSemanticLogging::Configuration#new ### Description Instantiates a new Configuration object with default values. This is the entry point for setting up custom configurations. ### Method `new()` ### Returns Configuration instance with all defaults loaded ``` -------------------------------- ### Add Gem to Gemfile Source: https://github.com/fabn/rails_semantic_logging/blob/main/README.md Add the rails_semantic_logging gem to your application's Gemfile to install it. ```ruby gem 'rails_semantic_logging' ``` -------------------------------- ### Datadog Initialization Configuration Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/api-reference/datadog-log-injection.md Configure Datadog tracing in `config/initializers/datadog.rb`. Enable tracing, ActiveJob integration, and log injection. ```ruby # config/initializers/datadog.rb Datadog.configure do |c| c.tracing.enabled = true c.tracing.contrib.active_job.enabled = true c.tracing.contrib.active_job.log_injection = true end ``` -------------------------------- ### Raise Custom Error Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/api-reference/module-entry-point.md Example of raising a custom gem-specific error. This is useful for signaling configuration issues or other gem-related problems. ```ruby raise RailsSemanticLogging::Error, 'Datadog formatter misconfigured' ``` -------------------------------- ### Show All Logs During Tests Source: https://github.com/fabn/rails_semantic_logging/blob/main/CLAUDE.md Run tests and display all log messages. ```bash LOG=all bundle exec rspec spec/path.rb ``` -------------------------------- ### RSpec Matchers Setup Source: https://github.com/fabn/rails_semantic_logging/blob/main/README.md Include the RSpec matchers module in your spec configuration to enable testing with Rails Semantic Logging. ```ruby require 'rails_semantic_logging/rspec/matchers' RSpec.configure do |config| config.include RailsSemanticLogging::RSpec::Matchers end ``` -------------------------------- ### Get Log Level for Environment Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/api-reference/configuration.md Determine the log level for a specific Rails environment. Respects the LOG_LEVEL environment variable for overrides. ```ruby config = RailsSemanticLogging.config config.log_level_for('development') # => "DEBUG" config.log_level_for('test') # => "FATAL" # Override via environment variable ENV['LOG_LEVEL'] = 'INFO' config.log_level_for('any_env') # => "INFO" ``` -------------------------------- ### Instantiate Datadog Formatter Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/api-reference/formatters-datadog.md Create a new instance of the Datadog formatter. This is typically done during application configuration in a production environment. ```ruby formatter = RailsSemanticLogging::Formatters::Datadog.new # In production configuration: app.config.rails_semantic_logger.format = formatter ``` -------------------------------- ### Complete Programmatic Configuration Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/api-reference/configuration.md Use this block in `config/application.rb` to set application-wide logging configurations, including application name, environment, formatter preferences, and custom log tags. ```ruby # config/application.rb RailsSemanticLogging.configure do |config| config.application_name = 'BikeRental' config.environment_name = ENV.fetch('NAMESPACE', Rails.env) config.quiet_assets = !Rails.env.development? config.sync_in_test = true config.default_payload = true config.production_formatter = :datadog config.development_formatter = :color # Custom tags as lambdas receive request context config.custom_log_tags = { tenant_id: ->(request) { request.headers['X-Tenant-ID'] }, user_id: ->(request) { extract_user(request)&.id } } end ``` -------------------------------- ### Multi-Tenant SaaS Configuration Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/README.md Set up custom log tags for multi-tenant applications, including tenant and user IDs extracted from request headers. ```ruby RailsSemanticLogging.configure do |config| config.application_name = 'SaaS' config.custom_log_tags = { tenant_id: ->(request) { request.headers['X-Tenant-ID'] }, user_id: ->(request) { current_user(request)&.id } } end ``` -------------------------------- ### Configure Application Name Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/api-reference/module-entry-point.md Set the application name in your `config/application.rb` file for semantic logging. ```ruby RailsSemanticLogging.configure do |config| config.application_name = 'MyApp' end ``` -------------------------------- ### Auto-inclusion in ActionController Base Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/api-reference/action-controller-default-payload.md This code demonstrates how the Railtie automatically includes the `DefaultPayload` concern in `ActionController::Base` subclasses. It's part of the default setup. ```ruby ActiveSupport.on_load(:action_controller_base) do include RailsSemanticLogging::ActionController::DefaultPayload end ``` -------------------------------- ### Configuration Class Methods Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/INDEX.md Details methods available on the Configuration class for managing logging settings. ```ruby RailsSemanticLogging::Configuration #new() #effective_log_tags() #formatter_for(env) #log_level_for(env) ``` -------------------------------- ### Get Default Application Name Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/configuration.md Illustrates the default behavior for `application_name` when not explicitly set, falling back to the Rails application's module name. ```ruby Rails.application.class.module_parent_name # => "MyApp" if your class is MyApp::Application ``` -------------------------------- ### Configuration Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/INDEX.md Details the configuration object and its available methods for customizing logging behavior. ```APIDOC ## Configuration ### Description Details the configuration object and its available methods for customizing logging behavior. ### Class `RailsSemanticLogging::Configuration` ### Methods - `new()` - `effective_log_tags()` - `formatter_for(env)` - `log_level_for(env)` ``` -------------------------------- ### Get Effective Log Tags Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/api-reference/configuration.md Retrieve a hash of log tags, merging default tags like request_id and client_ip with any custom tags defined in the application. ```ruby config = RailsSemanticLogging.config tags = config.effective_log_tags # => { request_id: :request_id, client_ip: :remote_ip, custom_tag: ->(req) { ... } } ``` -------------------------------- ### Configure Development Formatter to Color Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/configuration.md Set the development formatter to `:color` for human-readable colorized console output. This is the default for non-production environments. ```ruby RailsSemanticLogging.configure do |config| config.development_formatter = :color # colorized console output end ``` -------------------------------- ### Preserving Query String in Request Path Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/api-reference/action-controller-default-payload.md This example demonstrates how `request.fullpath` is used to preserve the query string, which is otherwise stripped by `rails_semantic_logger` from `request.path`. The Datadog formatter can then parse this into `http.url_details.queryString`. ```text Request: GET /search?q=bikes&limit=10 Rails :path: /search (query string stripped by rails_semantic_logger) DefaultPayload :full_path: /search?q=bikes&limit=10 (preserved) Datadog output: http.url_details.queryString: { q: "bikes", limit: "10" } ``` -------------------------------- ### Configure the Gem Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/EXPORTS.md Shows how to configure the Rails Semantic Logging gem using a block that accepts a configuration object. ```ruby RailsSemanticLogging.configure { |config| ... } ``` -------------------------------- ### Formatters Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/INDEX.md Documentation for the Datadog formatter, including its initialization and usage. ```APIDOC ## Formatters ### Datadog Formatter #### Description Provides a formatter compatible with Datadog's logging requirements. #### Class `RailsSemanticLogging::Formatters::Datadog` #### Methods - `new(time_format:, time_key:, **args)` - `call(log, logger)` ``` -------------------------------- ### Register Custom Patches Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/EXPORTS.md Illustrates how to register custom patches for Active Job using `ActiveSupport.on_load` to prepend a module. ```ruby ActiveSupport.on_load(:active_job) do ActiveJob::Base.prepend(MyPatch) end ``` -------------------------------- ### Format Log Entry for Datadog Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/api-reference/formatters-datadog.md Demonstrates how to use the Datadog formatter to convert a SemanticLogger log entry into a JSON string with Datadog Standard Attributes. Ensure you have SemanticLogger and RailsSemanticLogging gems installed. ```ruby log = SemanticLogger::Log.new( 'MyService', :info, 'Request completed', duration: 42, payload: { status: 200, method: 'GET' } ) formatter = RailsSemanticLogging::Formatters::Datadog.new json_output = formatter.call(log, logger_instance) # => '{"timestamp":"2025-10-26T10:30:45.123Z","status":"info",...}' ``` -------------------------------- ### Datadog Log Injection - Applying Patches Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/INDEX.md Demonstrates how to apply log injection patches for Datadog integration, including patching for 'perform_now' and 'enqueue' operations. ```ruby RailsSemanticLogging::Datadog::LogInjection .apply! .patch_perform_now .patch_enqueue ``` -------------------------------- ### Test Configuration Reset and Reconfiguration Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/api-reference/module-entry-point.md Demonstrates resetting the configuration and applying new settings, typically within a test suite. The `ensure` block guarantees the configuration is reset after the test. ```ruby it 'logs with custom formatter' do original_config = RailsSemanticLogging.config.dup RailsSemanticLogging.reset_config! RailsSemanticLogging.configure do |config| config.production_formatter = :json end # Test code here ensure RailsSemanticLogging.reset_config! # Config is fresh on next test end ``` -------------------------------- ### Set Application Name via Environment Variable Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/configuration.md Set the application name using an environment variable. This method has the highest priority for configuration. ```bash RAILS_SEMANTIC_LOGGING_APPLICATION_NAME=BikeRental bin/rails server ``` -------------------------------- ### Declarative `log_semantic` Matcher Examples Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/api-reference/rspec-matchers.md Use the `log_semantic` matcher to assert that a block of code emits at least one log entry matching the specified criteria. This provides a declarative way to test log output. ```ruby expect { logger.info("hello") }.to log_semantic(level: :info, message: /hello/) expect { service.call }.to log_semantic(named_tags: { job_class: 'MyJob' }) expect { do_work }.to log_semantic(payload: { items: 3 }) ``` -------------------------------- ### Run Single Spec File Source: https://github.com/fabn/rails_semantic_logging/blob/main/CLAUDE.md Execute tests for a specific spec file. ```bash bundle exec rspec spec/path/to/spec.rb ``` -------------------------------- ### Appender Validation Logic Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/api-reference/rspec-helpers.md This code snippet shows the validation logic executed during RSpec suite setup to ensure exactly one appender is configured at the trace level. This is crucial for the correct functioning of logging matchers. ```ruby # checks in configure_rspec! / before(:suite) block if SemanticLogger.appenders.size != 1 || SemanticLogger.appenders.first.level != :trace raise 'Expected only one appender with trace level, ' \ "got #{SemanticLogger.appenders.size} with #{SemanticLogger.appenders.map(&:level)}" end ``` -------------------------------- ### Pin Rails Version for Testing Source: https://github.com/fabn/rails_semantic_logging/blob/main/CLAUDE.md Update Rails to a specific version and run tests. ```bash RAILS_VERSION=7.1 bundle update rails && bundle exec rspec ``` -------------------------------- ### Controller Integration - Default Payload Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/INDEX.md Demonstrates how to append information to the default payload in Action Controller. ```ruby RailsSemanticLogging::ActionController::DefaultPayload #append_info_to_payload(payload) ``` -------------------------------- ### Multi-Tenant SaaS Configuration Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/configuration.md Configure custom log tags for multi-tenant applications to include tenant ID, user ID, and API key information in logs. This requires a request object to extract the necessary data. ```ruby RailsSemanticLogging.configure do |config| config.application_name = 'TenantSaaS' config.custom_log_tags = { tenant_id: ->(request) { request.headers['X-Tenant-ID'] }, user_id: ->(request) { current_user(request)&.id }, api_key: ->(request) { request.headers['X-API-Key']&.first(8) } } end ``` -------------------------------- ### Module Hierarchy Overview Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/EXPORTS.md Illustrates the module hierarchy of the Rails Semantic Logging gem, showing the organization of its various components and namespaces. ```ruby RailsSemanticLogging (top-level module) ├── Error (exception class) ├── Configuration (config management) ├── VERSION (constant) ├── Formatters (namespace) │ └── Datadog (formatter) ├── ActionController (namespace) │ └── DefaultPayload (concern) ├── JobLogging (namespace) │ ├── ActiveJobPatch (module) │ └── SidekiqPatch (module) ├── Datadog (namespace) │ └── LogInjection (module) ├── Railtie (Rails integration) └── RSpec (namespace) ├── InMemoryAppender (appender) ├── LogSemanticMatcher (matcher) ├── HaveLoggedMessageMatcher (matcher) ├── Matchers (module) └── Helpers (module) ├── LoggingHelpers (submodule) └── SilenceOutput (submodule) ``` -------------------------------- ### Rails Semantic Logging File Structure Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/MANIFEST.md Illustrates the directory layout and file organization for the rails_semantic_logging gem's documentation. ```text /workspace/home/output/ ├── 00-START-HERE.md (Entry point, quick navigation) ├── README.md (Overview, features, examples) ├── configuration.md (Complete config guide) ├── EXPORTS.md (All exported symbols) ├── INDEX.md (Topic-based navigation) ├── MANIFEST.md (This file) └── api-reference/ ├── module-entry-point.md (RailsSemanticLogging module) ├── configuration.md (Configuration class) ├── formatters-datadog.md (Datadog formatter) ├── action-controller-default-payload.md (Controller enrichment) ├── job-logging-patches.md (ActiveJob & Sidekiq patches) ├── datadog-log-injection.md (Datadog integration) ├── railtie.md (Rails integration) ├── rspec-matchers.md (RSpec matchers) └── rspec-helpers.md (RSpec helpers) ``` -------------------------------- ### Configure Production Formatter with Custom Instance Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/configuration.md Use a custom formatter instance for production logs by subclassing `SemanticLogger::Formatters::Base`. Ensure your custom formatter implements the `call` method. ```ruby class CustomFormatter < SemanticLogger::Formatters::Base def call(log, logger) # custom formatting end end RailsSemanticLogging.configure do |config| config.production_formatter = CustomFormatter.new end ``` -------------------------------- ### Configure Semantic Logger Application and Environment Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/api-reference/railtie.md Configures the Semantic Logger application name and environment during the `to_prepare` phase. This runs before the first request and before each code reload in development. It uses configuration options or falls back to Rails defaults. ```ruby config.to_prepare do cfg = RailsSemanticLogging.config SemanticLogger.application = cfg.application_name || Rails.application.class.module_parent_name SemanticLogger.environment = cfg.environment_name || Rails.env SemanticLogger.sync! if Rails.env.test? && cfg.sync_in_test end ``` -------------------------------- ### Configure Production Formatter via YAML Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/configuration.md Set the production formatter to `json` using a YAML configuration file. This allows for environment-specific logging configurations. ```yaml production: production_formatter: json ``` -------------------------------- ### Top-Level Methods Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/INDEX.md Provides access to the gem's configuration, version, and error class. ```APIDOC ## Top-Level Methods ### Description Provides access to the gem's configuration, version, and error class. ### Methods - `RailsSemanticLogging.config` - `RailsSemanticLogging.configure { |c| ... }` - `RailsSemanticLogging.reset_config!` - `RailsSemanticLogging::VERSION` - `RailsSemanticLogging::Error` ``` -------------------------------- ### RailsSemanticLogging.config Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/api-reference/configuration.md Returns the global configuration singleton instance. This allows direct access to and modification of the current configuration settings. ```APIDOC ## `RailsSemanticLogging.config → Configuration` Returns the global configuration singleton. ```ruby RailsSemanticLogging.config.application_name = 'MyApp' ``` ``` -------------------------------- ### Datadog Tracing Gemfile Configuration Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/api-reference/datadog-log-injection.md Add the `ddtrace` gem to your Gemfile to enable Datadog tracing. Ensure it is loaded to apply patches. ```ruby # Gemfile gem 'ddtrace' ``` -------------------------------- ### Environment-Aware Configuration Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/README.md Configure environment-specific settings and custom log tags, such as region, which can be fetched from environment variables or defaults. ```ruby RailsSemanticLogging.configure do |config| config.application_name = 'MyApp' config.environment_name = ENV.fetch('NAMESPACE', Rails.env) # => "prod-east", "prod-west", "staging", "development" config.custom_log_tags = { region: ->(request) { request.headers['X-Region'] || 'us-east-1' } } end ``` -------------------------------- ### Accessing Rails App in to_prepare Block Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/api-reference/railtie.md Shows how to access the Rails application object within a `to_prepare` block. Note that the `app` parameter is not available directly, and `Rails.application` should be used instead. ```ruby config.to_prepare do # No app parameter; use Rails.application Rails.env.test? && ... end ``` -------------------------------- ### Access Global Configuration Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/api-reference/module-entry-point.md Retrieve the global Configuration singleton instance. This instance is lazily initialized and mutable. ```ruby RailsSemanticLogging.config # => # # Access configuration values RailsSemanticLogging.config.application_name # => "MyApp" RailsSemanticLogging.config.production_formatter # => # ``` -------------------------------- ### Enable Logging in Tests Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/EXPORTS.md Shows how to temporarily enable logging at specific levels within a block of code for testing purposes, using `with_logging` and `with_ar_logging`. ```ruby with_logging(:trace) { ... } with_ar_logging(:debug) { ... } ``` -------------------------------- ### Access Current Configuration Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/EXPORTS.md Demonstrates how to access the current configuration object of the Rails Semantic Logging gem. ```ruby RailsSemanticLogging.config ``` -------------------------------- ### Development Debugging Configuration Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/configuration.md Configure the development formatter to use colorized output by default or JSON format if the JSON_LOGS environment variable is set. This aids in debugging during development. ```ruby # config/environments/development.rb RailsSemanticLogging.configure do |config| config.development_formatter = if ENV['JSON_LOGS'] :json else :color # default end end # Usage: # bin/rails server # colorized # JSON_LOGS=1 bin/rails server # JSON ``` -------------------------------- ### Environment Variable Overrides for Rails Semantic Logging Source: https://github.com/fabn/rails_semantic_logging/blob/main/_autodocs/README.md Demonstrates how to override Rails Semantic Logging configurations using environment variables at runtime. ```bash # Override formatter RAILS_SEMANTIC_LOGGING_PRODUCTION_FORMATTER=json bin/rails server # Override app name RAILS_SEMANTIC_LOGGING_APPLICATION_NAME=BikeRental bin/rails server # Disable asset quieting for debugging RAILS_SEMANTIC_LOGGING_QUIET_ASSETS=false bin/rails server ```