Sha256: 00d474d3c76348b924d7076d90c5370862726828ab15930c96a07bce5ae72f30

Contents?: true

Size: 1.46 KB

Versions: 4

Compression:

Stored size: 1.46 KB

Contents

module Startback
  module Support
    class LogFormatter

      DEFAULT_OPTIONS = {
        pretty_print: nil
      }

      def initialize(options = {})
        @options = DEFAULT_OPTIONS.merge(options)
        @options[:pretty_print] = auto_pretty_print unless @options.has_key?(:pretty_print)
      end

      def pretty_print?
        !!@options[:pretty_print]
      end

      def call(severity, time, progname, msg)
        msg = { message: msg } if msg.is_a?(String)
        msg = { error: msg } if msg.is_a?(Exception)
        data = {
          severity: severity,
          time: time
        }.merge(msg)
         .merge(error: error_to_json(msg[:error], severity))
         .compact
        if pretty_print?
          JSON.pretty_generate(data) << "\n"
        else
          data.to_json << "\n"
        end
      end

      def error_to_json(error, severity = nil)
        return error if error.nil?
        return error if error.is_a?(String)
        return error.to_s unless error.is_a?(Exception)

        backtrace = error.backtrace[0..25] if severity == "FATAL"
        causes = error.causes.map{|c| error_to_json(c) } if error.respond_to?(:causes)
        causes = nil if causes && causes.empty?
        {
          message: error.message,
          backtrace: backtrace,
          causes: causes
        }.compact
      end

    private

      def auto_pretty_print
        development?
      end

    end # class LogFormatter
  end # module Support
end # module Startback

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
startback-1.0.0 lib/startback/support/log_formatter.rb
startback-0.19.4 lib/startback/support/log_formatter.rb
startback-0.19.3 lib/startback/support/log_formatter.rb
startback-0.19.1 lib/startback/support/log_formatter.rb