Sha256: f51ca073a043e270c73b4ccfbc9f4019c9adecd85cc5f12e21e5fb88c0b8b306

Contents?: true

Size: 1.89 KB

Versions: 1

Compression:

Stored size: 1.89 KB

Contents

module Logster
  class Message
    LOGSTER_ENV = "_logster_env".freeze
    ALLOWED_ENV = %w{
      HTTP_HOST
      REQUEST_URI
      REQUEST_METHOD
      HTTP_USER_AGENT
      HTTP_ACCEPT
      HTTP_REFERER
      HTTP_X_FORWARDED_FOR
      HTTP_X_REAL_IP
    }

    attr_accessor :timestamp, :severity, :progname, :message, :key, :backtrace, :env

    def initialize(severity, progname, message, timestamp = nil, key = nil)
      @timestamp = timestamp || get_timestamp
      @severity = severity
      @progname = progname
      @message = message
      @key = key || SecureRandom.hex
      @backtrace = nil
    end

    def to_h
      {
        message: @message,
        progname: @progname,
        severity: @severity,
        timestamp: @timestamp,
        key: @key,
        backtrace: @backtrace,
        env: @env
      }
    end

    def to_json(opts=nil)
      JSON.fast_generate(to_h,opts)
    end

    def self.from_json(json)
      parsed = ::JSON.parse(json)
      msg = new( parsed["severity"],
            parsed["progname"],
            parsed["message"],
            parsed["timestamp"],
            parsed["key"] )
      msg.backtrace = parsed["backtrace"]
      msg.env = parsed["env"]
      msg
    end

    def populate_from_env(env)
      @env = Message.populate_from_env(env)
    end


    def self.populate_from_env(env)
      env[LOGSTER_ENV] ||= begin
          scrubbed = {}
          request = Rack::Request.new(env)
          params = {}
          request.params.each do |k,v|
            if k.include? "password"
              params[k] = "[reducted]"
            else
              params[k] = v[0..100]
            end
          end
          scrubbed["params"] = params if params.length > 0
          ALLOWED_ENV.map{ |k|
           scrubbed[k] = env[k] if env[k]
          }
          scrubbed
      end
    end

    protected

    def get_timestamp
      (Time.new.to_f * 1000).to_i
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
logster-0.0.10 lib/logster/message.rb