Skip to content

Event context

View Markdown

You can add custom metadata to the events sent to Honeybadger Insights by using the Honeybadger.event_context method. This metadata will be included in each event sent within the same thread.

For example, you can add user ID information to all events (via a Rails controller):

class ApplicationController < ActionController::Base
before_action :set_honeybadger_context
private
def set_honeybadger_context
if current_user
Honeybadger.event_context(user_id: current_user.id, user_email: current_user.email)
end
end
end

Event context is not automatically propagated to other threads. If you want to add context to events in a different thread, you can use the Honeybadger.get_event_context method to get the current context and pass it to the Honeybadger.event method:

class MyJob < ApplicationJob
def perform(user_id)
# Get context from the main thread
context = Honeybadger.get_event_context
Thread.new do
# Set the context in the new thread
Honeybadger.event_context(context)
# Do some work here
Honeybadger.event("background_work", { user_id: user_id, status: "completed" })
end
end
end

You can also set event context for a specific block of code using a block form:

Honeybadger.event_context(user_id: 123) do
# All events within this block will include the user_id context
Honeybadger.event("user_action", { action: "login" })
Honeybadger.event("user_action", { action: "logout" })
end
# Context is automatically cleared after the block

You can clear the current event context at any time:

Honeybadger.event_context.clear!