death-notifier/src/main/php/com/fwdekker/deathnotifier/LoggerUtil.php

54 lines
1.4 KiB
PHP

<?php
namespace com\fwdekker\deathnotifier;
use Monolog\ErrorHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
/**
* Helps with creating loggers.
*
* Contains global state, but reduces unnecessary parameter passing and unused fields.
*/
// TODO: Improve logging specificity and usefulness
class LoggerUtil
{
/**
* @var Logger|null the main logger instance that other loggers are derived from
*/
private static ?Logger $main_logger = null;
/**
* Configures the main logger.
*
* @param array<string, mixed> $config the logger configuration
* @return void
*/
public static function configure(array $config): void
{
if (self::$main_logger !== null)
throw new IllegalStateException("Logger has already been created.");
self::$main_logger = new Logger("main");
self::$main_logger->pushHandler(new StreamHandler($config["file"], $config["level"]));
ErrorHandler::register(self::$main_logger);
}
/**
* Returns a logger with the given name.
*
* @param string $name the name of the logger to return
* @return Logger a logger with the given name
*/
public static function with_name(string $name = "main"): Logger
{
if (self::$main_logger === null)
throw new IllegalStateException("Logger has not been created yet.");
return self::$main_logger->withName($name);
}
}