Sha256: 86b02ece9d3cfa0605f7e75ce29da4d3cfdeca9f7890fbfc42b3e0efc9a5c9d4

Contents?: true

Size: 1.96 KB

Versions: 2

Compression:

Stored size: 1.96 KB

Contents

require 'socket'
require 'syslog_protocol'

module RemoteSyslogSender
  class Sender
    # To suppress initialize warning
    class Packet < SyslogProtocol::Packet
      def initialize(*)
        super
        @time = nil
      end
    end

    attr_reader :socket
    attr_accessor :packet

    def initialize(remote_hostname, remote_port, options = {})
      @remote_hostname = remote_hostname
      @remote_port     = remote_port
      @whinyerrors     = options[:whinyerrors]
      @packet_size     = options[:packet_size] || 1024

      @packet = Packet.new

      local_hostname   = options[: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[:tag] || options[:program]  || "#{File.basename($0)}[#{$$}]"

      @socket = nil
    end

    def transmit(message, packet_options = nil)
      begin
        packet = @packet.dup
        if packet_options
          packet.tag = packet_options[:program] if packet_options[:program]
          packet.hostname = packet_options[:local_hostname] if packet_options[:local_hostname]
          %i(hostname facility severity tag).each do |key|
            packet.send("#{key}=", packet_options[key]) if packet_options[key]
          end
        end
        packet.content = message
        send_msg(packet.assemble(@packet_size))
      rescue
        if @whinyerrors
          raise
        else
          $stderr.puts "#{self.class} error: #{$!.class}: #{$!}\nOriginal message: #{message}"
        end
      end
    end

    # Make this act a little bit like an `IO` object
    alias_method :write, :transmit

    def close
      @socket.close
    end

    private

    def send_msg(payload)
      raise NotImplementedError, "please override"
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
remote_syslog_sender_multiline-1.2.5 lib/remote_syslog_sender_multiline/sender.rb
remote_syslog_sender_multiline-1.2.4 lib/remote_syslog_sender_multiline/sender.rb