将Monolog存储在数据库中

时间:2019-03-07 16:43:07

标签: database symfony monolog

我一直在用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做到这一点。

1 个答案:

答案 0 :(得分:0)

您可以通过创建自定义的独占渠道(例如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的类型)注入您的服务或您想记录任何内容的地方。这应该工作!现在,您可以根据自己的意愿来重构/增强功能。