{"id":32750028,"url":"https://github.com/amkisko/activesupport-json_logging.rb","last_synced_at":"2026-01-20T17:34:55.674Z","repository":{"id":321818845,"uuid":"1087315242","full_name":"amkisko/activesupport-json_logging.rb","owner":"amkisko","description":"Structured JSON logging for Rails and ActiveSupport with a safe, single-line formatter.","archived":false,"fork":false,"pushed_at":"2025-10-31T18:21:40.000Z","size":0,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-10-31T18:32:19.756Z","etag":null,"topics":["activesupport","logging","rails","ruby","rubygem"],"latest_commit_sha":null,"homepage":"https://rubygems.org/gems/activesupport-json_logging","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/amkisko.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-10-31T17:51:14.000Z","updated_at":"2025-10-31T18:21:43.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/amkisko/activesupport-json_logging.rb","commit_stats":null,"previous_names":["amkisko/activesupport-json_logging.rb"],"tags_count":2,"template":false,"template_full_name":null,"purl":"pkg:github/amkisko/activesupport-json_logging.rb","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/amkisko%2Factivesupport-json_logging.rb","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/amkisko%2Factivesupport-json_logging.rb/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/amkisko%2Factivesupport-json_logging.rb/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/amkisko%2Factivesupport-json_logging.rb/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/amkisko","download_url":"https://codeload.github.com/amkisko/activesupport-json_logging.rb/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/amkisko%2Factivesupport-json_logging.rb/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":283113561,"owners_count":26781474,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-11-07T02:00:06.343Z","response_time":61,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["activesupport","logging","rails","ruby","rubygem"],"created_at":"2025-11-03T23:00:24.924Z","updated_at":"2026-01-20T17:34:55.661Z","avatar_url":"https://github.com/amkisko.png","language":"Ruby","funding_links":[],"categories":[],"sub_categories":[],"readme":"# activesupport-json_logging\n\n[![Gem Version](https://badge.fury.io/rb/activesupport-json_logging.svg)](https://badge.fury.io/rb/activesupport-json_logging) [![Test Status](https://github.com/amkisko/activesupport-json_logging.rb/actions/workflows/test.yml/badge.svg)](https://github.com/amkisko/activesupport-json_logging.rb/actions/workflows/test.yml) [![codecov](https://codecov.io/gh/amkisko/activesupport-json_logging.rb/graph/badge.svg?token=UX80FTO0Y0)](https://codecov.io/gh/amkisko/activesupport-json_logging.rb) [![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=amkisko_activesupport-json_logging.rb\u0026metric=alert_status)](https://sonarcloud.io/summary/new_code?id=amkisko_activesupport-json_logging.rb)\n\nStructured JSON logging for Rails and ActiveSupport with a safe, single-line formatter.\nNo dependencies beyond Rails and Activesupport.\nSupports Rails versions from 6 to 8.\n\nSponsored by [Kisko Labs](https://www.kiskolabs.com).\n\n\u003ca href=\"https://www.kiskolabs.com\"\u003e\n  \u003cimg src=\"kisko.svg\" width=\"200\" alt=\"Sponsored by Kisko Labs\" /\u003e\n\u003c/a\u003e\n\n\n## Installation\n\nAdd to your Gemfile:\n\n```ruby\ngem \"activesupport-json_logging\"\n```\n\nRun bundler:\n\n```bash\nbundle install\n```\n\nUpdate configuration:\n\n```ruby\nRails.application.configure do\n  config.logger = JsonLogging.new(Logger.new(STDOUT))\nend\n```\n\n\n## What you get\n\n- `JsonLogging.new(logger)` - Wraps any standard Logger object to provide JSON formatting (similar to `ActiveSupport::TaggedLogging.new`)\n- `JsonLogging.logger(*args)` - Convenience method that creates an `ActiveSupport::Logger` and wraps it\n- Safe JSON serialization that never raises from the formatter\n- `JsonLogging.with_context` to attach contextual fields per-thread\n- Smart message parsing (handles hashes, JSON strings, plain strings, and Exception objects)\n- Native `tagged` method support - use it just like Rails' tagged logger\n- Service-specific tagged loggers - create loggers with permanent tags using `logger.tagged(\"service\")` without a block\n- Full compatibility with `ActiveSupport::BroadcastLogger` (Rails 7.1+)\n- Automatic Rails integration via Railtie (auto-requires the gem in Rails apps)\n\n## Basic usage\n\n```ruby\n# Wrap any standard logger\nlogger = JsonLogging.new(Logger.new(STDOUT))\nlogger.info(\"Booted\")\n\n# Or use the convenience method\nlogger = JsonLogging.logger($stdout)\nlogger.info(\"Booted\")\n\n# Tagged logging - works just like Rails.logger.tagged\nlogger.tagged(\"REQUEST\", request_id) do\n  logger.info(\"Processing request\")\nend\n\n# Tagged logging without block (returns new logger with tags)\nlogger.tagged(\"BCX\").info(\"Stuff\")\nlogger.tagged(\"BCX\", \"Jason\").info(\"Stuff\")\nlogger.tagged(\"BCX\").tagged(\"Jason\").info(\"Stuff\")\n\n# Create a service-specific logger with permanent tags\n# All logs from this logger will include the \"dotenv\" tag\ndotenv_logger = logger.tagged(\"dotenv\")\ndotenv_logger.info(\"Loading environment variables\")  # Includes \"dotenv\" tag\ndotenv_logger.warn(\"Missing .env file\")  # Includes \"dotenv\" tag\n\n# You can also create service loggers directly\nbase_logger = JsonLogging.logger($stdout)\nservice_logger = base_logger.tagged(\"my-service\")\nservice_logger.info(\"Service started\")  # All logs tagged with \"my-service\"\n\n# Add context\nJsonLogging.with_context(user_id: 123) do\n  logger.warn({event: \"slow_query\", duration_ms: 250})\nend\n\n# Log exceptions (automatically formatted with class, message, and backtrace)\nbegin\n  raise StandardError.new(\"Something went wrong\")\nrescue =\u003e e\n  logger.error(e)  # Exception is automatically parsed and formatted\nend\n```\n\n## Rails configuration\n\nThis gem does **not** automatically configure your Rails app. You set it up manually in initializers or environment configs.\n\n**Note:** \n- In Rails apps, the gem is automatically required via Railtie, so you typically don't need to manually `require \"json_logging\"` in initializers (though it's harmless if you do).\n- In Rails 7.1+, Rails automatically wraps your logger in `ActiveSupport::BroadcastLogger` to enable writing to multiple destinations (e.g., STDOUT and file simultaneously). This works seamlessly with our logger - your JSON logger will be wrapped and all method calls will delegate correctly. No special handling needed.\n- In Rails 7.1+, tag storage uses `ActiveSupport::IsolatedExecutionState` for improved thread/Fiber safety.\n\n### Service-specific loggers with tags\n\nYou can create loggers with permanent tags for specific services or components. This is useful when you want all logs from a particular service to be tagged consistently:\n\n```ruby\n# Create a logger for DotEnv service with \"dotenv\" tag\nbase_logger = JsonLogging.logger($stdout)\ndotenv_logger = base_logger.tagged(\"dotenv\")\n\n# All logs from this logger will include the \"dotenv\" tag\ndotenv_logger.info(\"Loading .env file\")\ndotenv_logger.warn(\"Missing .env.local file\")\ndotenv_logger.error(\"Invalid environment variable format\")\n\n# Example: Configure Dotenv::Rails to use tagged logger\nif defined?(Dotenv::Rails)\n  Dotenv::Rails.logger = base_logger.tagged(\"dotenv\")\nend\n\n# Example: Create multiple service loggers\nredis_logger = base_logger.tagged(\"redis\")\nsidekiq_logger = base_logger.tagged(\"sidekiq\")\napi_logger = base_logger.tagged(\"api\")\n\n# Each service logger maintains its tag across all log calls\nredis_logger.info(\"Connected to Redis\")  # Tagged with \"redis\"\nsidekiq_logger.info(\"Job enqueued\")      # Tagged with \"sidekiq\"\napi_logger.info(\"Request received\")      # Tagged with \"api\"\n```\n\n### BroadcastLogger integration\n\n`ActiveSupport::BroadcastLogger` (Rails 7.1+) allows writing logs to multiple destinations simultaneously. `JsonLogging` works seamlessly with `BroadcastLogger`:\n\n```ruby\n# Create JSON loggers for different destinations\nstdout_logger = JsonLogging.logger($stdout)\nfile_logger = JsonLogging.logger(Rails.root.join(\"log\", \"production.log\"))\n\n# Wrap in BroadcastLogger to write to both destinations\nbroadcast_logger = ActiveSupport::BroadcastLogger.new(stdout_logger)\nbroadcast_logger.broadcast_to(file_logger)\n\n# All logging methods work through BroadcastLogger\nbroadcast_logger.info(\"This goes to both STDOUT and file\")\nbroadcast_logger.warn({event: \"warning\", message: \"Something happened\"})\n\n# Tagged logging works through BroadcastLogger\nbroadcast_logger.tagged(\"REQUEST\", request_id) do\n  broadcast_logger.info(\"Processing request\")  # Tagged logs go to both destinations\nend\n\n# Service-specific loggers work with BroadcastLogger\n# Note: Create service logger from underlying logger, then wrap in BroadcastLogger\n# (BroadcastLogger.tagged without block returns array due to delegation)\nbase_logger = JsonLogging.logger($stdout)\ndotenv_logger = base_logger.tagged(\"dotenv\")\ndotenv_broadcast = ActiveSupport::BroadcastLogger.new(dotenv_logger)\ndotenv_broadcast.broadcast_to(file_logger.tagged(\"dotenv\"))  # Tag second destination too\ndotenv_broadcast.info(\"Environment loaded\")  # Tagged and broadcast to all destinations\n\n# Rails 7.1+ automatically uses BroadcastLogger\n# Your configuration can be simplified:\nRails.application.configure do\n  # Rails will automatically wrap this in BroadcastLogger\n  base_logger = ActiveSupport::Logger.new($stdout)\n  json_logger = JsonLogging.new(base_logger)\n  config.logger = json_logger  # Rails wraps this in BroadcastLogger automatically\nend\n```\n\n**Key points:**\n- All logger methods (`info`, `warn`, `error`, etc.) work through `BroadcastLogger`\n- Tagged logging (`tagged`) works correctly through `BroadcastLogger`\n- Service-specific tagged loggers work with `BroadcastLogger`\n- Each destination receives properly formatted JSON logs\n- No special configuration needed - just wrap your `JsonLogging` logger in `BroadcastLogger`\n\n### Basic setup\n\nCreate `config/initializers/json_logging.rb`:\n\n```ruby\n# Note: In Rails apps, the gem is automatically required via Railtie,\n# so the require below is optional but harmless\n# require \"json_logging\"\n\nRails.application.configure do\n  # Build JSON logger\n  base_logger = ActiveSupport::Logger.new($stdout)\n  json_logger = JsonLogging.new(base_logger)\n\n  # Set as Rails logger\n  config.logger = json_logger\n  \n  # Optional: set log tags for request_id, etc.\n  config.log_tags = [:request_id, :remote_ip]\n\n  # Set component loggers\n  config.active_record.logger = json_logger\n  config.action_view.logger = json_logger\n  config.action_mailer.logger = json_logger\n  config.active_job.logger = json_logger\nend\n```\n\n### Environment-specific examples\n\n#### Development (`config/environments/development.rb`)\n\n```ruby\nRails.application.configure do\n  config.log_level = ENV[\"DEBUG\"].present? ? :debug : :info\n\n  # Set up JSON logging\n  base_logger = ActiveSupport::Logger.new($stdout)\n  base_logger.level = config.log_level\n  json_logger = JsonLogging.new(base_logger)\n  config.logger = json_logger\n  config.log_tags = [:request_id]\n\n  # Set component loggers\n  config.active_record.logger = json_logger\n  config.action_view.logger = json_logger\n  config.action_mailer.logger = json_logger\n  config.active_job.logger = json_logger\n\n  # Disable verbose enqueue logs to reduce noise\n  config.active_job.verbose_enqueue_logs = false\n\n  # ... rest of your development config\nend\n```\n\n#### Production (`config/environments/production.rb`)\n\n```ruby\nRails.application.configure do\n  config.log_level = :info\n  config.log_tags = [:request_id]\n\n  # Set up JSON logging\n  logdev = Rails.root.join(\"log\", \"production.log\")\n  base_logger = ActiveSupport::Logger.new(logdev)\n  base_logger.level = config.log_level\n  json_logger = JsonLogging.new(base_logger)\n  config.logger = json_logger\n\n  # Set component loggers\n  config.active_record.logger = json_logger\n  config.action_view.logger = json_logger\n  config.action_mailer.logger = json_logger\n  config.active_job.logger = json_logger\n\n  # ... rest of your production config\nend\n```\n\n#### Test (`config/environments/test.rb`)\n\n```ruby\nRails.application.configure do\n  # Set log level to fatal to reduce noise during tests\n  config.log_level = ENV[\"DEBUG\"].present? ? :debug : :fatal\n\n  # Optionally use JSON logger in tests too\n  if ENV[\"JSON_LOGS\"] == \"true\"\n    base_logger = ActiveSupport::Logger.new($stdout)\n    base_logger.level = config.log_level\n    json_logger = JsonLogging.new(base_logger)\n    config.logger = json_logger\n  end\n\n  # ... rest of your test config\nend\n```\n\n### Lograge integration\n\nIf you use Lograge, configure it to feed raw hashes and let this gem handle JSON formatting. This example shows a complete setup including all Rails component loggers and common third-party libraries:\n\n**Important:** When using Lograge, `config.log_tags` does not work for adding fields to Lograge output. Instead, use `config.lograge.custom_options` to add custom fields to your request logs.\n\n```ruby\n# config/initializers/lograge.rb\n# Note: require is optional in Rails apps (auto-loaded via Railtie)\n# require \"json_logging\"\n\nRails.application.configure do\n  # Configure Lograge\n  config.lograge.enabled = true\n  # Use Raw formatter so we pass a Hash to our JSON logger and avoid double serialization\n  config.lograge.formatter = Lograge::Formatters::Raw.new\n  config.lograge.keep_original_rails_log = ENV[\"DEBUG\"] ? true : false\n\n  # Add custom fields to Lograge output\n  # Note: config.log_tags does NOT work with Lograge - use custom_options instead\n  config.lograge.custom_options = -\u003e(event) {\n    {\n      remote_ip: Current.remote_addr,\n      request_id: Current.request_id,\n      user_agent: Current.user_agent,\n      user_id: Current.user\u0026.id\n    }\n  }\n\n  # Optionally merge additional context from JsonLogging.with_context\n  # config.lograge.custom_options = -\u003e(event) {\n  #   {\n  #     remote_ip: Current.remote_addr,\n  #     request_id: Current.request_id,\n  #     user_agent: Current.user_agent,\n  #     user_id: Current.user\u0026.id\n  #   }.merge(JsonLogging.additional_context)\n  # }\n\n  # Build unified JSON logger\n  logdev = Rails.env.production? ? Rails.root.join(\"log\", \"#{Rails.env}.log\") : $stdout\n  base_logger = ActiveSupport::Logger.new(logdev)\n  base_logger.level = config.log_level\n  json_logger = JsonLogging.new(base_logger)\n\n  # Set the main Rails logger\n  config.logger = json_logger\n\n  # Override Rails.logger to ensure it uses our formatter\n  Rails.logger = json_logger\n\n  # Set all Rails component loggers to use the same tagged logger\n  config.active_record.logger = json_logger\n  config.action_view.logger = json_logger\n  config.action_mailer.logger = json_logger\n  config.active_job.logger = json_logger\n\n  # Configure third-party library loggers (if gems are present)\n  OmniAuth.config.logger = json_logger if defined?(OmniAuth)\n  Sidekiq.logger = json_logger if defined?(Sidekiq)\n  Shrine.logger = json_logger if defined?(Shrine)\n  Sentry.configuration.sdk_logger = json_logger if defined?(Sentry)\n  Dotenv::Rails.logger = json_logger if defined?(Dotenv::Rails)\n  Webpacker.logger = json_logger if defined?(Webpacker)\n\n  # Disable verbose enqueue logs to reduce noise\n  config.active_job.verbose_enqueue_logs = false\nend\n```\n\n### Puma integration\n\nTo make Puma output JSON lines, configure it in `config/puma.rb`:\n\n```ruby\n# config/puma.rb\n# Note: require is optional in Rails apps (auto-loaded via Railtie)\n# require \"json_logging\"\n\n# ... puma config ...\n\nlog_formatter do |message|\n  formatter = JsonLogging::Formatter.new(tags: [\"Puma\"])\n  formatter.call(nil, Time.current, nil, message).strip\nend\n\n# Optional: handle low-level errors\nlowlevel_error_handler do |e|\n  # Your error reporting logic here\n  [\n    500,\n    {\"Content-Type\" =\u003e \"application/json\"},\n    [{error: \"Critical error has occurred\"}.to_json]\n  ]\nend\n```\n\n## API\n\n### JsonLogging.logger(*args, **kwargs)\n\nReturns an `ActiveSupport::Logger` that has already been wrapped with JSON logging concern. Convenience method for creating a logger and wrapping it in one call.\n\n```ruby\nlogger = JsonLogging.logger($stdout)\nlogger.info(\"message\")\n```\n\n### JsonLogging.new(logger)\n\nWraps any standard Logger object to provide JSON formatting capabilities. Similar to `ActiveSupport::TaggedLogging.new`.\n\n```ruby\n# Wrap any standard logger\nlogger = JsonLogging.new(Logger.new(STDOUT))\nlogger.info(\"message\")\nlogger.info({event: \"test\", value: 123})  # Hashes are merged into payload\n\n# Log exceptions (automatically formatted with class, message, and backtrace)\nbegin\n  raise StandardError.new(\"Error message\")\nrescue =\u003e e\n  logger.error(e)  # Exception parsed and formatted automatically\nend\n\n# Tagged logging with block\nlogger.tagged(\"REQUEST\", request_id) do\n  logger.info(\"tagged message\")\nend\n\n# Tagged logging without block (returns new logger with tags)\nlogger.tagged(\"BCX\").info(\"Stuff\")\nlogger.tagged(\"BCX\", \"Jason\").info(\"Stuff\")\nlogger.tagged(\"BCX\").tagged(\"Jason\").info(\"Stuff\")\n```\n\n**Wrapping Compatibility:** You can wrap loggers that have already been wrapped with `ActiveSupport::TaggedLogging`:\n\n```ruby\n# Wrap a TaggedLogging logger - works perfectly\ntagged_logger = ActiveSupport::TaggedLogging.new(Logger.new(STDOUT))\njson_logger = JsonLogging.new(tagged_logger)\njson_logger.tagged(\"TEST\") { json_logger.info(\"message\") }  # Tags appear at root level in JSON\n```\n\n**Note:** If you wrap a `JsonLogging` logger with `ActiveSupport::TaggedLogging`, the TaggedLogging's text-based tags will appear as part of the message string in the JSON output, not as structured tags at the root level. For best results, wrap loggers with `JsonLogging` last.\n\n### JsonLogging::JsonLogger\n\n`JsonLogging::JsonLogger` is a class that extends `ActiveSupport::Logger` directly. While still fully functional, the recommended approach is to use `JsonLogging.new` to wrap any logger, as it provides more flexibility and works with any Logger implementation (including loggers already wrapped with `ActiveSupport::TaggedLogging`).\n\n```ruby\n# Direct usage (still supported)\nlogger = JsonLogging::JsonLogger.new($stdout)\nlogger.info(\"message\")\n\n# Recommended: wrap any logger\nlogger = JsonLogging.new(ActiveSupport::Logger.new($stdout))\nlogger.info(\"message\")\n```\n\n### JsonLogging::Formatter\n\nA standalone formatter that can be used independently (e.g., in Puma's `log_formatter`). Supports adding tags via the constructor.\n\n```ruby\n# Basic usage without tags\nformatter = JsonLogging::Formatter.new\nformatter.call(\"INFO\", Time.now, nil, \"message\")\n\n# With tags (useful for Puma or other standalone use cases)\nformatter = JsonLogging::Formatter.new(tags: [\"Puma\"])\nformatter.call(\"INFO\", Time.now, nil, \"message\")  # Output includes \"Puma\" tag at root level\n\n# Multiple tags\nformatter = JsonLogging::Formatter.new(tags: [\"Puma\", \"Worker\"])\nformatter.call(\"INFO\", Time.now, nil, \"message\")  # Output includes both tags\n```\n\n**Note:** When used with a logger (via `JsonLogging.new`), the logger uses `FormatterWithTags` which automatically includes tags from the logger's tagged context. Use `Formatter` directly only when you need a standalone formatter without a logger instance.\n\n### JsonLogging.with_context\n\nAdd thread-local context that appears in all log entries within the block:\n\n```ruby\nJsonLogging.with_context(user_id: 123, request_id: \"abc\") do\n  logger.info(\"message\")  # Will include user_id and request_id in context\nend\n```\n\n### JsonLogging.additional_context\n\nReturns the current thread-local context when called without arguments, or sets a transformer when called with a block or assigned a proc.\n\n**Getting context:**\n```ruby\nJsonLogging.with_context(user_id: 5) do\n  JsonLogging.additional_context  # =\u003e {user_id: 5}\nend\n```\n\n**Setting a transformer:**\nYou can customize how `additional_context` is built by setting a transformer. This is useful for adding default fields, computed values, or filtering context. Supports both block and assignment syntax. Note: keys are automatically stringified, so no key transformation is needed.\n\n```ruby\n# Using a block (recommended)\nJsonLogging.additional_context do |context|\n  context.merge(\n    environment: Rails.env,\n    hostname: Socket.gethostname,\n    app_version: MyApp::VERSION\n  )\nend\n\n# Using assignment with a proc\nJsonLogging.additional_context = -\u003e(context) do\n  context.merge(environment: Rails.env, hostname: Socket.gethostname)\nend\n\n# Add computed values based on current request\nJsonLogging.additional_context do |context|\n  context.merge(\n    request_id: Current.request_id,\n    user_agent: Current.user_agent,\n    ip_address: Current.ip_address\n  )\nend\n\n# Filter out nil values\nJsonLogging.additional_context do |context|\n  context.compact\nend\n```\n\nThe transformer receives the current thread-local context hash and should return a hash. If the transformer raises an error, the base context will be returned to avoid breaking logging.\n\n**Note:** The transformer is called every time a log entry is created, so keep it lightweight to avoid performance issues.\n\n### Inherited Rails Logger Features\n\nSince `JsonLogging::JsonLogger` extends `ActiveSupport::Logger`, it inherits all standard Rails logger features:\n\n#### Silencing Logs\n\nTemporarily silence logs below a certain severity level:\n\n```ruby\nlogger.silence(Logger::ERROR) do\n  logger.debug(\"This won't be logged\")\n  logger.info(\"This won't be logged\")\n  logger.warn(\"This won't be logged\")\n  logger.error(\"This WILL be logged\")\nend\n```\n\n#### Thread-Local Log Levels (Rails 7.1+)\n\nSet a log level that only affects the current thread/Fiber:\n\n```ruby\n# Set thread-local level\nlogger.local_level = :debug\n\n# Only this thread will log at debug level\nlogger.debug(\"Debug message\") # Will be logged\n\n# Other threads still use the global level\n```\n\nThis is useful for:\n- Debugging specific requests without changing global log level\n- Temporary verbose logging in background jobs\n- Per-request log level changes\n\n**Note:** `local_level` is available in Rails 7.1+. In Rails 6-7.0, only the global `level` is available.\n\n#### Standard Logger Methods\n\nAll standard Ruby Logger and ActiveSupport::Logger methods work:\n\n```ruby\nlogger.level = Logger::WARN           # Set log level\nlogger.level                         # Get current level\nlogger.debug?                        # Check if debug level is enabled\nlogger.info?                         # Check if info level is enabled\nlogger.close                         # Close the logger\nlogger.reopen                       # Reopen the logger (if supported by logdev)\n```\n\n## Features\n\n- **Native tagged logging**: Use `logger.tagged(\"TAG\")` just like Rails' tagged logger\n- **Smart message parsing**: Automatically handles hashes, JSON strings, plain strings, and Exception objects (with class, message, and backtrace)\n- **Thread-safe context**: `JsonLogging.with_context` works across threads\n- **Rails 7.1+ thread/Fiber safety**: Uses `ActiveSupport::IsolatedExecutionState` for improved concurrency\n- **Never raises**: Formatter and logger methods handle errors gracefully with fallback entries\n- **Single-line JSON**: Each log entry is a single line, safe for log aggregation tools\n\n## Security \u0026 privacy\n\n- **Rails ParameterFilter integration**: Automatically uses `Rails.application.config.filter_parameters` to filter sensitive data (passwords, tokens, etc.). This includes encrypted attributes automatically. See [Rails parameter filtering guide](https://thoughtbot.com/blog/parameter-filtering).\n- **Input sanitization**: Removes control characters, truncates long strings, and limits structure depth/size:\n  - Maximum string length: 10,000 characters (truncated with `...[truncated]` suffix)\n  - Maximum context hash size: 50 keys (additional keys are truncated)\n  - Maximum nesting depth: 10 levels (deeper structures return `{\"error\" =\u003e \"max_depth_exceeded\"}`)\n  - Maximum backtrace lines: 20 lines per exception\n- **Single-line JSON**: Emits single-line JSON to avoid log injection via newlines\n- **Never fails**: Formatter and logger never raise; fallback to safe entries on serialization errors\n- **Sensitive key detection**: Falls back to pattern matching when Rails ParameterFilter isn't available\n- **You control context**: You decide what goes into context via `JsonLogging.with_context`; avoid sensitive data\n\n### Configuring sensitive parameter filtering\n\nThis gem automatically uses Rails' `config.filter_parameters` when available. Configure it in `config/initializers/filter_parameter_logging.rb`:\n\n```ruby\nRails.application.config.filter_parameters += [\n  :passw, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn\n]\n```\n\nThe gem will automatically filter these from all log entries, including context data. Encrypted attributes (using Rails 7+ `encrypts`) are automatically filtered as well.\n\n\n## Development\n\nRun release.rb script to prepare code for publishing, it has all the required checks and tests.\n\n```bash\nusr/bin/release.rb\n```\n\n### Development: Using from Local Repository\n\nWhen developing the gem or testing changes in your application, you can point your Gemfile to a local path:\n\n```ruby\n# In your application's Gemfile\ngem \"activesupport-json_logging\", path: \"../activesupport-json_logging.rb\"\n```\n\nThen run:\n\n```bash\nbundle install\n```\n\n**Note:** When using `path:` in your Gemfile, Bundler will use the local gem directly. Changes you make to the gem code will be immediately available in your application without needing to rebuild or reinstall the gem. This is ideal for development and testing.\n\n## Contributing\n\nBug reports and pull requests are welcome on GitHub at https://github.com/amkisko/activesupport-json_logging.rb\n\nContribution policy:\n- New features are not necessarily added to the gem\n- Pull request should have test coverage for affected parts\n- Pull request should have changelog entry\n\nReview policy:\n- It might take up to 2 calendar weeks to review and merge critical fixes\n- It might take up to 6 calendar months to review and merge pull request\n- It might take up to 1 calendar year to review an issue\n\n\n## Publishing\n\n```sh\nrm activesupport-json_logging-*.gem\ngem build activesupport-json_logging.gemspec\ngem push activesupport-json_logging-*.gem\n```\n\n## License\n\nThe gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Famkisko%2Factivesupport-json_logging.rb","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Famkisko%2Factivesupport-json_logging.rb","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Famkisko%2Factivesupport-json_logging.rb/lists"}