Class: Atech::NetworkLogIO

Inherits:
IO
  • Object
show all
Defined in:
lib/atech/network_log_io.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ NetworkLogIO

Returns a new instance of NetworkLogIO.

Raises:

  • (ArgumentError)


7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/atech/network_log_io.rb', line 7

def initialize(options)
  @options = options

  raise(ArgumentError, ':host is required') unless @options[:host]
  raise(ArgumentError, ':app_name is required') unless @options[:app_name]
  raise(ArgumentError, ':log_name is required') unless @options[:log_name]

  @options[:port]         ||= 4455
  @options[:buffer_size]  ||= 512

  @socket = UDPSocket.new
  empty_buffer!
end

Instance Attribute Details

#optionsObject (readonly)

Returns the value of attribute options.



5
6
7
# File 'lib/atech/network_log_io.rb', line 5

def options
  @options
end

Instance Method Details

#empty_buffer!Object



21
22
23
# File 'lib/atech/network_log_io.rb', line 21

def empty_buffer!
  @buffer = fresh_buffer
end

#flushObject



47
48
49
50
51
52
53
# File 'lib/atech/network_log_io.rb', line 47

def flush
  return self if @buffer == @api_key
  @buffer << "\0\0"
  @socket.send(@buffer, 0, @options[:host], @options[:port])
  empty_buffer!
  return self
end

#fresh_bufferObject



25
26
27
# File 'lib/atech/network_log_io.rb', line 25

def fresh_buffer
  [@options[:app_name].bytesize, @options[:app_name], @options[:log_name].bytesize, @options[:log_name]].pack('nA*nA*')
end

#write(data) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/atech/network_log_io.rb', line 29

def write(data)
  data.force_encoding('BINARY')
  data = data[0,@options[:buffer_size] - fresh_buffer.bytesize - 2]

  ## Pre-flush if the existing buffer plus the new data plus the terminator would be more than the buffer size
  if @buffer.bytesize + 2 + data.bytesize + 2 > @options[:buffer_size]
    self.flush
  end

  @buffer << [data.bytesize].pack('n')
  @buffer << data

  ## Flush is autoflush is set or the buffer is full
  self.flush if @options[:auto_flush] or @buffer.bytesize + 2 >= @options[:buffer_size]

  return data.bytesize
end