Skip to main content

Log Context

Context allows you to attach metadata to all logs within a specific scope, without passing it to every log call.

Global Context

Set context that applies to all logs:
BrainzLab.set_context(
  deployment: "v2.3.1",
  datacenter: "us-east-1"
)

User Context

Set the current user:
BrainzLab.set_user(
  id: current_user.id,
  email: current_user.email,
  name: current_user.name,
  plan: current_user.plan
)
In Rails, set this in a before_action:
class ApplicationController < ActionController::Base
  before_action :set_brainzlab_user

  private

  def set_brainzlab_user
    if current_user
      BrainzLab.set_user(
        id: current_user.id,
        email: current_user.email,
        name: current_user.name
      )
    end
  end
end

Request Context

Automatically captured in Rails:
  • request_id - The Rails request ID
  • path - The request path
  • method - HTTP method
  • controller - Controller name
  • action - Action name
  • format - Response format

Block-Scoped Context

Add context for a specific block:
BrainzLab.with_context(order_id: order.id) do
  BrainzLab::Recall.info("Processing order")    # includes order_id
  BrainzLab::Recall.info("Charging card")       # includes order_id
  BrainzLab::Recall.info("Order complete")      # includes order_id
end

BrainzLab::Recall.info("Next log")  # does NOT include order_id

Tags

Tags are indexed for fast filtering:
BrainzLab.set_tags(
  feature: "checkout",
  version: "v2",
  ab_test: "variant_a"
)
Query by tags:
tag.feature:checkout since:1h

Environment Variables

Automatically captured:
VariableDescription
RAILS_ENVRails environment
GIT_COMMITGit commit SHA
GIT_BRANCHGit branch name
DYNOHeroku dyno name
HOSTNAMEServer hostname

Custom Auto-Context

Add context automatically to every log:
BrainzLab.configure do |config|
  config.recall_context_builder = -> {
    {
      tenant_id: Current.tenant&.id,
      feature_flags: Current.feature_flags
    }
  }
end

Clearing Context

Clear all context:
BrainzLab.clear_context
Clear specific keys:
BrainzLab.clear_context(:order_id, :payment_id)

Thread Safety

Context is stored in thread-local storage, so it’s automatically isolated between requests in threaded servers like Puma.
# Request 1
BrainzLab.set_user(id: 1)
BrainzLab::Recall.info("Log from user 1")  # user.id = 1

# Request 2 (concurrent)
BrainzLab.set_user(id: 2)
BrainzLab::Recall.info("Log from user 2")  # user.id = 2