Class: Sysloggly::Formatters::SimpleFormatter

Inherits:
Object
  • Object
show all
Defined in:
lib/sysloggly/formatters/simple_formatter.rb

Direct Known Subclasses

SyslogFormatter

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(input_uri, opts = {}) ⇒ SimpleFormatter

Returns a new instance of SimpleFormatter.



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/sysloggly/formatters/simple_formatter.rb', line 12

def initialize(input_uri, opts = {})
  @input_uri = input_uri

  @env = opts[:env] || Sysloggly.env
  @hostname = opts[:hostname] || Socket.gethostname.split(".").first
  @progname = opts[:progname]
  @custom_fields = opts.except(:progname).merge({
    env: @env,
    hostname: @hostname
  })

  if ["udp", "tcp"].include?(@input_uri.scheme) && !@input_uri.path.empty?
    if @facility = @input_uri.path.split("/")[1]
      @facility = @facility.to_i
      unless @facility <= 23 && @facility >= 0
        raise Sysloggly::UnknownFacility.new(@facility.to_s)
      end
    end
  else
    @facility = 23
  end
end

Instance Attribute Details

#custom_fieldsObject (readonly)

Returns the value of attribute custom_fields.



10
11
12
# File 'lib/sysloggly/formatters/simple_formatter.rb', line 10

def custom_fields
  @custom_fields
end

#input_uriObject (readonly)

Returns the value of attribute input_uri.



10
11
12
# File 'lib/sysloggly/formatters/simple_formatter.rb', line 10

def input_uri
  @input_uri
end

Instance Method Details

#call(severity, datetime, progname, payload) ⇒ Object



43
44
45
46
47
48
49
50
# File 'lib/sysloggly/formatters/simple_formatter.rb', line 43

def call(severity, datetime, progname, payload)
  message = "#{severity} [#{datetime.strftime(datetime_format)}] "

  message << MultiJson.dump(hashify_message(payload).merge(custom_fields))
  message << "\r\n"  if ["file", "tcp"].include?(input_uri.scheme)

  message
end

#datetime_formatObject

Specifies the date/time format for this client



38
39
40
# File 'lib/sysloggly/formatters/simple_formatter.rb', line 38

def datetime_format
  "%b %e %H:%M:%S"
end

#hashify_message(msg) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/sysloggly/formatters/simple_formatter.rb', line 53

def hashify_message(msg)
  if msg.is_a?(Hash)
    msg
  elsif msg.is_a?(Exception)
    { exception_class: msg.class.name, message: msg.message }
  elsif msg.is_a?(String)
    begin
      JSON.parse(msg)
    rescue
      { message: msg }
    end
  else
    { message: msg.inspect }
  end
end