# Better Stack Ruby & Rails logging 

Where do you want to collect your Ruby logs from?

- [Rails application](#logging-from-rails)
- [Rack application](#logging-from-rack)
- [Ruby code](#logging-from-ruby)

## Logging from Rails

Collect logs from your Rails application, including your **Sidekiq jobs**. This integration also supports **Structured Events** in Rails 8.1 or higher for rich, queryable event logging.

### 1. Install

Install [Better Stack Rails Gem](https://github.com/logtail/logtail-ruby-rails):

```bash
[label Add Better Stack Rails Gem]
bundle add logtail-rails
```

### 2. Setup

Set up Better Stack Rails Gem in `config/application.rb`:

```ruby
[label config/application.rb]
module YourProject
  class Application < Rails::Application
    # ...
    # configuration of your project
    # ...

    config.logger = Logtail::Logger.create_default_logger(
      "$SOURCE_TOKEN",
      ingesting_host: "$INGESTING_HOST",
    )
  end
end
```

### 3. Start logging 🎉

Use Rails logger as usual:

```ruby
[label Send logs to Better Stack]
Rails.logger.error("Something bad happened.")
Rails.logger.warn("Log message with structured logging.", {
    item: "Orange Soda",
    price: 100.00
})

# Send a structured event (in Rails 8.1 or higher)
Rails.event.notify("user.signed_up", email: "user@example.com")
```

You should see your logs in [Better Stack Logs → Live tail](https://telemetry.betterstack.com/team/0/tail ";_blank").

Check out the [Ruby on Rails dashboard](https://telemetry.betterstack.com/team/0/dashboards/platform/ruby ";_blank").

[warning]
**Rails version 5.0 or higher is required.**  
Ruby version 2.5 or higher is required.  
[/warning]




## Logging from Rack

Collect logs from any Rack-based framework such as [Sinatra](https://sinatrarb.com), [Hanami](https://hanamirb.org), [Padrino](https://padrinorb.com), or [Roda](https://github.com/jeremyevans/roda).

### 1. Install

Install [Better Stack Rack Gem](https://github.com/logtail/logtail-ruby-rack):

```bash
[label Add Better Stack Rack Gem]
bundle add logtail-rack
```

### 2. Setup

Set up Better Stack Rack Gem in your `config.ru`:

```ruby
[label config.ru]
require 'logtail-rack'

# Initialization of logging middlewares (you don't have to use all)
use Logtail::Integrations::Rack::HTTPContext
use Logtail::Integrations::Rack::HTTPEvents
use Logtail::Integrations::Rack::ErrorEvent
use Logtail::Integrations::Rack::UserContext
use Logtail::Integrations::Rack::SessionContext

# Logger instance initialization
http_io_device = Logtail::LogDevices::HTTP.new(
  "$SOURCE_TOKEN",
  ingesting_host: "$INGESTING_HOST",
)
logger = Logtail::Logger.new(http_io_device)
Logtail::Config.instance.logger = logger

# Here is your application initialization
run ...
```

### 3. Start logging 🎉

Use the instantiated logger instance to send logs to Better Stack:

```ruby
[label Send logs to Better Stack]
logger = Logtail::Config.instance.logger

logger.info("I am using Better Stack! 🚀")

# You can also provide additional information when logging
logger.debug("Logging structured data...",
  name: {
    first: "John",
    last: "Smith"
  },
  id: 123456
)
```

You should see your logs in [Better Stack Logs → Live tail](https://telemetry.betterstack.com/team/0/tail ";_blank").


[warning]
**Rack version 1.2 or higher is required.**  
Ruby version 2.3 or higher is required.  
[/warning]




## Logging from Ruby

Collect logs from your Ruby code.

### 1. Install

Install [Better Stack Gem](https://github.com/logtail/logtail-ruby):

```bash
[label Add Better Stack Gem]
bundle add logtail
```

### 2. Setup

Set up Better Stack Ruby client:

```ruby
[label Create Better Stack logger]
require "logtail"

http_io_device = Logtail::LogDevices::HTTP.new(
  "$SOURCE_TOKEN",
  ingesting_host: "$INGESTING_HOST",
)
logger = Logtail::Logger.new(http_io_device)
```

### 3. Start logging 🎉

Use Ruby logger as usual:

```ruby
[label Send logs to Better Stack]
logger.error("Something bad happened.")
logger.warn("Log message with structured logging.", {
    item: "Orange Soda",
    price: 100.00
})

# Close logger to ensure that all logs are sent to Better Stack
logger.close
```

You should see your logs in [Better Stack → Live tail](https://telemetry.betterstack.com/team/0/tail ";_blank").

[warning]
**Ruby version 2.3.0 or higher is required.**  
[/warning]



## Need help?

Please let us know at hello@betterstack.com.  
We're happy to help! 🙏

## Example projects

You can take a look at example projects on Github:

- [Rails](https://github.com/logtail/logtail-ruby-rails)
- [Rack](https://github.com/logtail/logtail-ruby-rack)
- [Ruby](https://github.com/logtail/logtail-ruby)

## Additional information

Interested in learning more about **log levels** in Rails?  
Check out our [Intro guide to Ruby on Rails logging](https://betterstack.com/community/guides/logging/how-to-start-logging-with-ruby-on-rails/).

### Enrich log context

Add custom data to multiple log lines using `with` block:

[code-tabs]
```ruby
[label Rails]
Logtail.with_context(user: { id: 123 }) do
    Rails.logger.info('User logged in.')
    Rails.logger.info('User bought a gem.')
end
```
```ruby
[label Rack]
logger = Logtail::Config.instance.logger
Logtail.with_context(user: { id: 123 }) do
    logger.info('User logged in.')
    logger.info('User bought a gem.')
end
```
```ruby
[label Ruby]
Logtail.with_context(user: { id: 123 }) do
    logger.info('User logged in.')
    logger.info('User bought a gem.')
end
```
[/code-tabs]

### Filter sensitive information

In Rails or Rack, you can filter sensitive parameters and HTTP headers:

[code-tabs]
```ruby
[label Rails]
# config/initializers/filter_logging.rb
# Be sure to restart your server when you create this file.

# Configure parameters to be filtered from the log file.
# Use this to limit dissemination of sensitive information.
# See the ActiveSupport::ParameterFilter documentation for supported notations and behaviors.
Rails.application.config.filter_parameters += [
  :passw, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn
]

# Configure HTTP headers to be filtered from the log.
# Use this to limit dissemination of sensitive information.
Logtail::Integrations::Rack::HTTPEvents.http_header_filters = [
  :authorization, :proxy_authorization, :cookie
]
```
```ruby
[label Rack]
# config.ru
# Be sure to restart your server when you modify this file.

# Configure HTTP headers to be filtered from the log.
# Use this to limit dissemination of sensitive information.
Logtail::Integrations::Rack::HTTPEvents.http_header_filters = [
  :authorization, :proxy_authorization, :cookie
]
```
[/code-tabs]

### Filter logs sent to Better Stack

You can prevent logger from sending certain logs to Better Stack:

[code-tabs]
```ruby
[label Rails]
# in your config/application.rb
config.logtail.filter_sent_to_better_stack do |log_entry|
    log_entry.context_snapshot[:http][:path].start_with?('/_')
end
```
```ruby
[label Rack]
# in your config.ru
Logtail.config.filter_sent_to_better_stack do |log_entry|
    log_entry.message.include?("IGNORE")
end
```
```ruby
[label Ruby]
# anywhere before sending the logs
Logtail.config.filter_sent_to_better_stack do |log_entry|
    log_entry.message.include?("IGNORE")
end
```
[/code-tabs]

See `Logtail::LogEntry` for available attributes of the block parameter.

### Structured Events

Starting with Rails 8.1, you can use the new [Structured Events](https://rubyonrails.org/2025/8/15/this-week-in-rails-structured-event-reporting-lands-in-rails-b4395645) system to send structured data to Better Stack. The `logtail-rails` gem automatically subscribes to these events and logs them as structured log entries in case you've used `Logtail::Logger.create_default_logger` to initialize.

This is particularly useful for tracking key business events or application-specific actions with rich, queryable data, without having to format them into a log message.

[code-tabs]
```ruby
[label Using events]
# Notify about a simple event with a payload
Rails.event.notify("user.signed_up",  email: "user@example.com")

# You can add context that will be included in all subsequent events
Rails.event.set_context(request_id: "abc-123", shop_id: 456)

# Tag specific events for easier filtering
Rails.event.tagged("api", "billing") do
    Rails.event.notify("payment.processed", amount: 9.99, currency: "USD")
end
```
```ruby
[label Configuring the event subscription]
# If you haven't used Logtail::Logger.create_default_logger
# the logger needs to be subscribed manually to the events
Rails.event.subscribe(
  Logtail::Integrations::Rails::EventLogSubscriber.new(logger)
)

# The event subscriber can have the log level changed
Logtail::Integrations::Rails::EventLogSubscriber.log_level = :debug

# The event subscriber can be disabled
Logtail::Integrations::Rails::EventLogSubscriber.enabled = false
```
[/code-tabs]

When you use `Rails.event.notify`, the `logtail-rails` gem captures the event name, payload, context, tags, and source location, and sends it all as a structured log to Better Stack.