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:

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_environments option (a list of environments to report events for). This was used together with the :environment_name option to determine whether to send events. :included_environments is 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")
end

In 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 :dsn configuration 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/0 or nil) - The DSN for your Sentry project. If this is not set, Sentry will not be enabled. If the SENTRY_DSN environment variable is set, it will be used as the default value. The default value is nil.

  • :environment_name (String.t/0 or atom/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 the SENTRY_ENVIRONMENT environment 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 between 0.0 and 1.0 (inclusive). A value of 0.0 means no transactions will be sampled, while 1.0 means 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/0 or nil) - 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 between 0.0 and 1.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_sampler and :traces_sample_rate are configured, :traces_sampler takes precedence.

    If the callback crashes, the failure is logged at the :error level and sampling falls back to :traces_sample_rate. When :traces_sample_rate is 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.0 and 1.0, the invalid sample rate is logged at the :warning level 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
    end

    This 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 of integer/0 or Range.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_processor reason. Outgoing requests are not affected.

    Available since 14.0.0.

    The default value is [404].

  • :included_environments (list of atom/0 or String.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_name needs 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/0 or nil) - The release version of your application. This is used to correlate events with source code. If the SENTRY_RELEASE environment variable is set, it will be used as the default value. The default value is nil.

  • :json_library (module/0) - A module that implements the "standard" Elixir JSON behaviour, that is, exports the encode/1 and decode/1 functions.

    Defaults to Jason if the JSON kernel 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 to Jason, but you will have to add :jason as 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 is true.

  • :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 of 0.0 will deny sending any events, and a value of 1.0 will send 100% of events. Sampling is applied after the :before_send callback. See where the Sentry documentation suggests this. Must be between 0.0 and 1.0 (included). The default value is 1.0.

  • :tags (map of term/0 keys and term/0 values) - 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. See Sentry.Context.add_breadcrumb/1. The default value is 100.

  • :max_stacktrace_arg_length (non_neg_integer/0) - The maximum length (in Unicode graphemes) of each inspected function argument reported in the vars of 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 is 10000.

  • :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 :sentry application starts. The default value is true.

  • :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 :debug level.

    All messages logged by the SDK itself carry domain: [:sentry], so you can filter them out through Logger's metadata filters.

    The default value is :warning.

  • :filter (module/0) - A module that implements the Sentry.EventFilter behaviour. Defaults to Sentry.DefaultEventFilter. If the module cannot be called, or its callback crashes, the failure is logged at the :error level and the exception is excluded. See the Filtering Exceptions section below. The default value is Sentry.DefaultEventFilter.

  • :dedup_events (boolean/0) - Whether to deduplicate events before reporting them to Sentry. If this option is true, 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 is true.

  • :test_mode (boolean/0) - Whether to enable test mode.

    When test_mode: true is set, the SDK automatically activates per-test configuration isolation and ensures the test registry is started at application boot. See Sentry.Test for 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 the monitor_config when reporting cron jobs with one of the integrations. This supports all the keys defined in the Sentry documentation. See also Sentry.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 is false.

      • :oban_tags_to_sentry_tags (t:oban_tags_to_sentry_tags_function/0 or nil) - A function that determines the Sentry tags to be added based on the Oban job. This function receives an Oban.Job struct 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)
        end

        This example transforms all Oban job tags into Sentry tags prefixed with oban_tags. and with a value of true. Available since 12.0.0.

        If the function crashes, the failure is logged at the :error level and the event is still reported, carrying only the tags the integration adds itself (oban_worker, oban_queue, and oban_state). A return value that is not a map is logged at the :warning level 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()) or nil) - A function that determines whether to report errors for Oban jobs. The function receives the worker module and the Oban.Job struct and should return true to report the error or false to skip reporting.

        should_report_error_callback: fn _worker, job ->
          job.attempt >= job.max_attempts
        end

        This example only reports errors on final retry attempts. Available since 12.0.0.

        If the function crashes, the failure is logged at the :error level and the error is reported, as if the function had returned true. 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 is false.

        • :monitor_slug_generator ({module(), atom()}) - A {module, function} tuple that generates a monitor name based on the Oban.Job struct. The function is called with the Oban.Job as 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 :error level 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()) or nil) - A function that determines whether to report a failed check-in for an Oban cron job. The function receives the worker module and the Oban.Job struct and should return true to report the failed check-in or false to skip it.

          should_report_error_check_in_callback: fn _worker, job ->
            job.attempt >= job.max_attempts
          end

          This 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 :error level and the failed check-in is reported, as if the function had returned true. 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.

      • :cron (keyword/0) - Configuration options for configuring crons for Quantum.
        • :enabled (boolean/0) - Whether to enable the Quantum integration. When enabled, the Sentry SDK will capture check-ins for Quantum jobs. Available since v10.2.0. The default value is false.
    • :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 is false.
  • :logs (keyword/0 or nil) - Configuration for the logger handler that the SDK attaches automatically at startup. When this is nil (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 :level and further configured by :excluded_domains and :metadata.

    • Logger messages reported as captured Sentry events, enabled by setting :capture_log_messages to true and 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/0 or nil) - An explicit organization ID for trace continuation validation. If not set, the SDK will extract it from the DSN host (e.g., o1234 from o1234.ingest.sentry.io gives "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 is nil.

  • :strict_trace_continuation (boolean/0) - When true, both the SDK's org ID and the incoming baggage sentry-org_id must 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. When false (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 is false.

  • :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. When test_mode: true is enabled, Sentry.Test starts 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 :default to 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: true is enabled, the SDK automatically uses {Sentry.Test.Config, :namespace} as the resolver to enable per-test configuration isolation via Sentry.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 of String.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.LiveViewHook breadcrumb 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/0 and the :header_scrubber option of Sentry.PlugContext.

      Available since 14.0.0.

      The default value is [].

    • :conn_private_allow_list (list of atom/0) - A list of keys that are retained in a %Plug.Conn{}'s :private map when a captured error embeds a connection (for example a Phoenix.ActionClauseError reported via Sentry.PlugCapture). All other :private keys are dropped.

      The :private map 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 — see Sentry.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/0 or nil) - The minimum Logger level for log events sent to Sentry's Logs Protocol. Setting this is what enables structured logs: when it is nil (the default), no logs are sent to the Logs Protocol, regardless of the other keys here. The default value is nil.

  • :excluded_domains (list of atom/0) - Domains to exclude from logs sent to Sentry's Logs Protocol. This does not affect captured Sentry events; use :capture_excluded_domains for those. The default value is [].

  • :metadata (list of atom/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_metadata for those. The default value is [].

  • :capture_log_messages (boolean/0) - Setting this to true is what enables reporting standalone log messages (such as Logger.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_messages option of Sentry.LoggerHandler. Available since v13.3.0. The default value is false.

  • :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 :error suppresses crashes too, mirroring the :level option of Sentry.LoggerHandler. When :capture_log_messages is true, this also gates which standalone Logger messages 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 of atom/0, or :all) - Logger metadata keys to include in captured Sentry events from the auto-attached handler, added under :extra as logger_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 of atom/0) - Domains to exclude from error events captured by the auto-attached handler. Defaults to [:cowboy] to avoid double-reporting events already captured by Sentry.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 returns nil or false, the event is not reported. If it returns an updated Sentry.Event, then the updated event is used instead. If the callback crashes, the failure is logged at the :error level and the event is not reported. See the Event Callbacks and Crashing Callbacks sections below for more information.

    :before_send is 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 :error level 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 returns nil or false, 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 :error level 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 returns nil or false, 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 :error level 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 the Sentry.HTTPClient behaviour. The default client uses Finch as the HTTP client; this changed from Hackney to Finch in v12.0.0. The default value is Sentry.FinchClient.

  • :send_max_attempts (pos_integer/0) - The maximum number of attempts to send an event to Sentry. The default value is 4.

  • :finch_pool_opts (keyword/0) - Pool options to be passed to Finch.start_link/1. These options control the connection pool behavior. Only applied if :client is set to Sentry.FinchClient. See Finch documentation for available options. The default value is [size: 50].

  • :finch_request_opts (keyword/0) - Request options to be passed to Finch.request/4. These options control individual request behavior. Only applied if :client is set to Sentry.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 :client is set to Sentry.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 :client is set to Sentry.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 :client is set to Sentry.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 is 1000.

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 is false.

  • :root_source_code_paths (list of Path.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_context is true. 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 of Regex.t/0 or String.t/0) - A list of regular expressions used to determine which files to exclude from source code context. Each element can be either a compiled Regex or 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 /E modifier in your regexps.

  • :source_code_map_path (Path.t/0) - The path to the source code map file. See mix sentry.package_source_code. Defaults to a private path inside Sentry's priv directory. 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 is 3.

  • :in_app_otp_apps (list of atom/0) - A list of OTP application names that will be used to populate additional modules for the :in_app_module_allow_list option. 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 of module/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 is MyApp and you configure this option to [MyApp], MyApp as well as any submodules (like MyApp.Submodule) would be considered part of your app.

    Usually, the :in_app_otp_apps option 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, and SENTRY_DSN. See the :release, :environment_name, and :dsn configuration 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
end

If 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_send callback that crashes is treated like one that returned false. The event or transaction is not sent, and the capture function returns :excluded.

  • A :filter module that cannot be called, or whose Sentry.EventFilter.exclude_exception?/2 crashes, is treated like one that excluded the exception. capture_exception/2 returns :excluded.

  • A :before_send_log or :before_send_metric callback that crashes is treated like one that returned nil. 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:

CallbackValue reported after a crash
Sentry.PlugContext's :body_scrubber, :header_scrubber, :cookie_scrubber, or :url_scrubberthe SDK's own default scrubber for that field
Sentry.PlugContext's :remote_address_readerthe address the SDK's default reader produces
Sentry.PlugCapture's :scrubberthe connection scrubbed by Sentry.Scrubber.scrub/1
Sentry.LiveViewHook's :scrubberredacted 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:

CallbackBehavior after a crash
:should_report_error_callbackthe job error is reported
:should_report_error_check_in_callbackthe failed check-in is reported
:oban_tags_to_sentry_tagsthe event carries the SDK's own Oban tags (oban_worker, oban_queue, and oban_state) and none of yours
:monitor_slug_generatorthe check-in uses the slug derived from the worker name
Sentry.Integrations.Oban.Cron.sentry_check_in_configuration/1the 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_generator or sentry_check_in_configuration/1 failed 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: 5

To 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_pattern configuration 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

Link to this type

after_send_event_callback()

View Source (since 9.0.0)
@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.

Link to this type

before_send_event_callback()

View Source (since 9.0.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.

Link to this type

before_send_log_callback()

View Source (since 12.0.0)
@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.

Link to this type

before_send_metric_callback()

View Source (since 13.0.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
Link to this type

send_type()

View Source (since 9.0.0)
@type send_type() :: :sync | :none

The strategy to use when sending an event to Sentry.

Functions

Link to this function

capture_check_in(options)

View Source (since 10.2.0)
@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 :dsn configuration 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 as capture_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
Link to this function

capture_exception(exception, options \\ [])

View Source
@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_event configuration, 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_send configuration, but applied only to this call. See the module documentation. Available since v10.0.0.

  • :breadcrumbs (list of keyword/0 or Sentry.Context.breadcrumb/0) - List of breadcrumbs. This list gets prepended to the list in the context (see Sentry.Context.add_breadcrumb/1). The default value is [].

  • :client (module/0) - Same as the global :client configuration, 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 :source field 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 (see Sentry.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 of String.t/0) - List of the fingerprint for grouping this event. The default value is ["{{ default }}"].

  • :interpolation_parameters (list of term/0) - The parameters to use for message interpolation. This is only used if the :message option is present. This is not present by default. See Sentry.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_parameters option as well to fill in those parameters. See Sentry.capture_message/2 for 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 (see Sentry.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_rate configuration, 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 (see Sentry.Context.set_tags_context/1) and with the :tags option 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 (see Sentry.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 %{}.

Link to this function

capture_message(message, opts \\ [])

View Source
@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_event configuration, 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_send configuration, but applied only to this call. See the module documentation. Available since v10.0.0.

  • :breadcrumbs (list of keyword/0 or Sentry.Context.breadcrumb/0) - List of breadcrumbs. This list gets prepended to the list in the context (see Sentry.Context.add_breadcrumb/1). The default value is [].

  • :client (module/0) - Same as the global :client configuration, 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 :source field of the returned struct. This is not present by default.

  • :exception (Exception.t/0) - This is the exception that gets reported in the :exception field of Sentry.Event.t/0. The term passed here also ends up unchanged in the :original_exception field of Sentry.Event.t/0. This option is required unless the :message option is present. Not present by default.

  • :extra (Sentry.Context.extra/0) - Map of extra context, which gets merged with the current context (see Sentry.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 of String.t/0) - List of the fingerprint for grouping this event. The default value is ["{{ default }}"].

  • :interpolation_parameters (list of term/0) - The parameters to use for message interpolation. This is only used if the :message option is present. This is not present by default. See Sentry.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 (see Sentry.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_rate configuration, 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 (see Sentry.Context.set_tags_context/1) and with the :tags option 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 (see Sentry.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 %s markers than parameters, the extra %s markers are included as is and the SDK doesn't raise any error. If you pass in more interpolation parameters than %s markers, 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.

Link to this function

flush(opts \\ [])

View Source (since 12.0.0)
@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)
Link to this function

get_dsn()

View Source (since 10.6.0)
@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.

Link to this function

get_last_event_id_and_source()

View Source
@spec get_last_event_id_and_source() :: {String.t(), atom() | nil} | nil

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.

Link to this function

put_config(key, value)

View Source (since 10.0.0)
@spec put_config(atom(), term()) :: :ok

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_term is 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
Link to this function

put_last_event_id_and_source(event_id, source \\ nil)

View Source

Puts the last event ID sent to the server for the current process in the process dictionary.

Link to this function

send_event(event, options \\ [])

View Source
@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 :client configuration, but applied only to this call. See the module documentation. Available since v10.0.0.

  • :sample_rate (float/0) - Same as the global :sample_rate configuration, 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_send configuration, 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_event configuration, 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 :result option also supported the :async value. This would spawn a Task to make the API call, and would return a {:ok, Task.t()} tuple. You could use Task operations 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 with result: :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/2 or capture_message/2.

Link to this function

send_transaction(transaction, options \\ [])

View Source