View Source Sentry (Sentry v14.0.0)
Provides the functionality to submit events to Sentry.
This library can be used to submit events to Sentry from any Elixir application. It supports several ways of reporting events:
Manually — see
capture_exception/2andcapture_message/2.Through an Erlang
:loggerhandler — seeSentry.LoggerHandler.Through an Elixir
Loggerbackend — seeSentry.LoggerBackend.Automatically for Plug/Phoenix applications — see the Setup with Plug and Phoenix guide, and the
Sentry.PlugCaptureandSentry.PlugContextmodules.Through integrations for various ecosystem tools, like Oban or Quantum.
Usage
Add the following to your production configuration:
# In config/prod.exs
config :sentry, dsn: "https://public:secret@app.getsentry.com/1",
environment_name: :prod,
tags: %{
env: "production"
}Sentry uses the :dsn option to determine whether it should record exceptions. If
:dsn is set, then Sentry records exceptions. If it's not set or set to nil,
then simply no events are sent to Sentry.
Included Environments
Before v10.0.0, the recommended way to control whether to report events to Sentry was the
:included_environmentsoption (a list of environments to report events for). This was used together with the:environment_nameoption to determine whether to send events.:included_environmentsis deprecated in v10.0.0 in favor of setting or not setting:dsn. It will be removed in v12.0.0.
You can even rely on more specific logic to determine the environment name. It's
not uncommon for most applications to have a "staging" environment. In order
to handle this without adding an additional Mix environment, you can set an
environment variable that determines the release level. By default, Sentry
picks up the SENTRY_ENVIRONMENT variable (at runtime, when starting).
Otherwise, you can read the variable at runtime. Do this only in
config/runtime.exs so that it will work both for local development as well
as Mix releases.
# In config/runtime.exs
if config_env() == :prod do
config :sentry, dsn: "https://public:secret@app.getsentry.com/1",
environment_name: System.fetch_env!("RELEASE_LEVEL")
endIn this example, we are getting the environment name from the RELEASE_LEVEL
environment variable. Now, on our servers, we can set the environment variable
appropriately. The config_env() == :prod check ensures that we only set
:dsn in production, effectively only enabling reporting in production-like
environments.
Sentry supports many configuration options. See the Configuration section for complete documentation.
Configuration
See also the official Sentry documentation.
You can configure Sentry through the application environment, under the :sentry application.
For example, you can do this in config/config.exs:
# config/config.exs
config :sentry,
# ...Sentry reads the configuration when the :sentry application starts, and
will not pick up any changes after that. This is in line with how other
Sentry SDKs (and many other Erlang/Elixir libraries) work. The reason
for this choice is performance: the SDK performs validation on application
start and then caches the configuration (in :persistent_term).
Updating Configuration at Runtime
If you must update configuration at runtime, use
put_config/2. This function is not efficient (since it updates terms in:persistent_term), but it works in a pinch. For example, it's useful if you're verifying that you send the right events to Sentry in your test suite, so you need to change the:dsnconfiguration to point to a local server that you can verify requests on.
Below you can find all the available configuration options.
Basic Options
:dsn(String.t/0ornil) - The DSN for your Sentry project. If this is not set, Sentry will not be enabled. If theSENTRY_DSNenvironment variable is set, it will be used as the default value. The default value isnil.:environment_name(String.t/0oratom/0) - The current environment name. This is used to specify the environment that an event happened in. It can be any string shorter than 64 bytes, except the string"None". When Sentry receives an event with an environment, it creates that environment if it doesn't exist yet. If theSENTRY_ENVIRONMENTenvironment variable is set, it will be used as the value for this option. The default value is"production".:traces_sample_rate- The sample rate for transaction events. A value between0.0and1.0(inclusive). A value of0.0means no transactions will be sampled, while1.0means all transactions will be sampled.This value is also used to determine if tracing is enabled: if it's not
nil, tracing is enabled.Tracing requires OpenTelemetry packages to work. See the OpenTelemetry setup documentation for guides on how to set it up.
The default value is
nil.:traces_sampler(t:traces_sampler_function/0ornil) - A function that determines the sample rate for transaction events. This function receives a sampling context struct and should return a boolean or a float between0.0and1.0.The sampling context contains:
:parent_sampled- boolean indicating if the parent trace span was sampled (nil if no parent):transaction_context- map with transaction information (name, op, etc.)
If both
:traces_samplerand:traces_sample_rateare configured,:traces_samplertakes precedence.If the callback crashes, the failure is logged at the
:errorlevel and sampling falls back to:traces_sample_rate. When:traces_sample_rateis not configured either, the trace is dropped and its child spans inherit that decision. See the Crashing Callbacks section below for more information.If the callback returns successfully but the returned value is not a boolean or a float between
0.0and1.0, the invalid sample rate is logged at the:warninglevel and the trace is dropped.Example:
traces_sampler: fn sampling_context -> case sampling_context.transaction_context.op do "http.server" -> 0.1 # Sample 10% of HTTP requests "db.query" -> 0.01 # Sample 1% of database queries _ -> false # Don't sample other operations end endThis value is also used to determine if tracing is enabled: if it's not
nil, tracing is enabled.The default value is
nil.:traces_ignore_http_status_codes(list ofinteger/0orRange.t/0) - HTTP statuses to keep out of tracing. An incoming request answered with one of these is not reported as a transaction, and neither is any work that outlives it. Takes status codes and ranges, like[404, 500..599].Defaults to
[404], so 404 Not Found requests are not traced. Set it to[]to trace them again.The transaction is dropped only once the response status is known, after the request has been handled. The trace is still propagated as sampled, so services called while handling the request still report their part of it. Dropped transactions are counted in client reports with the
event_processorreason. Outgoing requests are not affected.Available since 14.0.0.
The default value is
[404].:included_environments(list ofatom/0orString.t/0, or the atom:all) - This option is deprecated. Use :dsn to control whether to send events to Sentry. Deprecated. The environments in which Sentry can report events. If this is a list, then:environment_nameneeds to be in this list for events to be reported. If this is:all, then Sentry will report events regardless of the value of:environment_name. This will be removed in v11.0.0.:release(String.t/0ornil) - The release version of your application. This is used to correlate events with source code. If theSENTRY_RELEASEenvironment variable is set, it will be used as the default value. The default value isnil.:json_library(module/0) - A module that implements the "standard" Elixir JSON behaviour, that is, exports theencode/1anddecode/1functions.Defaults to
Jasonif theJSONkernel module is not available (it was introduced in Elixir 1.18.0). If you use the default configuration with Elixir version lower than 1.18, this option will default toJason, but you will have to add:jasonas a dependency of your application.The default value is
Jason.:send_client_reports(boolean/0) - Send diagnostic client reports about discarded events, interval is set to send a report once every 30 seconds if any discarded events exist. See Client Reports in Sentry docs. Available since v10.8.0. The default value istrue.:server_name(String.t/0) - The name of the server running the application. Not used by default.:sample_rate(float/0) - The percentage of events to send to Sentry. A value of0.0will deny sending any events, and a value of1.0will send 100% of events. Sampling is applied after the:before_sendcallback. See where the Sentry documentation suggests this. Must be between0.0and1.0(included). The default value is1.0.:tags(map ofterm/0keys andterm/0values) - A map of tags to be sent with every event. The default value is%{}.:extra(Sentry.Context.extra/0) - A map of extra data to be sent with every event. The default value is%{}.:max_breadcrumbs(non_neg_integer/0) - The maximum number of breadcrumbs to keep. SeeSentry.Context.add_breadcrumb/1. The default value is100.:max_stacktrace_arg_length(non_neg_integer/0) - The maximum length (in Unicode graphemes) of each inspected function argument reported in thevarsof a stacktrace frame. Arguments are inspected and then truncated to this length. This guards against very large terms (such as big structs) blowing up the size of an event. Available since v13.2.0. The default value is10000.:report_deps(boolean/0) - Whether to report application dependencies of your application alongside events. This list contains applications (alongside their version) that are loaded when the:sentryapplication starts. The default value istrue.:log_level- The level to use when Sentry fails to send an event due to an API failure or other reasons.Rate limits are the exception: Sentry logs them once per rate-limit window, and logs the individual events dropped while a limit is active at the
:debuglevel.All messages logged by the SDK itself carry
domain: [:sentry], so you can filter them out throughLogger's metadata filters.The default value is
:warning.:filter(module/0) - A module that implements theSentry.EventFilterbehaviour. Defaults toSentry.DefaultEventFilter. If the module cannot be called, or its callback crashes, the failure is logged at the:errorlevel and the exception is excluded. See the Filtering Exceptions section below. The default value isSentry.DefaultEventFilter.:dedup_events(boolean/0) - Whether to deduplicate events before reporting them to Sentry. If this option istrue, then the SDK will store reported events for around 30 seconds after they're reported. Any time the SDK is about to report an event, it will check if it has already reported within the past 30 seconds. If it has, then it will not report the event again, and will log a message instead. Events are deduplicated by comparing their message, exception, stacktrace, and fingerprint. Available since v10.0.0. The default value istrue.:test_mode(boolean/0) - Whether to enable test mode.When
test_mode: trueis set, the SDK automatically activates per-test configuration isolation and ensures the test registry is started at application boot. SeeSentry.Testfor the full testing guide. Available since v10.8.0.The default value is
false.:integrations(keyword/0) - Configuration for integrations with third-party libraries. Every integration has its own option and corresponding configuration options. The default value is[].:max_expected_check_in_time(integer/0) - The time in milliseconds that a check-in ID will live after it has been created.The SDK reports the start and end of each check-in. A check-in is used to track the progress of a specific check-in event associated with cron job telemetry events that are a part of the same job. However, to optimize performance and prevent potential memory issues, if a check-in end event is reported after the specified
max_expected_check_in_time, the SDK will not report it. This behavior helps manage resource usage effectively while still providing necessary tracking for your jobs. Available since 10.6.3.The default value is
600000.:monitor_config_defaults(keyword/0) - Defaults to be used for themonitor_configwhen reporting cron jobs with one of the integrations. This supports all the keys defined in the Sentry documentation. See alsoSentry.CheckIn.new/1. Available since v10.8.0. The default value is[].:oban(keyword/0) - Configuration for the Oban integration. The Oban integration requires at minumum Oban Pro v0.14 or Oban v.2.17.6. Available since v10.2.0.:capture_errors(boolean/0) - Whether to capture errors from Oban jobs. When enabled, the Sentry SDK will capture errors that happen in Oban jobs, including when errors return{:error, reason}tuples. Available since 10.3.0. The default value isfalse.:oban_tags_to_sentry_tags(t:oban_tags_to_sentry_tags_function/0ornil) - A function that determines the Sentry tags to be added based on the Oban job. This function receives anOban.Jobstruct and must return a map of tags and their values to be sent to Sentry.oban_tags_to_sentry_tags: fn job -> Map.new(job.tags, fn tag -> {"oban_tags.#{tag}", true} end) endThis example transforms all Oban job tags into Sentry tags prefixed with
oban_tags.and with a value oftrue. Available since 12.0.0.If the function crashes, the failure is logged at the
:errorlevel and the event is still reported, carrying only the tags the integration adds itself (oban_worker,oban_queue, andoban_state). A return value that is not a map is logged at the:warninglevel and falls back to those same tags. See the Crashing Callbacks section below for more information.The default value is
nil.:should_report_error_callback((Oban.Worker.t() | nil, Oban.Job.t() -> boolean())ornil) - A function that determines whether to report errors for Oban jobs. The function receives the worker module and theOban.Jobstruct and should returntrueto report the error orfalseto skip reporting.should_report_error_callback: fn _worker, job -> job.attempt >= job.max_attempts endThis example only reports errors on final retry attempts. Available since 12.0.0.
If the function crashes, the failure is logged at the
:errorlevel and the error is reported, as if the function had returnedtrue. See the Crashing Callbacks section below for more information.The default value is
nil.:cron(keyword/0) - Configuration options for configuring crons for Oban.:enabled(boolean/0) - Whether to enable the Oban integration. When enabled, the Sentry SDK will capture check-ins for Oban jobs. Available since v10.2.0. The default value isfalse.:monitor_slug_generator({module(), atom()}) - A{module, function}tuple that generates a monitor name based on theOban.Jobstruct. The function is called with theOban.Jobas its arguments and must return a string. This can be used to customize monitor slugs. Available since v10.8.0.If the function crashes, the failure is logged at the
:errorlevel and the check-in is still sent, under the slug the integration derives from the worker name. Until the function is fixed, the monitor you configured it for receives no check-ins at all. See the Crashing Callbacks section below for more information.:should_report_error_check_in_callback((Oban.Worker.t() | nil, Oban.Job.t() -> boolean())ornil) - A function that determines whether to report a failed check-in for an Oban cron job. The function receives the worker module and theOban.Jobstruct and should returntrueto report the failed check-in orfalseto skip it.should_report_error_check_in_callback: fn _worker, job -> job.attempt >= job.max_attempts endThis example only reports a failed check-in once all retries are exhausted. While retries remain the check-in is left open, so the retry that eventually succeeds closes the same check-in. Available since v13.5.0.
If the function crashes, the failure is logged at the
:errorlevel and the failed check-in is reported, as if the function had returnedtrue. See the Crashing Callbacks section below for more information.The default value is
nil.
:quantum(keyword/0) - Configuration for the Quantum integration. Available since v10.2.0.:telemetry(keyword/0) - Configuration for the Telemetry integration. Available since v10.10.0.:report_handler_failures(boolean/0) - Whether to report failures (to Sentry) that happen in telemetry handlers. These failures result in the handlers being detached, so capturing them in Sentry can be useful to detect and fix these issues as soon as possible. The default value isfalse.
:logs(keyword/0ornil) - Configuration for the logger handler that the SDK attaches automatically at startup. When this isnil(the default), the handler is not attached at all. Set it to a keyword list to attach it.The keys configure two independent features, each with its own opt-in:
Structured logs sent to Sentry's Logs Protocol, enabled by setting
:leveland further configured by:excluded_domainsand:metadata.Loggermessages reported as captured Sentry events, enabled by setting:capture_log_messagestotrueand further configured by:capture_level,:capture_metadata, and:capture_excluded_domains.
Crashes are reported as captured Sentry events whenever the handler is attached, independently of both opt-ins. The keys are documented under Logs Options below. Available since 12.0.0.
The default value is
nil.:org_id(String.t/0ornil) - An explicit organization ID for trace continuation validation. If not set, the SDK will extract it from the DSN host (e.g.,o1234fromo1234.ingest.sentry.iogives"1234"). This is useful for self-hosted Sentry or Relay setups where the org ID cannot be extracted from the DSN. Available since 12.1.0. The default value isnil.:strict_trace_continuation(boolean/0) - Whentrue, both the SDK's org ID and the incoming baggagesentry-org_idmust be present and match for a trace to be continued. Traces with a missing org ID on either side are rejected and a new trace is started. Whenfalse(the default), only a mismatch between two present org IDs will cause a new trace to be started. See the SDK spec for the full decision matrix. Available since 12.1.0. The default value isfalse.:telemetry_processor_categories- List of event categories that should be processed through the TelemetryProcessor. Categories in this list use the TelemetryProcessor's ring buffer and weighted round-robin scheduler, which provides prioritized scheduling and backpressure. Categories not in this list use the original sender-based approach.Log and metric events always use the TelemetryProcessor regardless of this setting.
Available categories:
:error- Error events (critical priority, batch_size=1):check_in- Cron check-ins (high priority, batch_size=1):transaction- Performance transactions (medium priority, batch_size=1):log- Log events (accepted for backward compatibility, logs always use the TelemetryProcessor regardless of this setting)
Available since 12.0.0.
The default value is
[:error, :check_in, :transaction].:client_report_sender(atom/0) - The registered name of the process that accumulates discarded-event outcomes and flushes them to Sentry as client reports.Defaults to the globally-supervised
Sentry.ClientReport.Sender. Whentest_mode: trueis enabled,Sentry.Teststarts one sender per test and points this at it, so outcomes are attributed to the test that produced them and never outlive it.Available since 14.0.0.
The default value is
Sentry.ClientReport.Sender.:namespace({module(), atom()}) - A{module, function}tuple that resolves scoped configuration overrides. The function receives a config key and must return{:ok, value}to override the global value, or:defaultto fall back to the global configuration.The default resolver (
{Sentry.Config, :namespace}) always returns:default, meaning global configuration is used as-is.When
test_mode: trueis enabled, the SDK automatically uses{Sentry.Test.Config, :namespace}as the resolver to enable per-test configuration isolation viaSentry.Test.Config.put/1.The default value is
{Sentry.Config, :namespace}.:scrubber(keyword/0) - Configuration for how the SDK scrubs sensitive data out of captured events.Available since v13.2.0.
The default value is
[].:param_keys(list ofString.t/0) - Additional sensitive parameter keys, redacted wherever the SDK scrubs a map or a query string: request and query params, the request URL,Sentry.LiveViewHookbreadcrumb data, Oban job args, and maps captured into stacktrace frame variables.These terms extend
Sentry.Scrubber.default_param_keys/0; the default list cannot be shortened.Terms are matched as case-insensitive substrings of the key name, so
"ref"redacts"internal_ref"and"REF_ID"alike.This does not affect header scrubbing, which uses its own list — see
Sentry.Scrubber.default_header_keys/0and the:header_scrubberoption ofSentry.PlugContext.Available since 14.0.0.
The default value is
[].:conn_private_allow_list(list ofatom/0) - A list of keys that are retained in a%Plug.Conn{}'s:privatemap when a captured error embeds a connection (for example aPhoenix.ActionClauseErrorreported viaSentry.PlugCapture). All other:privatekeys are dropped.The
:privatemap can hold framework internals and sensitive data (such as the decoded session under:plug_session), so it is not safe to report wholesale. By default the SDK keeps only Phoenix's routing and render metadata — seeSentry.Scrubber.default_private_allow_list/0— which is high-signal for triaging which controller/action failed. Set this option to extend or replace that list.Available since v13.2.0.
The default value is
[:phoenix_controller, :phoenix_action, :phoenix_endpoint, :phoenix_router, :phoenix_view, :phoenix_layout, :phoenix_format, :phoenix_template, :phoenix_router_url, :phoenix_static_url].
Logs Options
These are the keys of the :logs option above.
:level(Logger.level/0ornil) - The minimum Logger level for log events sent to Sentry's Logs Protocol. Setting this is what enables structured logs: when it isnil(the default), no logs are sent to the Logs Protocol, regardless of the other keys here. The default value isnil.:excluded_domains(list ofatom/0) - Domains to exclude from logs sent to Sentry's Logs Protocol. This does not affect captured Sentry events; use:capture_excluded_domainsfor those. The default value is[].:metadata(list ofatom/0, or:all) - Logger metadata keys to include as attributes in log events sent to Sentry's Logs Protocol. If set to:all, all metadata will be included. This does not affect captured Sentry events; use:capture_metadatafor those. The default value is[].:capture_log_messages(boolean/0) - Setting this totrueis what enables reporting standalone log messages (such asLogger.error("oops")) to Sentry as captured events, in addition to crash reports. Crash reports are sent whether or not this option is enabled, so you do not need to turn it on to capture crashes. Both crashes and messages are gated by:capture_level. This mirrors the:capture_log_messagesoption ofSentry.LoggerHandler. Available since v13.3.0. The default value isfalse.:capture_level(Logger.level/0) - The minimum Logger level for captured Sentry events, including crashes. At the default:error, crashes (which are logged at:error) are reported; raising this above:errorsuppresses crashes too, mirroring the:leveloption ofSentry.LoggerHandler. When:capture_log_messagesistrue, this also gates which standaloneLoggermessages become captured events. This is independent of:level, which controls the level for structured logs sent to Sentry's Logs Protocol. Available since v13.3.0. The default value is:error.:capture_metadata(list ofatom/0, or:all) - Logger metadata keys to include in captured Sentry events from the auto-attached handler, added under:extraaslogger_metadata. If set to:all, all metadata will be included. This is independent of:metadata, which controls metadata for structured logs sent to Sentry's Logs Protocol. Available since v13.3.0. The default value is[].:capture_excluded_domains(list ofatom/0) - Domains to exclude from error events captured by the auto-attached handler. Defaults to[:cowboy]to avoid double-reporting events already captured bySentry.PlugCapture. This is independent of:excluded_domains, which controls structured logs sent to Sentry's Logs Protocol. Available since v13.3.0. The default value is[:cowboy].
Hook Options
These options control hooks that this SDK can call before or after sending events.
:before_send(before_send_event_callback/0) - Allows performing operations on the event before it is sent as well as filtering out the event altogether. If the callback returnsnilorfalse, the event is not reported. If it returns an updatedSentry.Event, then the updated event is used instead. If the callback crashes, the failure is logged at the:errorlevel and the event is not reported. See the Event Callbacks and Crashing Callbacks sections below for more information.:before_sendis available since v10.0.0. Before, it was called:before_send_event.:before_send_event(before_send_event_callback/0) - This option is deprecated. Use :before_send instead. Exactly the same as:before_send, but has been deprecated since v10.0.0.:after_send_event(after_send_event_callback/0) - Callback that is called after attempting to send an event. The result of the HTTP call as well as the event will be passed as arguments. The return value of the callback is not returned. If the callback crashes, the failure is logged at the:errorlevel and the caller still receives the result of the send. See the Event Callbacks and Crashing Callbacks sections below for more information.:before_send_log(before_send_log_callback/0) - Allows performing operations on a log event before it is sent, as well as filtering out the log event altogether. If the callback returnsnilorfalse, the log event is not reported. If it returns a (potentially-updated)Sentry.LogEvent, then the updated log event is used instead. If the callback crashes, the failure is logged at the:errorlevel and the log event is not reported. See the Crashing Callbacks section below for more information. Available since v12.0.0.:before_send_metric(before_send_metric_callback/0) - Allows performing operations on a metric before it is sent, as well as filtering out the metric altogether. If the callback returnsnilorfalse, the metric is not reported. If it returns a (potentially-updated)Sentry.Metric, then the updated metric is used instead. If the callback crashes, the failure is logged at the:errorlevel and the metric is not reported. See the Crashing Callbacks section below for more information. Available since v13.0.0.
Transport Options
These options control how this Sentry SDK sends events to the Sentry server.
:send_result(send_type/0) - Controls what to return when reporting exceptions to Sentry. The default value is:none.:client(module/0) - A module that implements theSentry.HTTPClientbehaviour. The default client uses Finch as the HTTP client; this changed from Hackney to Finch in v12.0.0. The default value isSentry.FinchClient.:send_max_attempts(pos_integer/0) - The maximum number of attempts to send an event to Sentry. The default value is4.:finch_pool_opts(keyword/0) - Pool options to be passed toFinch.start_link/1. These options control the connection pool behavior. Only applied if:clientis set toSentry.FinchClient. See Finch documentation for available options. The default value is[size: 50].:finch_request_opts(keyword/0) - Request options to be passed toFinch.request/4. These options control individual request behavior. Only applied if:clientis set toSentry.FinchClient. See Finch documentation for available options. The default value is[receive_timeout: 5000].:hackney_opts(keyword/0) - Deprecated: Use Finch as the default HTTP client instead.Options to be passed to
hackney. Only applied if:clientis set toSentry.HackneyClient.The default value is
[pool: :sentry_pool].:hackney_pool_timeout(timeout/0) - Deprecated: Use Finch as the default HTTP client instead.The maximum time to wait for a connection to become available. Only applied if
:clientis set toSentry.HackneyClient.The default value is
5000.:hackney_pool_max_connections(pos_integer/0) - Deprecated: Use Finch as the default HTTP client instead.The maximum number of connections to keep in the pool. Only applied if
:clientis set toSentry.HackneyClient.The default value is
50.:telemetry_buffer_capacities(%{category => pos_integer()}) - Overrides for the maximum number of items each telemetry buffer can hold. When a buffer reaches capacity, oldest items are dropped to make room. Default: error=100, check_in=100, transaction=1000, log=1000, metric=1000. Available since v12.0.0. The default value is%{}.:telemetry_scheduler_weights(%{priority => pos_integer()}) - Overrides for the weighted round-robin scheduler priority weights. Higher weights mean more sending slots for that priority level. Default: critical=5, high=4, medium=3, low=2. Available since v12.0.0. The default value is%{}.:transport_capacity(pos_integer/0) - Maximum number of items the transport queue can hold. For log envelopes, each log event counts as one item toward capacity. When the queue is full, the scheduler stops dequeuing from buffers until space becomes available. The transport queue processes one envelope at a time. Available since v12.0.0. The default value is1000.
Source Code Context Options
These options control how source code context is reported alongside events.
:enable_source_code_context(boolean/0) - Whether to report source code context alongside events. The default value isfalse.:root_source_code_paths(list ofPath.t/0) - A list of paths to the root of your application's source code. This is used to determine the relative path of files in stack traces. Usually, you'll want to set this to[File.cwd!()]. For umbrella apps, you should set this to all the application paths in your umbrella (such as[Path.join(File.cwd!(), "apps/app1"), ...]). Required if:enabled_source_code_contextistrue. The default value is[].:source_code_path_pattern(String.t/0) - A glob pattern used to determine which files to report source code context for. The glob "starts" from:root_source_code_paths. The default value is"**/*.ex".:source_code_exclude_patterns(list ofRegex.t/0orString.t/0) - A list of regular expressions used to determine which files to exclude from source code context. Each element can be either a compiledRegexor a string pattern that will be compiled to a regex at runtime.Using strings is required for OTP 28.0 compatibility, as compiled regexes cannot be serialized in release config files.
If you're on OTP 28.1 or later, you must use
/Emodifier in your regexps.:source_code_map_path(Path.t/0) - The path to the source code map file. Seemix sentry.package_source_code. Defaults to a private path inside Sentry'sprivdirectory. Available since v10.2.0.:context_lines(pos_integer/0) - The number of lines of source code before and after the line that caused the exception to report. The default value is3.:in_app_otp_apps(list ofatom/0) - A list of OTP application names that will be used to populate additional modules for the:in_app_module_allow_listoption. List your application (or the applications in your umbrella project) for them to show as "in-app" in stacktraces in Sentry. We recommend using this option over:in_app_module_allow_list, unless you need more control over the exact modules to consider as "in-app".Available since v10.9.0.
The default value is
[].:in_app_module_allow_list(list ofmodule/0) - A list of modules that is used to distinguish among stacktrace frames that belong to your app and ones that are part of libraries or core Elixir. This is used to better display the significant part of stacktraces. The logic is "greedy", so if your app's root module isMyAppand you configure this option to[MyApp],MyAppas well as any submodules (likeMyApp.Submodule) would be considered part of your app.Usually, the
:in_app_otp_appsoption should be preferred as it's simpler to work with.The default value is
[].
Configuration Through System Environment
Sentry supports loading some configuration from the system environment. The supported environment variables are:
SENTRY_RELEASE,SENTRY_ENVIRONMENT, andSENTRY_DSN. See the:release,:environment_name, and:dsnconfiguration options respectively for more information.
Filtering Exceptions
If you would like to prevent Sentry from sending certain exceptions, you can
use the :before_send configuration option. See the Event Callbacks
section below.
Before v9.0.0, the recommended way to filter out exceptions was to use a filter,
that is, a module implementing the Sentry.EventFilter behaviour. This is still supported,
but is now deprecated. See Sentry.EventFilter for more information.
If the configured filter cannot be called, or its Sentry.EventFilter.exclude_exception?/2
callback crashes, the exception is excluded and the failure is logged. See the
Crashing Callbacks section below.
Event Callbacks
You can configure the :before_send and :after_send_event options to
customize what happens before and/or after sending an event. The :before_send
callback must be of type before_send_event_callback/0 and the :after_send_event
callback must be of type after_send_event_callback/0. For example, you
can set:
config :sentry,
before_send: {MyModule, :before_send},
after_send_event: {MyModule, :after_send}MyModule could look like this:
defmodule MyModule do
@spec before_send(Sentry.Event.t()) :: Sentry.Event.t()
def before_send(event) do
metadata = Map.new(Logger.metadata())
%Sentry.Event{event | extra: Map.merge(event.extra, metadata)}
end
@spec after_send(Sentry.Event.t(), {:ok, String.t()} | {:error, any()}) :: any()
def after_send(event, result) do
case result do
{:ok, id} ->
Logger.info("Successfully sent event!")
{:error, _reason} ->
Logger.info(fn -> "Did not successfully send event! #{inspect(event)}" end)
end
end
endIf the before_send callback returns nil or false, the event is not reported.
Crashing Callbacks
Available since 14.0.0.
When a callback you configure raises, throws, or exits, Sentry catches the failure and logs
it at the :error level instead of letting it reach the code that was reporting the event
or serving the request. The log carries the :sentry logger domain, so the SDK never
reports its own callback failure as an event.
What happens next depends on where the callback runs.
Event Callbacks
If a :before_send, :after_send_event, :filter, :before_send_log,
:before_send_metric, or :traces_sampler callback fails, the item being handled is
dropped:
A
:before_sendcallback that crashes is treated like one that returnedfalse. The event or transaction is not sent, and the capture function returns:excluded.A
:filtermodule that cannot be called, or whoseSentry.EventFilter.exclude_exception?/2crashes, is treated like one that excluded the exception.capture_exception/2returns:excluded.A
:before_send_logor:before_send_metriccallback that crashes is treated like one that returnednil. The log event or metric is not sent, and the rest of the batch it belongs to is unaffected.
An :after_send_event callback runs once the event has already been sent and its
return value is ignored, so a crash there changes nothing the caller sees: the send
result is still the one the transport produced.
A :traces_sampler callback that crashes does not drop the trace outright. Sampling
falls back to the configured :traces_sample_rate, so the trace is kept or dropped at
the rate you configured. If :traces_sample_rate is not configured either, the trace is
dropped and the child spans of that trace inherit that decision instead of calling the
failing sampler again.
Request Callbacks
The callbacks that Sentry.PlugContext, Sentry.PlugCapture, and Sentry.LiveViewHook
accept run inside your request or LiveView process, where a failure of theirs would break
your application rather than just the report. It cannot: the request is served, and the
LiveView keeps running, exactly as they would have without Sentry. Sentry.PlugCapture
additionally re-raises your application's original exception unchanged, whatever fails
while it is capturing it.
Nothing is dropped either. The event is still reported, and only the field the failing callback was responsible for degrades:
| Callback | Value reported after a crash |
|---|---|
Sentry.PlugContext's :body_scrubber, :header_scrubber, :cookie_scrubber, or :url_scrubber | the SDK's own default scrubber for that field |
Sentry.PlugContext's :remote_address_reader | the address the SDK's default reader produces |
Sentry.PlugCapture's :scrubber | the connection scrubbed by Sentry.Scrubber.scrub/1 |
Sentry.LiveViewHook's :scrubber | redacted breadcrumb data, that is, an empty map |
A crashed scrubber reports more, not less
Apart from
Sentry.LiveViewHook, which redacts the data outright, falling back to the SDK's default scrubber means that data only your custom scrubber was dropping is sent to Sentry for as long as that scrubber keeps failing. The error-level log is the only signal, so alert on it rather than treating a custom scrubber as a guarantee.
Oban Callbacks
The callbacks the Oban integration accepts run inside :telemetry handlers, and
:telemetry permanently detaches a handler that fails. Sentry's two Oban handlers
therefore catch every failure in their own body, so a callback of yours that keeps failing
never stops later jobs from being reported or checked in.
No Oban item is dropped because one of these callbacks failed. The two that only return a decision fail open, and the three that customize an item fall back to what the SDK derived on its own:
| Callback | Behavior after a crash |
|---|---|
:should_report_error_callback | the job error is reported |
:should_report_error_check_in_callback | the failed check-in is reported |
:oban_tags_to_sentry_tags | the event carries the SDK's own Oban tags (oban_worker, oban_queue, and oban_state) and none of yours |
:monitor_slug_generator | the check-in uses the slug derived from the worker name |
Sentry.Integrations.Oban.Cron.sentry_check_in_configuration/1 | the check-in uses the slug and monitor config the integration inferred, with nothing merged in |
A crashing check-in customization sends the check-in elsewhere
A check-in whose
:monitor_slug_generatororsentry_check_in_configuration/1failed is still sent, but under the SDK's default slug rather than the one you configured. For as long as the callback keeps failing, the monitor you meant to check in to receives nothing and looks idle, while a monitor under the default slug receives the check-ins instead. The error-level log is the only signal.
If a failure happens elsewhere in one of the handlers, the check-in or error event it was
about to send is lost. That loss is counted in client reports under internal_sdk_error
rather than passing silently.
Reporting Source Code
Sentry supports reporting the source code of (and around) the line that caused an issue. An example configuration to enable this functionality is:
config :sentry,
dsn: "https://public:secret@app.getsentry.com/1",
enable_source_code_context: true,
root_source_code_paths: [File.cwd!()],
context_lines: 5To support this functionality, Sentry needs to package source code
and store it so that it's available in the compiled application. Packaging source
code is an active step you have to take; use the mix sentry.package_source_code Mix task to do that.
Sentry stores the packaged source code in its priv directory. This is included by
default in Mix releases. Once the source code is packaged
and ready to ship with your release, Sentry will load it when the :sentry application
starts. If there are issues with loading the packaged code, Sentry will log some warnings
but will boot up normally and it just won't report source code context.
Prune Large File Trees
Due to Sentry reading the file system and defaulting to a recursive search of directories, it is important to check your configuration and compilation environment to avoid a folder recursion issue. You might see problems when deploying to the root folder, so it is best to follow the practice of compiling your application in its own folder. Modifying the
:source_code_path_patternconfiguration option from its default is also an avenue to avoid compile problems, as well as pruning unnecessary files with:source_code_exclude_patterns.
Summary
Types
A callback to use with the :after_send_event configuration option.
A callback to use with the :before_send configuration option.
configuration options.k
A callback to use with the :before_send_log configuration option.
A callback to use with the :before_send_metric configuration option.
The strategy to use when sending an event to Sentry.
Functions
Captures a check-in built with the given options.
Parses and submits an exception to Sentry.
Reports a message to Sentry.
Flushes all pending events to Sentry.
Returns the currently-set Sentry DSN, if set (or nil otherwise).
Gets the last event ID sent to the server from the process dictionary. Since it uses the process dictionary, it will only return the last event ID sent within the current process.
Updates the value of key in the configuration at runtime.
Puts the last event ID sent to the server for the current process in the process dictionary.
Sends an event to Sentry.
Types
@type after_send_event_callback() :: (Sentry.Event.t(), result :: term() -> term()) | {module(), function_name :: atom()}
A callback to use with the :after_send_event configuration option.
If this is {module, function_name}, then module.function_name(event, result) will
be called, where event is of type Sentry.Event.t/0.
@type before_send_event_callback() :: (Sentry.Event.t() -> as_boolean(Sentry.Event.t())) | {module(), function_name :: atom()}
A callback to use with the :before_send configuration option.
configuration options.k
If this is {module, function_name}, then module.function_name(event) will
be called, where event is of type Sentry.Event.t/0.
See the Configuration section in the module documentation for more information on configuration.
@type before_send_log_callback() :: (Sentry.LogEvent.t() -> as_boolean(Sentry.LogEvent.t())) | {module(), function_name :: atom()}
A callback to use with the :before_send_log configuration option.
If this is {module, function_name}, then module.function_name(log_event) will
be called, where log_event is of type Sentry.LogEvent.t/0.
@type before_send_metric_callback() :: (Sentry.Metric.t() -> as_boolean(Sentry.Metric.t())) | {module(), function_name :: atom()}
A callback to use with the :before_send_metric configuration option.
If this is {module, function_name}, then module.function_name(metric) will
be called, where metric is of type Sentry.Metric.t/0.
@type send_result() :: {:ok, event_or_envelope_id :: String.t()} | {:error, Sentry.ClientError.t()} | :ignored | :unsampled | :excluded
@type send_type() :: :sync | :none
The strategy to use when sending an event to Sentry.
Functions
@spec capture_check_in(keyword()) :: {:ok, check_in_id :: String.t()} | :ignored | {:error, Sentry.ClientError.t()}
Captures a check-in built with the given options.
Check-ins are used to report the status of a monitor to Sentry. This is used to track the health and progress of cron jobs. This function is somewhat low level, and mostly useful when you want to report the status of a cron but you are not using any common library to manage your cron jobs.
This function buffers the check-in through the telemetry processor and returns
right away with {:ok, check_in_id}, where check_in_id is the ID of the
check-in. You can use this ID to send updates about the same check-in. Use
flush/1 if you need to block until buffered telemetry has been sent.
This requires :check_in to be listed in the :telemetry_processor_categories
configuration, which is the default. Without it, the check-in is sent with a
synchronous HTTP request instead, which returns {:error, reason} if it fails.
Setting the DSN
If the
:dsnconfiguration is not set, this function won't report the check-in to Sentry and will instead return:ignored. This behaviour is consistent with the rest of the SDK (such ascapture_exception/2).
Examples
Say you have a GenServer which periodically sends a message to itself to execute some job. You could monitor the health of this GenServer by reporting a check-in to Sentry.
For example:
@impl GenServer
def handle_info(:execute_periodic_job, state) do
# Report that the job started.
{:ok, check_in_id} = Sentry.capture_check_in(status: :in_progress, monitor_slug: "genserver-job")
:ok = do_job(state)
# Report that the job ended successfully.
Sentry.capture_check_in(check_in_id: check_in_id, status: :ok, monitor_slug: "genserver-job")
{:noreply, state}
end
@spec capture_exception( Exception.t(), keyword() ) :: send_result()
Parses and submits an exception to Sentry.
This only sends the exception if the :dsn configuration option is set
and is not nil. See the Configuration section
in the module documentation.
Options
:after_send_event(after_send_event_callback/0) - Same as the global:after_send_eventconfiguration, but applied only to this call. See the module documentation. Available since v10.0.0.:before_send(before_send_event_callback/0) - Same as the global:before_sendconfiguration, but applied only to this call. See the module documentation. Available since v10.0.0.:breadcrumbs(list ofkeyword/0orSentry.Context.breadcrumb/0) - List of breadcrumbs. This list gets prepended to the list in the context (seeSentry.Context.add_breadcrumb/1). The default value is[].:client(module/0) - Same as the global:clientconfiguration, but applied only to this call. See the module documentation. Available since v10.0.0.:event_source(atom/0) - The source of the event. This fills in the:sourcefield of the returned struct. This is not present by default.:extra(Sentry.Context.extra/0) - Map of extra context, which gets merged with the current context (seeSentry.Context.set_extra_context/1). If fields collide, the ones in the map passed through this option have precedence over the ones in the context. The default value is%{}.:fingerprint(list ofString.t/0) - List of the fingerprint for grouping this event. The default value is["{{ default }}"].:interpolation_parameters(list ofterm/0) - The parameters to use for message interpolation. This is only used if the:messageoption is present. This is not present by default. SeeSentry.capture_message/2. Available since v10.1.0.:level(t:level/0) - The level of the event. The default value is:error.:message(String.t/0) - A message to report. The string can contain interpolation markers (%s). In that case, you can pass the:interpolation_parametersoption as well to fill in those parameters. SeeSentry.capture_message/2for more information on message interpolation. Not present by default.:request(Sentry.Context.request_context/0) - Map of request context, which gets merged with the current context (seeSentry.Context.set_request_context/1). If fields collide, the ones in the map passed through this option have precedence over the ones in the context. The default value is%{}.:result- Allows specifying how the result should be returned. The possible values are::sync- Sentry will make an API call synchronously (including retries) and will return{:ok, event_id}if successful.:none- Sentry will send the event in the background, in a fire-and-forget fashion. The function will return{:ok, ""}regardless of whether the API call ends up being successful or not.
:sample_rate(float/0) - Same as the global:sample_rateconfiguration, but applied only to this call. See the module documentation. Available since v10.0.0.:stacktrace(Exception.stacktrace/0) - The exception's stacktrace. This can also be used with messages (:message). Not present by default.:tags(Sentry.Context.tags/0) - Map of tags context, which gets merged with the current context (seeSentry.Context.set_tags_context/1) and with the:tagsoption in the global Sentry configuration. If fields collide, the ones in the map passed through this option have precedence over the ones in the context, which have precedence over the ones in the configuration. The default value is%{}.:user(Sentry.Context.user_context/0) - Map of user context, which gets merged with the current context (seeSentry.Context.set_user_context/1). If fields collide, the ones in the map passed through this option have precedence over the ones in the context. The default value is%{}.
@spec capture_message( String.t(), keyword() ) :: send_result()
Reports a message to Sentry.
Options
:after_send_event(after_send_event_callback/0) - Same as the global:after_send_eventconfiguration, but applied only to this call. See the module documentation. Available since v10.0.0.:before_send(before_send_event_callback/0) - Same as the global:before_sendconfiguration, but applied only to this call. See the module documentation. Available since v10.0.0.:breadcrumbs(list ofkeyword/0orSentry.Context.breadcrumb/0) - List of breadcrumbs. This list gets prepended to the list in the context (seeSentry.Context.add_breadcrumb/1). The default value is[].:client(module/0) - Same as the global:clientconfiguration, but applied only to this call. See the module documentation. Available since v10.0.0.:event_source(atom/0) - The source of the event. This fills in the:sourcefield of the returned struct. This is not present by default.:exception(Exception.t/0) - This is the exception that gets reported in the:exceptionfield ofSentry.Event.t/0. The term passed here also ends up unchanged in the:original_exceptionfield ofSentry.Event.t/0. This option is required unless the:messageoption is present. Not present by default.:extra(Sentry.Context.extra/0) - Map of extra context, which gets merged with the current context (seeSentry.Context.set_extra_context/1). If fields collide, the ones in the map passed through this option have precedence over the ones in the context. The default value is%{}.:fingerprint(list ofString.t/0) - List of the fingerprint for grouping this event. The default value is["{{ default }}"].:interpolation_parameters(list ofterm/0) - The parameters to use for message interpolation. This is only used if the:messageoption is present. This is not present by default. SeeSentry.capture_message/2. Available since v10.1.0.:level(t:level/0) - The level of the event. The default value is:error.:request(Sentry.Context.request_context/0) - Map of request context, which gets merged with the current context (seeSentry.Context.set_request_context/1). If fields collide, the ones in the map passed through this option have precedence over the ones in the context. The default value is%{}.:result- Allows specifying how the result should be returned. The possible values are::sync- Sentry will make an API call synchronously (including retries) and will return{:ok, event_id}if successful.:none- Sentry will send the event in the background, in a fire-and-forget fashion. The function will return{:ok, ""}regardless of whether the API call ends up being successful or not.
:sample_rate(float/0) - Same as the global:sample_rateconfiguration, but applied only to this call. See the module documentation. Available since v10.0.0.:stacktrace(Exception.stacktrace/0) - The exception's stacktrace. This can also be used with messages (:message). Not present by default.:tags(Sentry.Context.tags/0) - Map of tags context, which gets merged with the current context (seeSentry.Context.set_tags_context/1) and with the:tagsoption in the global Sentry configuration. If fields collide, the ones in the map passed through this option have precedence over the ones in the context, which have precedence over the ones in the configuration. The default value is%{}.:user(Sentry.Context.user_context/0) - Map of user context, which gets merged with the current context (seeSentry.Context.set_user_context/1). If fields collide, the ones in the map passed through this option have precedence over the ones in the context. The default value is%{}.
Interpolation (since v10.1.0)
The message argument supports interpolation. You can pass a string with formatting
markers as %s, and then pass in the :interpolation_parameters option as a list
of positional parameters to interpolate. For example:
Sentry.capture_message("Error with user %s", interpolation_parameters: ["John"])This way, Sentry will group the messages based on the non-interpolated string, but it will show the interpolated string in the UI.
Missing or Extra Parameters
If the message string has more
%smarkers than parameters, the extra%smarkers are included as is and the SDK doesn't raise any error. If you pass in more interpolation parameters than%smarkers, the extra parameters are ignored as well. This is because the SDK doesn't want to be the cause of even more errors in your application when what you're trying to do is report an error in the first place.
@spec flush(keyword()) :: :ok
Flushes all pending events to Sentry.
This is a blocking call that drains all the buffers and waits for the scheduler to process all pending items. The SDK automatically calls this with the default timeout before stopping its supervision tree during graceful application shutdown.
Call it explicitly when you need to flush earlier or use a different timeout.
Options
:timeout- Maximum time to wait for flush to complete (default: 5000ms)
Examples
# Flush with default timeout
Sentry.flush()
# Flush with custom timeout
Sentry.flush(timeout: 10_000)
@spec get_dsn() :: String.t() | nil
Returns the currently-set Sentry DSN, if set (or nil otherwise).
This is useful in situations like capturing user feedback.
Gets the last event ID sent to the server from the process dictionary. Since it uses the process dictionary, it will only return the last event ID sent within the current process.
Updates the value of key in the configuration at runtime.
Once the :sentry application starts, it validates and caches the value of the
configuration options you start it with. Because of this, updating configuration
at runtime requires this function as opposed to just changing the application
environment.
This Function Is Slow
This function updates terms in
:persistent_term, which is what this SDK uses to cache configuration. Updating terms in:persistent_termis slow and can trigger full GC sweeps. We recommend only using this function in rare cases, or during tests.
Examples
For example, if you're using Bypass to test
that you send the correct events to Sentry:
test "reports the correct event to Sentry" do
bypass = Bypass.open()
Bypass.expect(...)
Sentry.put_config(:dsn, "http://public:secret@localhost:#{bypass.port}/1")
Sentry.put_config(:send_result, :sync)
my_function_to_test()
end
Puts the last event ID sent to the server for the current process in the process dictionary.
@spec send_event( Sentry.Event.t(), keyword() ) :: send_result()
Sends an event to Sentry.
An event is the most generic payload you can send to Sentry. It encapsulates
information about an exception, a message, or any other event that you want to
report. To manually build events, see the functions in Sentry.Event.
This function doesn't build the event for you, it only sends it. Most of the time,
you'll want to use capture_exception/2 or capture_message/2. To manually create events,
see Sentry.Event.create_event/1.
Options
:result- Allows specifying how the result should be returned. The possible values are::sync- Sentry will make an API call synchronously (including retries) and will return{:ok, event_id}if successful.:none- Sentry will send the event in the background, in a fire-and-forget fashion. The function will return{:ok, ""}regardless of whether the API call ends up being successful or not.
:client(module/0) - Same as the global:clientconfiguration, but applied only to this call. See the module documentation. Available since v10.0.0.:sample_rate(float/0) - Same as the global:sample_rateconfiguration, but applied only to this call. See the module documentation. Available since v10.0.0.:before_send(before_send_event_callback/0) - Same as the global:before_sendconfiguration, but applied only to this call. See the module documentation. Available since v10.0.0.:after_send_event(after_send_event_callback/0) - Same as the global:after_send_eventconfiguration, but applied only to this call. See the module documentation. Available since v10.0.0.
Async Send
Before v9.0.0 of this library, the
:resultoption also supported the:asyncvalue. This would spawn aTaskto make the API call, and would return a{:ok, Task.t()}tuple. You could useTaskoperations to wait for the result asynchronously. Since v9.0.0, this option is not present anymore. Instead, you can spawn a task yourself that then calls this function withresult: :sync. The effect is exactly the same.
Sending Exceptions and Messages
This function is low-level, and mostly intended for library developers, or folks that want to have full control on what they report to Sentry. For most use cases, use
capture_exception/2orcapture_message/2.