feat: log to database

This commit is contained in:
Björn Fromme
2025-04-25 08:31:45 +02:00
parent 8d1edc3da0
commit 9094e8c061
7 changed files with 288 additions and 0 deletions
+8
View File
@@ -7,6 +7,10 @@ monolog:
when@dev: when@dev:
monolog: monolog:
handlers: handlers:
database:
type: service
id: App\Logger\DatabaseHandler
channels: ["core", "bpn"]
bpn: bpn:
type: stream type: stream
path: "%kernel.logs_dir%/%kernel.environment%.bpn.log" path: "%kernel.logs_dir%/%kernel.environment%.bpn.log"
@@ -52,6 +56,10 @@ when@test:
when@prod: when@prod:
monolog: monolog:
handlers: handlers:
database:
type: service
id: App\Logger\DatabaseHandler
channels: ["core", "bpn"]
bpn: bpn:
type: rotating_file type: rotating_file
max_files: 7 max_files: 7
+35
View File
@@ -0,0 +1,35 @@
<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
/**
* Auto-generated Migration: Please modify to your needs!
*/
final class Version20250425063035 extends AbstractMigration
{
public function getDescription(): string
{
return '';
}
public function up(Schema $schema): void
{
// this up() migration is auto-generated, please modify it to your needs
$this->addSql(<<<'SQL'
CREATE TABLE core_log_entry (id INT AUTO_INCREMENT NOT NULL, channel VARCHAR(255) NOT NULL, message VARCHAR(255) NOT NULL, context JSON DEFAULT NULL COMMENT '(DC2Type:json)', extra JSON DEFAULT NULL COMMENT '(DC2Type:json)', created_at DATETIME NOT NULL COMMENT '(DC2Type:datetime_immutable)', PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8mb4 COLLATE `utf8mb4_unicode_ci` ENGINE = InnoDB
SQL);
}
public function down(Schema $schema): void
{
// this down() migration is auto-generated, please modify it to your needs
$this->addSql(<<<'SQL'
DROP TABLE core_log_entry
SQL);
}
}
+1
View File
@@ -296,6 +296,7 @@ class ApiClient
$this->logger->info('Sending request to BPN API', [ $this->logger->info('Sending request to BPN API', [
'requestId' => $requestId, 'requestId' => $requestId,
'type' => $data['satz']['@typ'],
]); ]);
if (true === $debug || true === $this->config['debug']) { if (true === $debug || true === $this->config['debug']) {
+102
View File
@@ -0,0 +1,102 @@
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Table(name: 'core_log_entry')]
#[ORM\Entity]
class LogEntry
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(type: 'integer')]
private ?int $id = null;
#[ORM\Column(type: 'string', length: 255)]
private ?string $channel;
#[ORM\Column(type: 'string', length: 255)]
private ?string $message;
#[ORM\Column(type: 'json', nullable: true)]
private ?array $context = [];
#[ORM\Column(type: 'json', nullable: true)]
private ?array $extra = [];
#[ORM\Column(type: 'datetime_immutable')]
private \DateTimeImmutable $createdAt;
public function __construct(string $channel, string $message)
{
$this->channel = $channel;
$this->message = $message;
$this->createdAt = new \DateTimeImmutable('now');
}
public function getId(): ?int
{
return $this->id;
}
public function getMessage(): ?string
{
return $this->message;
}
public function setMessage(string $message): self
{
$this->message = $message;
return $this;
}
public function getChannel(): ?string
{
return $this->channel;
}
public function setChannel(?string $channel): self
{
$this->channel = $channel;
return $this;
}
public function getContext(): ?array
{
return $this->context;
}
public function setContext(?array $context): self
{
$this->context = $context;
return $this;
}
public function getExtra(): ?array
{
return $this->extra;
}
public function setExtra(?array $extra): self
{
$this->extra = $extra;
return $this;
}
public function getCreatedAt(): ?\DateTimeImmutable
{
return $this->createdAt;
}
public function setCreatedAt(\DateTimeImmutable $createdAt): self
{
$this->createdAt = $createdAt;
return $this;
}
}
+46
View File
@@ -0,0 +1,46 @@
<?php
namespace App\Logger;
use App\Entity\LogEntry;
use Doctrine\ORM\EntityManagerInterface;
use Monolog\Handler\AbstractProcessingHandler;
use Monolog\LogRecord;
class DatabaseHandler extends AbstractProcessingHandler
{
public function __construct(private readonly EntityManagerInterface $entityManager)
{
parent::__construct();
}
protected function write(LogRecord $record): void
{
$message = $this->replacePlaceHolder($record);
$logEntry = new LogEntry($record->channel, $message);
$logEntry
->setContext($record->context)
->setExtra($record->extra)
;
$this->entityManager->persist($logEntry);
$this->entityManager->flush();
}
private function replacePlaceHolder(LogRecord $record): string
{
$message = $record->message;
if (!str_contains($message, '{')) {
return $message;
}
$replacements = [];
foreach ($record->context as $k => $v) {
$replacements['{'.$k.'}'] = $v;
}
return strtr($message, $replacements);
}
}
+27
View File
@@ -0,0 +1,27 @@
<?php
namespace App\Logger;
use Monolog\Attribute\AsMonologProcessor;
use Monolog\LogRecord;
use Symfony\Component\HttpFoundation\RequestStack;
#[AsMonologProcessor]
class RequestInfoProcessor
{
public function __construct(private readonly RequestStack $requestStack)
{
}
public function __invoke(LogRecord $record): LogRecord
{
if (null == $request = $this->requestStack->getMainRequest()) {
return $record;
}
$record['extra']['uri'] = $request->getRequestUri();
$record['extra']['method'] = $request->getMethod();
return $record;
}
}
+69
View File
@@ -0,0 +1,69 @@
<?php
namespace App\Logger;
use App\Entity\User;
use Monolog\Attribute\AsMonologProcessor;
use Monolog\LogRecord;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken;
#[AsMonologProcessor]
class UserDataProcessor
{
public function __construct(private readonly Security $security)
{
}
public function __invoke(LogRecord $record): LogRecord
{
if (isset($record->extra['user'])) {
return $record;
}
if ('cli' === PHP_SAPI) {
$record->extra['user'] = [
'id' => null,
'username' => 'SYSTEM',
'role' => 'system',
];
return $record;
}
/** @var User $user */
$user = $this->security->getUser();
if (null === $user) {
$record->extra['user'] = [
'id' => null,
'username' => 'ANONYMOUS',
'role' => 'public',
];
return $record;
}
// Check for switched or aliased users
$originalUser = null;
$token = $this->security->getToken();
if ($token instanceof SwitchUserToken) {
// User is currently switched to
$originalUser = $token->getOriginalToken()->getUser();
}
if (null !== $originalUser) {
$username = sprintf('%s (via %s)', $user->getUserIdentifier(), $originalUser->getUserIdentifier());
} else {
$username = $user->getUserIdentifier();
}
$record->extra['user'] = [
'id' => $user->getId(),
'username' => $username,
'roles' => $user->getRoles(),
];
return $record;
}
}