首页 > 解决方案 > 我无法在 Symfony 3.4 中使用 Monolog 的特定通道将日志写入文件

问题描述

我尝试在 Symfony 3.4 的命令中使用 Monolog 中的特定通道(称为 encuestas_cloud)将日志写入特定文件,但我无法做到。

我已经阅读了 Symfony 文档并在网络上进行了搜索,我认为它配置得很好,但我得到了一个错误。

代码是:

在 config_dev.yml 中:

monolog:

  handlers:
    main:
        type: stream
        path: '%kernel.logs_dir%/%kernel.environment%.log'
        level: debug
        channels: ['!event']

  ...
    encuestas_cloud_logger:
        #type: rotating_file
        type: stream
        path: 'D:/web/xampp/htdocs/temp/logs/encuestas_cloud.log'
        level: info
        channels: ['encuestas_cloud']   
        max_files: 10       

在 services.yml

services:
  _defaults:
     autowire: true
     autoconfigure: true
     public: false

  AppBundle\Command\EncuestasCloudCommand\:
    resource: '../../src/AppBundle/Command/EncuestasCloudCommand.php'
    arguments: ['@logger']
    public: true
    tags:
        - { name: monolog.logger, channel: encuestas_cloud } 

命令:

// src/AppBundle/Command/EncuestasCloudCommand.php
namespace AppBundle\Command;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
...

class EncuestasCloudCommand extends ContainerAwareCommand

{
  private $logger;

  public function __construct(LoggerInterface $logger)
  {
    $this->logger = $logger;
    parent::__construct();
  }

 ...
 protected function execute(InputInterface $input, OutputInterface $output)
 {

    $logger = $this->logger;
    $logger->addInfo('My logger is now ready');

当我执行它时,我得到:

在 LoggerChannelPass.php 第 98 行:

Monolog 配置错误:分配给
“encuestas_cloud_logger”处理程序的日志记录通道“encuestas_cloud”不存在。

在 ContainerBuilder.php 第 1063 行:

您请求了一个不存在的服务“monolog.logger.encuestas_cloud”。

如果我添加channels: ['encuestas_cloud'] config_dev.yml

monolog:
  channels: ['encuestas_cloud'] 

  handlers:
    main:
        type: stream
...

错误消失,但日志仍转到常规日志文件:dev.log

请,有人可以帮我找出配置有什么问题吗?

非常感谢!!!

标签: symfonymonolog

解决方案


将您的命令的参数从更改@logger@monolog.logger.encuestas_cloud工作吗?这应该注入特定配置的记录器,因此您的日志记录将出现在正确的记录器中。

monolog:
  channels: ['encuestas_cloud']

应该定义 AFAIK,并明确排除main记录器的通道,以不出现在那里:

monolog:
    handlers:
        main:
            ...
            channels: [ '!encuestas_cloud' ]

推荐阅读