Skip to content

Instantly share code, notes, and snippets.

@karboom
Last active May 17, 2018 07:25
Show Gist options
  • Save karboom/bec3bfb385e8d08afa046594fe1c9ccb to your computer and use it in GitHub Desktop.
Save karboom/bec3bfb385e8d08afa046594fe1c9ccb to your computer and use it in GitHub Desktop.
A udp server for HAProxy syslog and insert into influxdb
const dgram = require('dgram');
const server = dgram.createSocket('udp4');
const cp = require('child_process')
const config = {
db: 'HAProxy',
url: 'localhost:8086',
listen: 514
}
server.on('error', (err) => {
console.log(`server error:\n${err.stack}`);
server.close();
});
server.on('message', (msg, rinfo) => {
// 自己找一段日志测试一下就知道对应数据了,因此使用简单方法
let main = msg.toString().split('haproxy')[1]
let segments = main.split(' ')
// 声明变量
let [path, query] = (segments[14] || '').split('?')
let process_name = 'haproxy'+segments[0].replace(':', '')
let ip = segments[1].split(':')[0]
let method = segments[13].substr(1)
let status = segments[6]
let return_size = segments[7]
let backend = segments[4].split('/')[1]
let [accept_time, queue_time, connect_time, response_time, total_time] = segments[5].split('/')
let [process_connection, front_connection, backend_connection] = segments[11].split('/')
let tags = `ip=${ip},url=${path},process=${process_name},status=${status},backend=${backend}`
let fields = `method="${method}",return_size=${return_size},accept_time=${accept_time},queue_time=${queue_time},connect_time=${connect_time},response_time=${response_time},total_time=${total_time},process_connection=${process_connection},backend_connection=${backend_connection}`
// 需要纳秒,注意:只是日志出创建时间
let create_time = Date.parse(segments[2].replace(':', ' ').replace('[', '').replace(']', '')) + '000000'
let line = `${config.db},${tags} ${fields} ${create_time}`
cp.exec(`curl -i -X POST 'http://${config.url}/write?db=${config.db}' --data-binary '${line}'`, (err, output) => {
if (err) console.error(err)
if (output.toString().indexOf('204') === -1) console.log('日志格式错误: ' + output)
})
});
server.on('listening', () => {
const address = server.address();
console.log(`server listening ${address.address}:${address.port}`);
});
server.bind(config.listen);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment