PSR-3 日志接口规范

来源:互联网 发布:单页seo怎么赚钱 编辑:程序博客网 时间:2024/05/21 04:21

本文描述了日志类库的通用接口规范。

主要目标是让类库获得一个 Psr\Log\LoggerInterface对象并且通过简单和通用的方式来写日志。有自定义需求的框架和CMS系统,可以根据情况扩展这个接口,但是应该和本文档保持兼容。这能确保使用第三方类库文件时仍能写到集中的应用程序日志中。

关键词 “必须”(“MUST”)、“一定不可/一定不能”(“MUST NOT”)、“需要”(“REQUIRED”)、
“将会”(“SHALL”)、“不会”(“SHALL NOT”)、“应该”(“SHOULD”)、“不该”(“SHOULD NOT”)、
“推荐”(“RECOMMENDED”)、“可以”(“MAY”)和”可选“(“OPTIONAL”)的详细描述可参见 RFC 2119

单词implementor(实现者)在这个文档中被解释为:在日志相关的库或框架实现LoggerInterface接口的人。用这些实现者开发出来的类库的人都被称作user(用户)

1. 规范

1.1 基础

  • LoggerInterface接口对外定义了八个方法,分别用来记录RFC 5424中定义的八个等级的日志:debug、 info、 notice、 warning、 error、 critical、 alert 以及 emergency 。
  • 第九个方法log,其第一个参数为记录的等级。用一个日志等级常量来调用这个方法必须和直接调用指定等级方法的结果一致。如果传入的等级常量参数没有预先定义,则必须抛出Psr\Log\InvalidArgumentException类型的异常。在不确定的情况下,使用者不应该使用自定义的日志等级。

1.2 信息

  • 每个方法都接受一个字符串类型或者是有__toString()方法的对象作为记录信息参数。实现者可以对传入的对象有特殊的处理。如果不是这样,实现者必须把它转换成字符串。
  • message参数中可能包含一些可以被上下文数组所替换的占位符。

其中占位符必须与上下文数组中的键名保持一致。

占位符名字必须使用一对花括号来作为分隔符。在占位符和分隔符之间一定不能有任何空格。

占位符的名称应该只由A-Za-z,0-9、下划线_、以及英文的句号.组成,其它的字符作为以后占位符规范的保留字。

实现者可以通过对占位符采用不同的转义和转换策略,来生成最终的日志。而用户在不知道上下文的前提下,不应该提前转义占位符。

下面提供一个占位符替换的例子,仅作为参考:

 /**   * Interpolates context values into the message placeholders.   */  function interpolate($message, array $context = array())  {      // build a replacement array with braces around the context keys      $replace = array();      foreach ($context as $key => $val) {          // check that the value can be casted to string          if (!is_array($val) && (!is_object($val) || method_exists($val, '__toString'))) {              $replace['{' . $key . '}'] = $val;          }      }      // interpolate replacement values into the message and return      return strtr($message, $replace);  }  // a message with brace-delimited placeholder names  $message = "User {username} created";  // a context array of placeholder names => replacement values  $context = array('username' => 'bolivar');  // echoes "User bolivar created"  echo interpolate($message, $context);

1.3 上下文

  • 每个记录函数都接受一个上下文数组参数,用来存储不适合在字符串中填充的信息。它可以装载任何信息,所以实现者必须确保能正确处理其装载的信息,对于其装载的数据,一定不能抛出异常,或产生PHP出错、警告或提醒信息(error、warning、notice)。
  • 如果在上下文参数中传入了一个异常对象,它必须exception作为键名。记录异常信息是一种常见的模式,并且可以在日志系统支持的情况下从异常中提取出整个调用栈。实现者在使用它时,必须确保键名为 ‘exception‘的键值是否真的是一个Exception,毕竟它可以装载任何信息。

1.4 助手类和接口

  • Psr\Log\AbstractLogger类让你通过继承它并实现通用的log方法来方便的实现LoggerInterface接口。而其他八个方法将会把消息和上下文转发给log方法。
  • 同样地,使用Psr\Log\LoggerTrait也只需实现其中的log方法。不过,需要特别注意的是,在traits可复用代码块还不能实现接口前,还需要implement LoggerInterface
  • Psr\Log\NullLogger是和接口一起提供的。它在没有可用的日志记录器时,可以为使用日志接口的用户们提供一个后备的“黑洞”。然而,当上下文的构建非常消耗资源时,带条件检查的日志记录或许是更好的办法。
  • Psr\Log\LoggerAwareInterface只有一个setLogger(LoggerInterface $logger)方法,它可以在框架中用来随意设置一个日志记录器。
  • Psr\Log\LoggerAwareTraittrait可复用代码块可以在任何的类里面使用,只需通过它提供的$this->logger,就可以轻松地实现等同的接口。
  • Psr\Log\LogLevel 类装载了八个记录等级常量。

2. 包

psr/log中提供了上文描述过的接口和类,以及相关的异常类,还有一组用来验证你的实现的单元测试。

3. Psr\Log\LoggerInterface

<?phpnamespace Psr\Log;/** * Describes a logger instance * * The message MUST be a string or object implementing __toString(). * * The message MAY contain placeholders in the form: {foo} where foo * will be replaced by the context data in key "foo". * * The context array can contain arbitrary data, the only assumption that * can be made by implementors is that if an Exception instance is given * to produce a stack trace, it MUST be in a key named "exception". * * See https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md * for the full interface specification. */interface LoggerInterface{    /**     * System is unusable.     *     * @param string $message     * @param array $context     * @return null     */    public function emergency($message, array $context = array());    /**     * Action must be taken immediately.     *     * Example: Entire website down, database unavailable, etc. This should     * trigger the SMS alerts and wake you up.     *     * @param string $message     * @param array $context     * @return null     */    public function alert($message, array $context = array());    /**     * Critical conditions.     *     * Example: Application component unavailable, unexpected exception.     *     * @param string $message     * @param array $context     * @return null     */    public function critical($message, array $context = array());    /**     * Runtime errors that do not require immediate action but should typically     * be logged and monitored.     *     * @param string $message     * @param array $context     * @return null     */    public function error($message, array $context = array());    /**     * Exceptional occurrences that are not errors.     *     * Example: Use of deprecated APIs, poor use of an API, undesirable things     * that are not necessarily wrong.     *     * @param string $message     * @param array $context     * @return null     */    public function warning($message, array $context = array());    /**     * Normal but significant events.     *     * @param string $message     * @param array $context     * @return null     */    public function notice($message, array $context = array());    /**     * Interesting events.     *     * Example: User logs in, SQL logs.     *     * @param string $message     * @param array $context     * @return null     */    public function info($message, array $context = array());    /**     * Detailed debug information.     *     * @param string $message     * @param array $context     * @return null     */    public function debug($message, array $context = array());    /**     * Logs with an arbitrary level.     *     * @param mixed $level     * @param string $message     * @param array $context     * @return null     */    public function log($level, $message, array $context = array());}

4. Psr\Log\LoggerAwareInterface

<?phpnamespace Psr\Log;/** * Describes a logger-aware instance */interface LoggerAwareInterface{    /**     * Sets a logger instance on the object     *     * @param LoggerInterface $logger     * @return null     */    public function setLogger(LoggerInterface $logger);}

5. Psr\Log\LogLevel

<?phpnamespace Psr\Log;/** * Describes log levels */class LogLevel{    const EMERGENCY = 'emergency';    const ALERT     = 'alert';    const CRITICAL  = 'critical';    const ERROR     = 'error';    const WARNING   = 'warning';    const NOTICE    = 'notice';    const INFO      = 'info';    const DEBUG     = 'debug';}
2 0
原创粉丝点击