Class: AntisyslogSender

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

Instance Method Summary collapse

Constructor Details

#initialize(remote_hostname, remote_port, options = {}) ⇒ AntisyslogSender

Returns a new instance of AntisyslogSender.



206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
# File 'lib/antisyslog.rb', line 206

def initialize(remote_hostname, remote_port, options = {})
  @remote_hostname = remote_hostname
  @remote_port     = remote_port
  @whinyerrors     = options[:whinyerrors]
  @protocol        = options[:protocol] || 'tcp'
  @splitlines      = options[:split_lines] || false
  
  @socket = @protocol == 'tcp' ? TCPSocket.new(@remote_hostname, @remote_port) : UDPSocket.new
  @packet = AntisyslogPacket.new

  local_hostname   = options[:local_hostname] || (Socket.gethostname rescue `hostname`.chomp)
  local_hostname   = 'localhost' if local_hostname.nil? || local_hostname.empty?
  @packet.hostname = local_hostname

  @packet.facility = options[:facility] || 'user'
  @packet.severity = options[:severity] || 'notice'
  @packet.tag      = options[:program]  || "#{File.basename($0)}[#{$$}]"
end

Instance Method Details

#closeObject



259
260
261
# File 'lib/antisyslog.rb', line 259

def close
  @socket.close
end

#send_msg(msg) ⇒ Object



225
226
227
228
229
230
231
232
233
# File 'lib/antisyslog.rb', line 225

def send_msg(msg)
  packet = @packet.dup
  packet.content = msg
  if @protocol == 'tcp'
    @socket.send(packet.assemble, 0)
  else
    @socket.send(packet.assemble, 0, @remote_hostname, @remote_port)
  end
end

#transmit(message) ⇒ Object Also known as: write



235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
# File 'lib/antisyslog.rb', line 235

def transmit(message)
  if @splitlines
    message.split(/\r?\n/).each do |line|
      begin
        next if line =~ /^\s*$/
        send_msg(line)
      rescue
        $stderr.puts "#{self.class} error: #{$!.class}: #{$!}\nOriginal message: #{line}"
        raise if @whinyerrors
      end
    end
  else
    begin
      send_msg(message)
    rescue
      $stderr.puts "#{self.class} error: #{$!.class}: #{$!}\nOriginal message: #{message}"
      raise if @whinyerrors
    end
  end
end