将Monolog存储在数据库中

问题描述 投票:-1回答:1

我一直用Symfony 4.2创建一个应用程序,我想保存数据库中的所有日志,我正在使用MonologBu​​ndle。

Monolog.yml

monolog:
    handlers:
        main:
            type: stream
            path: "%kernel.logs_dir%/%kernel.environment%.log"
            level: debug
            channels: ["!event"]
        console:
            type: console
            process_psr_3_messages: false
            channels: ["!event", "!doctrine", "!console"]

我想将数据存储在像enter image description here这样的数据库中

我怎么能用Symfony做到这一点。

database symfony monolog
1个回答
0
投票

您可以通过创建自定义monolog通道(例如doctrine_channel)和处理程序(例如doctrine)来实现这一点。根据您的需要更新下面的示例。

Monolog配置

monolog:
    channels: [doctrine_channel]
    handlers:
        main:
            ...
            channels: [... !doctrine_channel]
        console:
            ...
            channels: [... !doctrine_channel]
        doctrine:
            type: service
            channels: [doctrine_channel]
            id: app.logger.doctrine_handler

服务配置

services:
    app.logger.doctrine_handler:
        class: App\Logger\DoctrineHandler
        arguments:
            - "@doctrine.orm.entity_manager"

DoctrineHandler

namespace App\Logger;

use App\Entity\Log;
use Doctrine\ORM\EntityManagerInterface;
use Monolog\Handler\AbstractProcessingHandler;

class DoctrineHandler extends AbstractProcessingHandler
{
    private $initialized;
    private $entityManager;
    private $channel = 'doctrine_channel';

    public function __construct(EntityManagerInterface $entityManager)
    {
        parent::__construct();

        $this->entityManager = $entityManager;
    }

    protected function write(array $record)
    {
        if (!$this->initialized) {
            $this->initialize();
        }

        if ($this->channel != $record['channel']) {
            return;
        }

        $log = new Log();
        $log->setMessage($record['message']);
        $log->setLevel($record['level_name']);

        $this->entityManager->persist($log);
        $this->entityManager->flush();
    }

    private function initialize()
    {
        $this->initialized = true;
    }
}

结果

mysql> SELECT * FROM log;
+----+----------+-----------+---------------------+
| id | message  | level     | created_at          |
+----+----------+-----------+---------------------+
|  1 | Welcome! | INFO      | 2019-02-07 19:00:00 |
|  2 | Go back! | WARNING   | 2019-02-07 19:00:05 |
|  3 | Help!    | EMERGENCY | 2019-02-07 19:00:10 |
+----+----------+-----------+---------------------+
3 rows in set (0.00 sec)

然后将@monolog.logger.doctrine_channel(类型暗示LoggerInterface)注入您的服务或您想要记录的任何地方。这应该工作!现在,您可以根据需要进行重构/增强。

© www.soinside.com 2019 - 2024. All rights reserved.