Skip to content

Instantly share code, notes, and snippets.

@johlym
Last active July 5, 2020 04:31
Show Gist options
  • Save johlym/d1e0fc818245ff390337762e92917e9d to your computer and use it in GitHub Desktop.
Save johlym/d1e0fc818245ff390337762e92917e9d to your computer and use it in GitHub Desktop.
require 'daemons'
Daemons.run('syslog_relay.rb')
#!/usr/bin/env ruby
require 'socket'
LISTEN_PORT = 55514
DESTINATION_HOST = "abc.com"
DESTINATION_PORT = 12345
class SyslogRelay
##############################################################################
# <43>Jul 4 20:28:26 Gateway rsyslogd: set SCM_CREDENTIALS failed on '/dev/log': Protocol not available
# 1. <43>
# 2. Jul
# 3. 4
# 4. 20:28:26
# 5. Gateway
# 6. rsyslogd
# 7. set SCM_CREDENTIALS failed on '/dev/log': Protocol not available
GATEWAY_PARSER = /(<.+\>)(\w{3})\s(\s\d|\d{2})\s(\d{2}:\d{2}:\d{2})\s(\S+)\s(\S+):\s([\S\s]+)$/
##############################################################################
# <30>Jul 4 20:28:32 U7LR,788a20834cf7,v4.3.13.11253: logread[15580]: Logread connected to 10.68.0.51:55514
# 1. <30>
# 2. Jul
# 3. 4
# 4. 20:28:32
# 5. U7LR
# 6. 788a20834cf7
# 7. v4.3.13.11253
# 8. logread[15580]
# 9. Logread connected to 10.68.0.51:55514
UNIFI_PARSER = /(<.+\>)(\w{3})\s(\s\d|\d{2})\s(\d{2}:\d{2}:\d{2})\s(\S+),(\S+),([\w\d\.]+)[\s\:]+([\w\d\[\]\-]+)[\s\:]+([\S\s]+)$/
##############################################################################
def initialize(listen_port, destination_host, destination_port, include_version_details = true)
@server = UDPSocket.new
@server.bind("0.0.0.0", listen_port)
@client = UDPSocket.new
@destination_host = destination_host
@destination_port = destination_port
@include_version_details = include_version_details
end
def start
if @running
return
end
@running = true
run
end
def join
if @thread
@thread.join
end
end
def run
@thread = Thread.new do
while @running
begin
data, from = @server.recvfrom(65535)
if data && data.length > 0
if matched = data.match(UNIFI_PARSER)
# Matches GATEWAY logs
_, pri, mon, day, time, model, mac, fwver, process, message = *matched
output = "model=#{model} mac=#{mac} fw_version=#{fwver} process=#{process} message=#{message}"
formatted_message = "#{pri} #{mon} #{day} #{time} unifi device #{output}"
elsif matched = data.match(GATEWAY_PARSER)
# Matches Other UNIFI logs
_, pri, mon, day, time, model, process, message = *matched
output = "model=#{model} process=#{process} message=#{message}"
formatted_message = "#{pri} #{mon} #{day} #{time} unifi gateway #{output}"
end
@client.send(formatted_message, 0, @destination_host, @destination_port)
end
rescue => ex
puts "Error: #{ex.class}: #{ex.message}"
end
end
end
end
end
relay = SyslogRelay.new(LISTEN_PORT, DESTINATION_HOST, DESTINATION_PORT)
relay.start
relay.join
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment