概述 快速入门 教程 手册 最佳实践 组件 参考 贡献

发布于 2015-08-27 16:41:01 | 149 次阅读 | 评论: 0 | 来源: 网络整理

The Console component comes with a standalone logger complying with the PSR-3 standard. Depending on the verbosity setting, log messages will be sent to the OutputInterface instance passed as a parameter to the constructor.

The logger does not have any external dependency except php-fig/log. This is useful for console applications and commands needing a lightweight PSR-3 compliant logger:

namespace Acme;

use PsrLogLoggerInterface;

class MyDependency
{
    private $logger;

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

    public function doStuff()
    {
        $this->logger->info('I love Tony Vairelles' hairdresser.');
    }
}

You can rely on the logger to use this dependency inside a command:

namespace AcmeConsoleCommand;

use AcmeMyDependency;
use SymfonyComponentConsoleCommandCommand;
use SymfonyComponentConsoleInputInputInterface;
use SymfonyComponentConsoleOutputOutputInterface;
use SymfonyComponentConsoleLoggerConsoleLogger;

class MyCommand extends Command
{
    protected function configure()
    {
        $this
            ->setName('my:command')
            ->setDescription(
                'Use an external dependency requiring a PSR-3 logger'
            )
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $logger = new ConsoleLogger($output);

        $myDependency = new MyDependency($logger);
        $myDependency->doStuff();
    }
}

The dependency will use the instance of ConsoleLogger as logger. Log messages emitted will be displayed on the console output.

Verbosity

Depending on the verbosity level that the command is run, messages may or may not be sent to the OutputInterface instance.

By default, the console logger behaves like the Monolog’s Console Handler. The association between the log level and the verbosity can be configured through the second parameter of the ConsoleLogger constructor:

// ...
$verbosityLevelMap = array(
    LogLevel::NOTICE => OutputInterface::VERBOSITY_NORMAL,
    LogLevel::INFO   => OutputInterface::VERBOSITY_NORMAL,
);
$logger = new ConsoleLogger($output, $verbosityLevelMap);

Color

The logger outputs the log messages formatted with a color reflecting their level. This behavior is configurable through the third parameter of the constructor:

// ...
$formatLevelMap = array(
    LogLevel::CRITICAL => self::INFO,
    LogLevel::DEBUG    => self::ERROR,
);
$logger = new ConsoleLogger($output, array(), $formatLevelMap);
最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务