psr/log_用log4php实现PSR-3

psr/log

With the recent passage of PSR-3, a standard for a common interface for logging libraries, it seems appropriate to discuss the implementation with my favorite logging library. log4php is an open source Apache project that is a very versatile logging framework.

随着最近PSR-3(日志记录库通用接口的标准)的通过,似乎有必要与我最喜欢的日志记录库讨论实现。 log4php是一个开放源代码的Apache项目,它是一个非常通用的日志记录框架。

Through log4php’s configuration files, logging has a variety of output locations, so it’s possible to send specific log levels to different output locations. For example: debug, info, and notice are used mainly for general logging and debugging, and so it makes sense to direct these to a standard log file, whereas critical and above typically mean something has gone horribly wrong with our application and it makes more sense to send these to ourselves via email for immediate diagnosis.

通过log4php的配置文件,日志记录具有各种输出位置,因此可以将特定的日志级别发送到不同的输出位置。 例如:debug,info和notice主要用于常规的日志记录和调试,因此将它们定向到标准日志文件是有意义的,而关键的及以上的消息通常意味着我们的应用程序出现了严重错误,它使更多通过电子邮件将这些信息发送给我们进行即时诊断的感觉。

获取依赖 (Getting Dependencies)

Before we can start writing code, we need to our dependencies. The PSR-3 interface class is required; it’s currently found on GitHub and can be installed via composer from Packagist. Also, the log4php framework is required, which can be downloaded from Apache, with PEAR, or composer.

在开始编写代码之前,我们需要对我们的依赖项。 需要PSR-3接口类; 它目前可以在GitHub上找到 ,可以通过 Packagist的composer安装。 另外,需要log4php框架,可以从Apache ,PEAR 或composer 下载该框架。

Here’s a sample composer.json file that sets everything up:

这是设置所有内容的示例composer.json文件:

{
    "require": {
        "psr/log": "dev-master",
        "apache/log4php": "2.3.0"
    }
}

包装log4php (Wrapping log4php)

With the necessary third-party libraries installed, we can create a generic logging class which implements the PSR-3 interface and uses log4php.

安装了必要的第三方库后,我们可以创建一个通用的日志记录类,该类实现PSR-3接口并使用log4php。

Eight different log levels are exposed by the PSR-3 interface: debug, info, notice, warning, error, critical, alert, and emergency. log4php contains six logging levels: trace, debug, info, warn, error, and fatal. We have to map the PSR-3 levels to appropriate log4php levels. The below class implements interface and manages a log4php logger instance to map the levels.

PSR-3接口提供了八种不同的日志级别:调试,信息,通知,警告,错误,严重,警报和紧急情况。 log4php包含六个日志记录级别:跟踪,调试,信息,警告,错误和致命。 我们必须将PSR-3级别映射到适当的log4php级别。 下面的类实现接口并管理一个log4php记录器实例以映射级别。

<?php
require_once 'vendor/autoload.php';

class MyLogger implements PsrLogLoggerInterface
{
    private $logger;

    public function __construct($logger = 'main', $config = null) {
        Logger::configure($config);
        $this->logger = Logger::getLogger($logger);
    }

    /**
     * System is unusable.
     *
     * @param string $message
     * @param array $context
     * @return null
     */
    public function emergency($message, array $context = array()) {
        $this->logger->fatal($this->interpolate($message, $context));
    }

    /**
     * Action must be taken immediately.
     *
     * @param string $message
     * @param array $context
     * @return null
     */
    public function alert($message, array $context = array()) {
       $this->logger->fatal($this->interpolate($message, $context));
    }

    /**
     * Critical conditions.
     *
     * @param string $message
     * @param array $context
     * @return null
     */
    public function critical($message, array $context = array()) {
        $this->logger->fatal($this->interpolate($message, $context));
    }

    /**
     * Runtime errors that do not require immediate action but should
     * be logged and monitored.
     *
     * @param string $message
     * @param array $context
     * @return null
     */
    public function error($message, array $context = array()) {
        $this->logger->error($this->interpolate($message, $context));
    }

    /**
     * Exceptional occurrences that are not errors.
     *
     * @param string $message
     * @param array $context
     * @return null
     */
    public function warning($message, array $context = array()) {
        $this->logger->warn($this->interpolate($message, $context));
    }
    /**
     * Normal but significant events.
     *
     * @param string $message
     * @param array $context
     * @return null
     */
    public function notice($message, array $context = array()) {
        $this->logger->info($this->interpolate($message, $context));
    }

    /**
     * Interesting events.
     *
     * @param string $message
     * @param array $context
     * @return null
     */
    public function info($message, array $context = array()) {
        $this->logger->info($this->interpolate($message, $context));
    }

    /**
     * Detailed debug information.
     *
     * @param string $message
     * @param array $context
     * @return null
     */
    public function debug($message, array $context = array()) {
        $this->logger->debug($this->interpolate($message, $context));
    }

    /**
     * Logs with an arbitrary level.
     *
     * @param mixed $level
     * @param string $message
     * @param array $context
     * @return null
     */
    public function log($level, $message, array $context = array()) {
        throw new Exception('Please call specific logging message');
    }

    /**
     * Interpolates context values into the message placeholders.
     * Taken from PSR-3's example implementation.
     */
    protected function interpolate($message, array $context = array()) {
        // build a replacement array with braces around the context
        // keys
        $replace = array();
        foreach ($context as $key => $val) {
            $replace['{' . $key . '}'] = $val;
        }

        // interpolate replacement values into the message and return
        return strtr($message, $replace);
    }
}

Apart from implementing the PSR-3 interface, this class contains a constructor that accepts 2 optional parameters named $logger and $config. The first parameter allows you to specify a name for the logger and log4php will maintain a reference to it allowing you to maintain multiple logger instances at the same time with different names. The second parameter allows you to specify a configuration file. If none is specified, log4php will use its default configuration.

除了实现PSR-3接口之外,此类还包含一个构造函数,该构造函数接受2个名为$logger$config可选参数。 第一个参数允许您为记录器指定一个名称,log4php将维护对它的引用,从而允许您使用不同的名称同时维护多个记录器实例。 第二个参数允许您指定配置文件。 如果未指定,log4php将使用其默认配置。

The newly created MyLogger class can now be tested with the following example:

现在,可以使用以下示例测试新创建的MyLogger类:

<?php
$logger = new MyLogger();
$logger->debug('My debug test');

The default log4php setting for debug will output the message to standard out, so the results of this example will be sent to the web browser.

调试的默认log4php设置会将消息输出为标准输出,因此此示例的结果将发送到Web浏览器。

log4php配置 (log4php Configuration)

log4php ships with a default configuration so we get started using it right away, but it also provides the ability to override the configuration using XML or PHP code. The most popular supported configuration is XML.

log4php附带了默认配置,因此我们立即开始使用它,但是它也提供了使用XML或PHP代码覆盖配置的功能。 最受欢迎的支持配置是XML。

Let’s create a config.xml file with a new appender that will tell log4php to log all messages with warn and above to a file:

让我们使用新的附加程序创建config.xml文件,该附加程序将告诉log4php将所有带有warn及以上消息的消息记录到文件中:

<configuration xmlns="http://logging.apache.org/log4php/">
 <appender name="myAppender" class="LoggerAppenderFile">
  <param name="file" value="myLog.log"/>
 </appender>
 <root>
  <level value="WARN"/>
   <appender_ref ref="myAppender"/>
  </root>
</configuration>

We now need to pass the name of the new configuration file to MyLogger when we invoke its constructor.

现在,当我们调用其构造函数时,需要将新配置文件的名称传递给MyLogger

<?php
$logger = new MyLogger('main', 'config.xml');
$logger->debug('My debug test');

If you re-run the example, when the debug message is called, log4php will ignore it because debug is below warn and our configuration only logs warn and above.

如果重新运行该示例,则在调用debug消息时,log4php将忽略它,因为debug在警告以下,而我们的配置仅在warn以上。

结论 (Conclusion)

By leveraging the PSR-3 logging interface and log4php, standards-compliant logging is now extremely simple to add to any of our projects. To learn more about log4php, visit the Quick Start guide. For more about PSR-3, read the standard on GitHub.

通过利用PSR-3日志记录界面和log4php,符合标准的日志记录现在非常容易添加到我们的任何项目中。 要了解有关log4php的更多信息,请访问快速入门指南 。 有关PSR-3的更多信息,请阅读GitHub上标准

Image via Fotolia

图片来自Fotolia

翻译自: https://www.sitepoint.com/implementing-psr-3-with-log4php/

psr/log

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值