Class: Bitlogger::RemoteLogger

Inherits:
Object
  • Object
show all
Defined in:
lib/bitlogger/remote_logger.rb

Instance Method Summary collapse

Constructor Details

#initialize(formatter, additional, url, post_key, ca_crt_path = nil) ⇒ RemoteLogger

Returns a new instance of RemoteLogger.

Raises:

  • (ArgumentError)


3
4
5
6
7
8
9
10
11
12
13
# File 'lib/bitlogger/remote_logger.rb', line 3

def initialize(formatter, additional, url, post_key, ca_crt_path = nil)
  raise ArgumentError, 'Invalid url' unless URI.valid?(url)
  if !ca_crt_path.nil? && !File.exist?(ca_crt_path)
    raise ArgumentError, "CA certificate not found (file `#{ca_crt_path}` missing)"
  end
  @formatter   = formatter
  @additional  = additional
  @url         = url
  @post_key    = post_key
  @ca_crt_path = ca_crt_path
end

Instance Method Details

#log(msgs) ⇒ Object

Parameters:

  • msgs (Array<Hash>, Hash)


16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/bitlogger/remote_logger.rb', line 16

def log(msgs)
  msgs = [msgs] unless msgs.is_a?(Array)
  msgs = msgs.map { |msg| @formatter.format_hash(@additional.merge(msg)) }
  response = nil

  if ssl_url?(@url)
    opts = {
        :method      => :post,
        :url         => @url,
        :payload     => {@post_key => msgs.to_json}
    }
    if @ca_crt_path.nil?
      opts[:verify_ssl]  = 0
    else
      opts[:verify_ssl]  = 1
      opts[:ssl_ca_file] = @ca_crt_path
    end
    response = RestClient::Request.execute(opts)
  else
    response = RestClient.post(@url, {@post_key => msgs.to_json})
  end
  response.code == 200
rescue => e
  STDERR.puts("Error: #{e.class.name}, #{e.message}")
  return false
end

#ssl_url?(url) ⇒ Boolean

Returns:

  • (Boolean)


43
44
45
# File 'lib/bitlogger/remote_logger.rb', line 43

def ssl_url?(url)
  url.start_with?('https://')
end