This repository has been archived on 2024-09-05. You can view files and clone it, but cannot push or open issues or pull requests.
shimmie2/ext/log_logstash/main.php

69 lines
1.7 KiB
PHP
Raw Normal View History

2021-12-14 18:32:47 +00:00
<?php
declare(strict_types=1);
2015-01-24 16:57:28 +00:00
namespace Shimmie2;
class LogLogstash extends Extension
{
public function onInitExt(InitExtEvent $event): void
{
global $config;
$config->set_default_string("log_logstash_host", "127.0.0.1:1234");
}
public function onLog(LogEvent $event): void
{
global $user;
2015-01-24 16:57:28 +00:00
try {
$data = [
"@type" => "shimmie",
"@message" => $event->message,
"@fields" => [
"username" => ($user && $user->name) ? $user->name : "Anonymous",
"section" => $event->section,
"priority" => $event->priority,
"time" => $event->time,
],
#"@request" => $_SERVER,
"@request" => [
"UID" => get_request_id(),
"REMOTE_ADDR" => get_real_ip(),
],
];
2015-01-24 16:57:28 +00:00
$this->send_data($data);
2023-01-11 11:15:26 +00:00
} catch (\Exception $e) {
2019-10-02 09:10:47 +00:00
// we can't log that logging is broken
}
}
2015-01-24 16:57:28 +00:00
/**
* @param array<string, mixed> $data
*/
private function send_data(array $data): void
{
global $config;
2015-01-24 16:57:28 +00:00
$host = $config->get_string("log_logstash_host");
if (!$host) {
return;
}
2015-01-24 16:57:28 +00:00
try {
$parts = explode(":", $host);
$host = $parts[0];
$port = (int)$parts[1];
$fp = fsockopen("udp://$host", $port, $errno, $errstr);
2023-11-11 21:49:12 +00:00
if (!$fp) {
return;
}
fwrite($fp, \Safe\json_encode($data));
fclose($fp);
2023-01-11 11:15:26 +00:00
} catch (\Exception $e) {
2019-10-02 09:10:47 +00:00
// we can't log that logging is broken
}
}
2015-01-24 16:57:28 +00:00
}