Sha256: 533e7ca9047db61f11449e89ac74f0a00176e1f365fffb0ab12983a013a90b3a

Contents?: true

Size: 1.12 KB

Versions: 2

Compression:

Stored size: 1.12 KB

Contents

require 'oj'

module Semlogr
  module Formatters
    class JsonFormatter
      def initialize(opts = {})
        default_opts = {
          mode: :custom,
          time_format: :ruby,
          use_to_json: true
        }

        @opts = default_opts.merge(opts)
      end

      def format(log_event)
        event = {
          timestamp: log_event.timestamp.iso8601(3),
          severity: log_event.severity.to_s,
          message_template: log_event.template.text,
          message: log_event.to_s
        }

        add_error(event, log_event.error)
        add_properties(event, log_event.properties)

        event = yield(event) if block_given?
        event_json = Oj.dump(event, @opts)
        "#{event_json}\n"
      end

      private

      def add_error(event, error)
        return unless error

        backtrace = error.backtrace || []
        event[:error] = {
          type: error.class,
          message: error.message,
          backtrace: backtrace
        }
      end

      def add_properties(event, properties)
        return unless properties.any?

        event[:properties] = properties
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
semlogr-0.2.2 lib/semlogr/formatters/json_formatter.rb
semlogr-0.2.1 lib/semlogr/formatters/json_formatter.rb