Implement proper log output

This commit is contained in:
Christopher Vagnetoft
2026-01-17 18:05:02 +01:00
parent b5de63e225
commit e3022469e7
2 changed files with 46 additions and 10 deletions

View File

@@ -1,6 +1,8 @@
#!/usr/bin/env php #!/usr/bin/env php
<?php <?php
use Psr\Log\AbstractLogger;
require_once __DIR__."/../vendor/autoload.php"; require_once __DIR__."/../vendor/autoload.php";
$opts = getopt("hc:",["help","config:"],$optind); $opts = getopt("hc:",["help","config:"],$optind);
@@ -11,6 +13,15 @@ $configFile = isset($opts['c'])
? $opts['config'] ? $opts['config']
: null); : null);
$logger = new class extends AbstractLogger
{
public function log($level, string|Stringable $message, array $context = []): void
{
printf("[%s] %s %s\n", $level, $message, $context?json_encode($context,JSON_UNESCAPED_SLASHES):'');
}
};
$daemon = (new NoccyLabs\Ntfi\NtfiDaemon()) $daemon = (new NoccyLabs\Ntfi\NtfiDaemon())
->setLogger($logger)
->setConfigFile($configFile) ->setConfigFile($configFile)
->start(); ->start();

View File

@@ -4,6 +4,8 @@ namespace NoccyLabs\Ntfi;
use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\ServerRequestInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use React\Http\Browser; use React\Http\Browser;
use React\Http\HttpServer; use React\Http\HttpServer;
use React\Http\Message\Response; use React\Http\Message\Response;
@@ -24,6 +26,12 @@ class NtfiDaemon
private array $channels = []; private array $channels = [];
private LoggerInterface $logger;
public function __construct()
{
$this->logger = new NullLogger();
}
/** /**
* Set the configuration file to use * Set the configuration file to use
* *
@@ -39,6 +47,12 @@ class NtfiDaemon
return $this; return $this;
} }
public function setLogger(LoggerInterface $logger): self
{
$this->logger = $logger;
return $this;
}
/** /**
* Read the configuration, and/or return with defaults. * Read the configuration, and/or return with defaults.
* *
@@ -79,13 +93,17 @@ class NtfiDaemon
$config = $this->readConfig(); $config = $this->readConfig();
$this->servers = $config['servers']; $this->servers = $config['servers'];
printf("Configured servers: %s\n", join(", ",array_keys($this->servers))); $this->logger->debug("Configured servers:");
foreach ($this->servers as $server => $info) {
$this->logger->debug(sprintf(" %s -> %s", $server, $info['server']??'?'));
}
$this->channels = $config['channels']; $this->channels = $config['channels'];
printf("Configured channels:\n"); $this->logger->debug("Configured channels:");
foreach ($this->channels as $channel=>$info) { foreach ($this->channels as $channel=>$info) {
printf(" %s -> %s\n", $channel, $info['destination']??'?'); $this->logger->debug(sprintf(" %s -> %s", $channel, $info['destination']??'?'));
} }
$this->setupHttp($config['listen']); $this->setupHttp($config['listen']);
$this->logger->info("Listening on http://{$config['listen']}");
return $this; return $this;
} }
@@ -113,17 +131,24 @@ class NtfiDaemon
*/ */
private function onRequest(ServerRequestInterface $request) private function onRequest(ServerRequestInterface $request)
{ {
$d = new Deferred();
$path = trim($request->getUri()->getPath(), '/'); $path = trim($request->getUri()->getPath(), '/');
$type = $request->getHeaderLine("content-type"); $type = $request->getHeaderLine("content-type");
$body = $request->getBody(); $body = $request->getBody();
try { try {
$this->doPublish($path, $type, $body); $this->doPublish($path, $type, $body)->then(
fn($r) => $d->resolve($r),
fn($t) => $d->reject($t)
);
} catch (\Exception $e) { } catch (\Exception $e) {
return Response::plaintext($e->getMessage())->withStatus(500); $this->logger->error($e->getMessage(), [ 'file' => $e->getFile(), 'line' => $e->getLine() ]);
$d->reject(new \Throwable("Publish failed"));
// return Response::plaintext($e->getMessage())->withStatus(500);
} }
return Response::plaintext("OK"); return $d->promise();
} }
/** /**
@@ -136,7 +161,7 @@ class NtfiDaemon
*/ */
private function doPublish(string $path, string $type, string $body): PromiseInterface private function doPublish(string $path, string $type, string $body): PromiseInterface
{ {
printf("in: %s (%s) %d bytes\n", $path, $type, strlen($body)); $this->logger->info(sprintf("request: %s (%s) %d bytes", $path, $type, strlen($body)));
foreach ($this->channels as $pattern => $channel) { foreach ($this->channels as $pattern => $channel) {
$re = '/^'.preg_replace('/\{(.+?)\}/', '(?P<$1>[a-zA-Z0-9-_]+)', $pattern).'$/'; $re = '/^'.preg_replace('/\{(.+?)\}/', '(?P<$1>[a-zA-Z0-9-_]+)', $pattern).'$/';
// printf("pattern={%s} re={%s}\n", $pattern, $re); // printf("pattern={%s} re={%s}\n", $pattern, $re);
@@ -152,6 +177,7 @@ class NtfiDaemon
} }
} }
return new Promise(function (callable $resolve, callable $reject) use ($path) { return new Promise(function (callable $resolve, callable $reject) use ($path) {
$this->logger->notice("No channel found matching '{$path}'");
$reject(new \Exception("No channel matching '{$path}'")); $reject(new \Exception("No channel matching '{$path}'"));
}); });
} }
@@ -168,12 +194,11 @@ class NtfiDaemon
*/ */
private function publish(string $connection, string $topic, string $type, string $body): PromiseInterface private function publish(string $connection, string $topic, string $type, string $body): PromiseInterface
{ {
printf("out: %s %s (%s) %d bytes\n", $connection, $topic, $type, strlen($body)); $this->logger->debug(sprintf("Attempting to publish to topic '%s' on '%s'", $topic, $connection));
$d = new Deferred(); $d = new Deferred();
$serverInfo = $this->servers[$connection] ?? throw new \Exception("The server '{$connection}' is not configured"); $serverInfo = $this->servers[$connection] ?? throw new \Exception("The server '{$connection}' is not configured");
$browser = new Browser(); $browser = new Browser();
if (isset($serverInfo['token']) && $serverInfo['token']) { if (isset($serverInfo['token']) && $serverInfo['token']) {
$browser = $browser $browser = $browser
@@ -187,7 +212,7 @@ class NtfiDaemon
$url = sprintf("https://%s/%s", $serverInfo['server'], $topic); $url = sprintf("https://%s/%s", $serverInfo['server'], $topic);
printf("post: %s\n", $url); $this->logger->info(sprintf("Posting to URL '%s'", $url));
$browser->post($url, [ $browser->post($url, [
'content-type' => $type, 'content-type' => $type,
], $body)->then( ], $body)->then(