我一直在用Symfony 4.2创建一个应用程序,我想将所有日志保存在数据库中,我正在使用MonologBundle。
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"]
如何使用Symfony做到这一点。
答案 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
的类型)注入您的服务或您想记录任何内容的地方。这应该工作!现在,您可以根据自己的意愿来重构/增强功能。