登录不同文件时使用处理器

登录不同文件时使用处理器

本文介绍了Symfony2:登录不同文件时使用处理器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要在另一个文件中写入应用程序日志,而不是一个Symfony2编写自己的日志和系统日志.我知道我需要像这样创建自己的服务:

I want to write my application logs in another file than the one Symfony2 writes its own logs and system logs. I understood that I needed to create a service of my own like this :

services:
    actionslogger:
        class: Symfony\Bridge\Monolog\Logger
        arguments: [app]
        calls:
             - [pushHandler, [@actionslogger_handler]]
    actionslogger_handler:
        class: Monolog\Handler\StreamHandler
        arguments: [%kernel.logs_dir%/actions_%kernel.environment%.log, 200]

当我在应用程序中使用 $ logger = $ this-> get('actionslogger'); 时,效果很好.但是我也想使用格式化程序和处理器来管理日志的写入方式.为此,我使用以下配置:

That works fine when I use $logger = $this->get('actionslogger'); in my application, so that's ok.But I also want to use a Formatter and a Processor to manage the way my logs are written. To do that, I use this configuration :

services:
    actionslogger.formatter.session_request:
        class: Monolog\Formatter\LineFormatter
        arguments:
            - "[%%datetime%%] [%%extra.token%%] %%channel%%.%%level_name%%: %%message%%\n"

    actionslogger.processor.session_request:
        class: My\Bundle\LogProcessor
        arguments:  [ @session ]
        tags:
            - { name: actionslogger.processor, method: processRecord }

我可以通过以下配置将此格式化程序和处理器与Symfony2默认记录器一起使用:

I can use this Formatter and Processor with Symfony2 default logger with this config:

monolog:
    handlers:
        main:
            type:  stream
            path:  %kernel.logs_dir%/%kernel.environment%.log
            level: debug
            formatter: actionslogger.formatter.session_request

但是,如果我可以将格式化程序与自己的记录器一起使用,则不能使用处理器.这是我的配置:

But if I can use the Formatter with my own logger, I can't use the Processor. Here's my config:

services:
    actionslogger.formatter.session_request:
        class: Monolog\Formatter\LineFormatter
        arguments:
            - "[%%datetime%%] [%%extra.token%%] %%channel%%.%%level_name%%: %%message%%\n"

    actionslogger.processor.session_request:
        class: My\Bundle\LogProcessor
        arguments:  [ @session ]
        tags:
            - { name: actionslogger.processor, channel: app, method: processRecord, handler: @actionslogger_handler }

    actionslogger:
        class: Symfony\Bridge\Monolog\Logger
        arguments: [app]
        calls:
             - [pushHandler, [@actionslogger_handler]]
    actionslogger_handler:
        class: Monolog\Handler\StreamHandler
        arguments: [%kernel.logs_dir%/actions_%kernel.environment%.log, 200]
        calls:
             #- [pushProcessor, [???]]
             - [setFormatter, [@actionslogger.formatter.session_request]]

处理器配置中的标记通道和处理程序似乎没用.

The tags channel and handler in the Processor's config seems useless.

我该怎么做才能使处理器与记录仪一起使用?我应该在注释行中将什么传递给pushProcessor方法(如果那可能是有效的选项)?

What can I do to make the Processor work with my logger?What should I pass to the pushProcessor method in the commented line (if that could be a valid option)?

感谢您的帮助.

注意:使用Symfony 2.0.0

Note: using Symfony 2.0.0

推荐答案

对自己的回答:

好吧,我找不到如何设置它的方法,所以我最终得到了一个不太沉重的解决方案:

Well, I couldn't find how to set this, so I ended up with this not-so-heavy solution :

我创建了一个非常简单的新记录器,并在构造函数中影响了我全新的Processor,因此文件位于My/Bundle中,如下所示:

I create a new logger, that is quite simple, and affect it my brand new Processor in the constructor, so the files are in My/Bundle and like this:

#LogProcessor.php

use Symfony\Component\HttpFoundation\Session;
class LogProcessor
{
    private $session;
    private $token;
    public function __construct(Session $session)
    {
        $this->session = $session;
    }
    public function processRecord(array $record)
    {
        if (null === $this->token) {
            try {
                $this->token = ($this->session->getId());
            } catch (\RuntimeException $e) {
                $this->token = '????????';
            }
            $this->token .= '#' . substr(uniqid(), -8);
        }
        $record['extra']['token'] = $this->token;
        $record['extra']['context'] = "";
        foreach($record['context'] as $key=>$value) {
            $key=str_replace(array("=","#","|"),"",$key);
            $value=str_replace(array("=","#","|"),"",$value);
            $record['extra']['context'].=$key."=".$value."#";
        }
        return $record;
    }
}

#MyLogger.php

use Symfony\Bridge\Monolog\Logger;
use Symfony\Component\HttpFoundation\Session;
use My\Bundle\LogProcessor;

class MyLogger extends Logger {
    private $session;
    private $processor;

    public function __construct($name, Session $session)
    {
        parent::__construct($name);
        $this->session= $session;
        $this->processor= new LogProcessor($session);
        $this->pushProcessor((array($this->processor, 'processRecord')));
    }
}

(如果以后我想修改Logger的addRecord方法,这甚至可能会派上用场)

(That could even come in handy if I want to modify the addRecord method of Logger later)

然后我创建一个像这样的新服务:

Then I create a new service like this:

#app/config/config.yml or src/My/Bundle/Resources/config/services.yml (if imported in app/config/config.yml)

services:
    mylogger:
        class: My\Bundle\MyLogger
        arguments: [app, @session]
        calls:
             - [pushHandler, [@mylogger.handler]]
    mylogger.handler:
        class: Monolog\Handler\StreamHandler
        arguments: [%kernel.logs_dir%/actions_%kernel.environment%.log, 200] # 200 means "INFO"
        calls:
             - [setFormatter, [@monolog.formatter.compactformat]]
    monolog.formatter.compactformat:
        class: Monolog\Formatter\LineFormatter
        arguments:
            - "%%datetime%%|%%channel%%|%%level_name%%|%%extra.token%%|%%message%%|%%extra.context%%\n"

然后我去.现在,我可以将我的新日志记录服务与Formatter和/或Processor一起使用,并对其进行所需的操作(这里:以易于使用的格式添加会话ID和日志上下文信息).

And here I go. I can now use my new logging service, with my Formatter /and/ my Processor, and do what I want with them (here: adding session id and log context information in an easy-to-use format).

#MyController.php
public function myMethod() {
    ...
    $logger = $this->get('mylogger');
    $logger->info('ACCESS PAGE', array('user'=>$userName, 'IP'=>$userIP, 'section'=>$section));
    ...
}

无论如何,如果有人对我的第一个问题有答案(有关如何在个人日志服务中直接链接处理器,请直接在配置中),请在此处发布.

Anyway, if someone has the answer for my 1st question (about how to link the processor on a personal logging service, directly in the config), please post here.

这篇关于Symfony2:登录不同文件时使用处理器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 18:06