Files
oficial/app/common/Implement/Log/Handler/MySQL.php

73 lines
2.3 KiB
PHP
Raw Normal View History

2024-04-02 13:50:08 -03:00
<?php
namespace Incoviba\Common\Implement\Log\Handler;
2024-04-02 13:50:08 -03:00
use Incoviba\Common\Define\Connection;
2024-04-02 13:50:08 -03:00
use Monolog\Handler\AbstractProcessingHandler;
use Monolog\Level;
use Monolog\LogRecord;
use PDOStatement;
2024-04-02 13:50:08 -03:00
class MySQL extends AbstractProcessingHandler
2024-04-02 13:50:08 -03:00
{
private bool $initialized = false;
private PDOStatement $statement;
2024-06-07 17:18:20 -04:00
public function __construct(protected Connection $connection, protected int $retainDays = 90, int|string|Level $level = Level::Debug, bool $bubble = true)
2024-04-02 13:50:08 -03:00
{
parent::__construct($level, $bubble);
}
public function write(LogRecord $record): void
{
if (!$this->initialized) {
if (!$this->checkTableExists()) {
$this->createTable();
}
$this->cleanup();
2024-04-02 13:50:08 -03:00
$this->initialized();
}
$this->statement->execute([
'channel' => $record->channel,
'level' => $record->level->getName(),
'message' => $record->formatted,
'time' => $record->datetime->format('Y-m-d H:i:s.u'),
'context' => (count($record->context) > 0) ? json_encode($record->context, JSON_UNESCAPED_SLASHES) : '',
'extra' => (count($record->extra) > 0) ? json_encode($record->extra, JSON_UNESCAPED_SLASHES) : ''
]);
}
private function initialized(): void
{
$query = <<<QUERY
INSERT INTO monolog (channel, level, message, time, context, extra)
VALUES (:channel, :level, :message, :time, :context, :extra)
QUERY;
$this->statement = $this->connection->getPDO()->prepare($query);
$this->initialized = true;
}
private function checkTableExists(): bool
{
$query = "SHOW TABLES LIKE 'monolog'";
$result = $this->connection->query($query);
return $result->rowCount() > 0;
}
private function createTable(): void
{
$query = <<<QUERY
2024-04-02 13:50:08 -03:00
CREATE TABLE IF NOT EXISTS monolog (
channel VARCHAR(255),
level VARCHAR(100),
message LONGTEXT,
time DATETIME,
context LONGTEXT,
extra LONGTEXT
)
QUERY;
$this->connection->getPDO()->exec($query);
}
private function cleanup(): void
{
2024-06-07 17:18:20 -04:00
$query = "DELETE FROM monolog WHERE time < DATE_SUB(CURDATE(), INTERVAL {$this->retainDays} DAY)";
2024-04-02 13:50:08 -03:00
$this->connection->query($query);
}
}