Documentation forSolarWinds Observability SaaS

Ingest logs from Ruby on Rails or Ruby (Papertrail)

You can ship Ruby on Rails or Ruby (without Rails) application logs directly to SolarWinds Papertrail over HTTPS:

The Rails setup adds one initializer, which adds a second logger to Rails.logger. Rails keeps writing its log as before, and every record is also sent to Papertrail.

Each log record does the following:

  • Shows the correct System, Program, and Severity in the Logs Explorer.
  • Keeps the plain-text log line from Rails, with the request ID in front.
  • Arrives as a single event, even when it spans several lines, such as the Rails exception report with its backtrace.
  • Is sent in batches over port 443 from a background thread and also from every Puma worker process.

To get a destination and token in Papertrail, add a new log destination. The ingestion token is generated along with the destination. Use the collector endpoints for your account's region:

  • HTTPS: https://logs.collector.<REGION>.cloud.solarwinds.com/v1/logs/bulk

Replace <REGION> with the data center your organization uses: na-01, eu-01, or ap-01.

Each record is prefixed with its length in bytes (octet-counted framing). Line breaks inside a message do not split the message into several events.

Ruby on Rails - HTTPS

Requirements

  • Ruby 3.2 or later

  • Rails 7.1 or later (Rails.logger.broadcast_to)

  • Outbound HTTPS (port 443) to logs.collector.<REGION>.cloud.solarwinds.com

    Replace <REGION> with the data center your organization uses: na-01, eu-01, or ap-01.

No gems are needed.

Step 1: Add the initializer

Create config/initializers/swo_logger.rb:

require "json"
require "logger"
require "net/http"
require "socket"

# Sends Ruby Logger / Rails.logger records to SolarWinds Observability Logs (Papertrail) as RFC 5424
# syslog messages over HTTPS: every record keeps its own Severity, System and Program, and multi-line
# messages (backtraces) stay one event. A background thread posts a batch every second.

class SwoLogger < Logger
  SEVERITY = { "DEBUG" => 7, "INFO" => 6, "WARN" => 4, "ERROR" => 3, "FATAL" => 2, "ANY" => 1 }.freeze

  def initialize(token:, region:, app_name:, msgid: "-", level: DEBUG, tags_from: nil)
    super(Device.new("https://logs.collector.#{region}.cloud.solarwinds.com/v1/logs/bulk", token), level: level)
    host, app, msgid = [Socket.gethostname, app_name, msgid].map { |v| v.to_s.gsub(/[^!-~]/, "-") } # no spaces in the header
    app = app[0, 48]
    self.formatter = proc do |severity, time, _progname, msg|
      text = case msg
             when String    then msg
             when Exception then "#{msg.message} (#{msg.class})\n#{Array(msg.backtrace).join("\n")}"
             when Hash      then msg.transform_keys(&:to_s).then { |h| [h.delete("msg"), (h.to_json unless h.empty?)].compact.join(" ") }
             else msg.inspect
             end
      text = text.sub(/\A[ \t]*\n/, "") # Rails' exception report starts with an empty line

      tags = tags_from ? tags_from.current_tags : []
      text = "[#{tags.join('] [')}] #{text}" unless tags.empty? || text.start_with?("[#{tags.first}]")
      "<#{8 + SEVERITY.fetch(severity, 5)}>1 #{time.utc.strftime('%FT%T.%6NZ')} #{host} #{app} #{Process.pid} #{msgid} - #{text.rstrip}"
    end
  end

  class Device
    def initialize(url, token)
      @uri, @token = URI(url), token
      at_exit { close }
    end

    def write(message)
      start unless @pid == Process.pid # first write, or first write after a fork (Puma, Unicorn)

      @queue << "#{message.bytesize} #{message}".b if @queue.size < 10_000
    rescue ClosedQueueError
      nil
    end

    def close
      return unless @pid == Process.pid

      @queue.close
      @thread.join(12)
    end

    def reopen(_log = nil) = self

    private

    def start
      @queue, @pid = Thread::Queue.new, Process.pid
      @thread = Thread.new do
        batch, sent = String.new, now
        loop do
          frame = @queue.pop(timeout: 1)
          batch = post(batch) if frame && batch.bytesize + frame.bytesize > 4_000_000 # requests stay below 5 MiB

          batch << frame if frame
          batch, sent = post(batch), now if !batch.empty? && (frame.nil? || now - sent >= 1)
          break if frame.nil? && @queue.closed?
        end
      end
    end

    # Retries network errors and 5xx (not on exit); prints why a batch was not delivered. Returns an empty batch.

    def post(body)
      problem = nil
      (@queue.closed? ? 1 : 3).times do |attempt|
        sleep(attempt)
        res = Net::HTTP.start(@uri.host, @uri.port, use_ssl: @uri.scheme == "https", open_timeout: 5, read_timeout: 10) do |http|
          http.post(@uri.path, body, "Authorization" => "Bearer #{@token}", "Content-Type" => "application/syslog-frames")
        end
        return String.new if res.code == "202"

        problem = "HTTP #{res.code}"
        break if res.code.to_i < 500 # 401: wrong token or region

      rescue StandardError => e
        problem = "#{e.class}: #{e.message}"
      end
      warn "SWO log delivery failed: #{problem}"
      String.new
    end

    def now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  end
end

# Rails 7.1+: also send every Rails.logger record to Papertrail. Does nothing while SWO_TOKEN is not set.

if ENV["SWO_TOKEN"].present?
  SwoLogger.include(ActiveSupport::LoggerSilence) # honor Rails.logger.silence { ... }

  Rails.logger.broadcast_to(SwoLogger.new(
    token:     ENV["SWO_TOKEN"],
    region:    ENV["SWO_REGION"],
    app_name:  ENV.fetch("SWO_APP_NAME") { Rails.application.class.module_parent_name.underscore.dasherize },
    msgid:     Rails.env,
    level:     Rails.logger.level,
    tags_from: Rails.logger.formatter # request IDs; do not wrap SwoLogger in ActiveSupport::TaggedLogging

  ))
end

Notes:

  • Nothing is sent while SWO_TOKEN is not set. You can commit the file and set the token only where logs should be sent, usually in production.

  • The Papertrail logger uses the level Rails.logger has at boot (config.log_level). In production, this is info by default or RAILS_LOG_LEVEL.

  • Request tags from config.log_tags (by default, the request ID) and Rails.logger.tagged("...") { ... } blocks are included. Records written with the block-less form Rails.logger.tagged("...").info(...) are sent to the Rails log only.

  • Rails.logger.silence { ... } also applies to the records sent to Papertrail.

  • Do not wrap SwoLogger in ActiveSupport::TaggedLogging. With two tagged loggers in the broadcast, Rails runs every tagged { ... } block once per logger. (On Rails 7.1, that includes every request.)

  • While the collector is unreachable, at most 10,000 records wait in memory. Newer records are dropped.

Step 2: Set the environment variables

Set the following variables in the environment where your application runs:

SWO_TOKEN=<TOKEN>
SWO_REGION=<REGION>
# optional: SWO_APP_NAME=my-shop

Notes:

  • SWO_APP_NAME becomes the Program. By default, the application module name is used.

  • Keep the token out of source control. Use your container environment, platform config (Kamal, Heroku, Render), or a git-ignored .env file.

Step 3: Verify

Run the following where SWO_TOKEN and SWO_REGION are set. (For production, add RAILS_ENV=production.)

bin/rails runner 'm = "swo-setup-check-#{Time.now.utc.strftime("%Y%m%d%H%M%S")}"; Rails.logger.info(msg: "Hello from Rails #{m}", order_id: 1234); begin; raise "Payment failed #{m}"; rescue => e; Rails.logger.error(e); end; puts "marker: #{m}"'

In the Logs Explorer, search for the printed marker. The System column shows your server's host name, Program shows your application name, and the error appears as one event with the full backtrace.

What arrives in the Logs Explorer

The following searchable attributes are extracted from each event:

Attribute Value
syslog.host, syslog.appname System and Program
syslog.msgid Rails environment (for example, production)
syslog.procId Ruby process ID
json.* Each field of a hash message (for example, json.order_id:1234)

Troubleshooting

Symptom Likely cause What to do
SWO log delivery failed: HTTP 401 on standard error Wrong token, or the token belongs to a different region Copy the token again from the log destination and check SWO_REGION.
SWO log delivery failed: SocketError ... getaddrinfo or Net::OpenTimeout SWO_REGION contains an invalid value, or outbound 443 is blocked Use your account's region (na-01, eu-01, or ap-01); check the firewall or proxy.
No logs arrive and nothing is printed SWO_TOKEN is not set in the process that runs the app, so the initializer does nothing Check with bin/rails runner 'p ENV.key?("SWO_TOKEN")' in that environment.
Debug records are missing The Papertrail logger uses Rails.logger's level Set RAILS_LOG_LEVEL=debug or config.log_level.
Program shows the wrong name The default comes from the application module name Set SWO_APP_NAME.

Ruby (without Rails) - HTTPS

To send application logs from Ruby programs without Rails, you must be on Ruby 3.2 or later with outbound HTTPS on port 443.

Save the initializer code from Step 1 above as swo_logger.rb. Omit the last block, beginning from the comment # Rails 7.1+: also send every Rails.logger record. Then create the logger, and use it like any Ruby Logger. Replace my-service with your application name.

require_relative "swo_logger"

logger = SwoLogger.new(token: ENV.fetch("SWO_TOKEN"), region: ENV.fetch("SWO_REGION"), app_name: "my-service")
logger.info("Order processed")
logger.info({ msg: "Order processed", order_id: 1234 })
begin
  # application code

rescue => e
  logger.error(e) # message, class and backtrace in one event

end

Notes

  • The default level is DEBUG. Pass level: Logger::INFO to send less.

  • The last batch is sent when the program exits normally. It is lost if the process is killed with SIGKILL or exits with exit!.

Fallback: Forward via a syslog daemon

If your application cannot connect directly to the Papertrail collector — for example, a strict outbound firewall blocks port 443 — write logs to a local file and use the host's syslog daemon to forward them to Papertrail over TLS. SolarWinds Observability supports rsyslog on Linux and NXlog on Windows for this purpose. See Send Logs using syslog for configuration instructions.

The scripts are not supported under any SolarWinds support program or service. The scripts are provided AS IS without warranty of any kind. SolarWinds further disclaims all warranties including, without limitation, any implied warranties of merchantability or of fitness for a particular purpose. The risk arising out of the use or performance of the scripts and documentation stays with you. In no event shall SolarWinds or anyone else involved in the creation, production, or delivery of the scripts be liable for any damages whatsoever (including, without limitation, damages for loss of business profits, business interruption, loss of business information, or other pecuniary loss) arising out of the use of or inability to use the scripts or documentation.