上节聊完了PHP官方的相关代码规范,下面给大家带来了PHP系列的PHP推荐标准的另外两个,PSR-3,PSR-4。

首先,我们先来了解下PSR-3是怎么回事。

PHP-FIG发布的第三个推荐规范与前两个不同,不是一系列的指导方针,而是一个接口,规定PHP日志记录器组件可以实现的方法。

基础

The LoggerInterface exposes eight methods to write logs to the eight RFC 5424levels (debug, info, notice, warning, error, critical, alert, emergency).

  1. <?php
  2.  
  3. namespace Psr\Log;
  4.  
  5. /**
  6. * Describes a logger instance
  7. *
  8. * The message MUST be a string or object implementing __toString().
  9. *
  10. * The message MAY contain placeholders in the form: {foo} where foo
  11. * will be replaced by the context data in key "foo".
  12. *
  13. * The context array can contain arbitrary data, the only assumption that
  14. * can be made by implementors is that if an Exception instance is given
  15. * to produce a stack trace, it MUST be in a key named "exception".
  16. *
  17. * See https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md
  18. * for the full interface specification.
  19. */
  20. interface LoggerInterface
  21. {
  22. /**
  23. * System is unusable.
  24. *
  25. * @param string $message
  26. * @param array $context
  27. * @return null
  28. */
  29. public function emergency($message, array $context = array());
  30.  
  31. /**
  32. * Action must be taken immediately.
  33. *
  34. * Example: Entire website down, database unavailable, etc. This should
  35. * trigger the SMS alerts and wake you up.
  36. *
  37. * @param string $message
  38. * @param array $context
  39. * @return null
  40. */
  41. public function alert($message, array $context = array());
  42.  
  43. /**
  44. * Critical conditions.
  45. *
  46. * Example: Application component unavailable, unexpected exception.
  47. *
  48. * @param string $message
  49. * @param array $context
  50. * @return null
  51. */
  52. public function critical($message, array $context = array());
  53.  
  54. /**
  55. * Runtime errors that do not require immediate action but should typically
  56. * be logged and monitored.
  57. *
  58. * @param string $message
  59. * @param array $context
  60. * @return null
  61. */
  62. public function error($message, array $context = array());
  63.  
  64. /**
  65. * Exceptional occurrences that are not errors.
  66. *
  67. * Example: Use of deprecated APIs, poor use of an API, undesirable things
  68. * that are not necessarily wrong.
  69. *
  70. * @param string $message
  71. * @param array $context
  72. * @return null
  73. */
  74. public function warning($message, array $context = array());
  75.  
  76. /**
  77. * Normal but significant events.
  78. *
  79. * @param string $message
  80. * @param array $context
  81. * @return null
  82. */
  83. public function notice($message, array $context = array());
  84.  
  85. /**
  86. * Interesting events.
  87. *
  88. * Example: User logs in, SQL logs.
  89. *
  90. * @param string $message
  91. * @param array $context
  92. * @return null
  93. */
  94. public function info($message, array $context = array());
  95.  
  96. /**
  97. * Detailed debug information.
  98. *
  99. * @param string $message
  100. * @param array $context
  101. * @return null
  102. */
  103. public function debug($message, array $context = array());
  104.  
  105. /**
  106. * Logs with an arbitrary level.
  107. *
  108. * @param mixed $level
  109. * @param string $message
  110. * @param array $context
  111. * @return null
  112. */
  113. public function log($level, $message, array $context = array());
  114. }

A ninth method, log, accepts a log level as the first argument. Calling this method with one of the log level constants MUST have the same result as calling the level-specific method.

Message参数

1、Every method accepts a string as the message, or an object with a__toString() method. Implementors MAY have special handling for the passed objects. If that is not the case, implementors MUST cast it to a string.

2、The message MAY contain placeholders which implementors MAY replace with values from the context array.

Placeholder names MUST correspond to keys in the context array.

Implementors MAY use placeholders to implement various escaping strategies and translate logs for display. Users SHOULD NOT pre-escape placeholder values since they can not know in which context the data will be displayed.

总的来讲,占位符是为后面的Context参数提供占位服务,$context参数用于构造复杂的日志消息,$context参数的值是一个关联数组,键是占位符的名称(不能有花括号),对应的值用于替换Message参数中的占位符。

The following is an example implementation of placeholder interpolation provided for reference purposes only:

  1. /**
  2. * Interpolates context values into the message placeholders.
  3. */
  4. function interpolate($message, array $context = array())
  5. {
  6. // build a replacement array with braces around the context keys
  7. $replace = array();
  8. foreach ($context as $key => $val) {
  9. // check that the value can be casted to string
  10. if (!is_array($val) && (!is_object($val) || method_exists($val, '__toString'))) {
  11. $replace['{' . $key . '}'] = $val;
  12. }
  13. }
  14.  
  15. // interpolate replacement values into the message and return
  16. return strtr($message, $replace);
  17. }
  18.  
  19. // a message with brace-delimited placeholder names
  20. $message = "User {username} created";
  21.  
  22. // a context array of placeholder names => replacement values
  23. $context = array('username' => 'bolivar');
  24.  
  25. // echoes "User bolivar created"
  26. echo interpolate($message, $context);

Context参数

1、Every method accepts an array as context data. This is meant to hold any extraneous information that does not fit well in a string.

2、If an Exception object is passed in the context data, it MUST be in the'exception' key.

这个参数是可选的,提供用于替换message参数中的占位标记的值。

辅助类和接口

1、The Psr\Log\AbstractLogger class lets you implement the LoggerInterface very easily by extending it and implementing the generic log method. The other eight methods are forwarding the message and context to it.

2、Similarly, using the Psr\Log\LoggerTrait only requires you to implement the generic log method. Note that since traits can not implement interfaces, in this case you still have to implement LoggerInterface.

3、The Psr\Log\NullLogger is provided together with the interface. It MAY be used by users of the interface to provide a fall-back “black hole” implementation if no logger is given to them. However, conditional logging may be a better approach if context data creation is expensive.

4、The Psr\Log\LoggerAwareInterface only contains a setLogger(LoggerInterface $logger) method and can be used by frameworks to auto-wire arbitrary instances with a logger.

  1. <?php
  2.  
  3. namespace Psr\Log;
  4.  
  5. /**
  6. * Describes a logger-aware instance
  7. */
  8. interface LoggerAwareInterface
  9. {
  10. /**
  11. * Sets a logger instance on the object
  12. *
  13. * @param LoggerInterface $logger
  14. * @return null
  15. */
  16. public function setLogger(LoggerInterface $logger);
  17. }

5、The Psr\Log\LoggerAwareTrait trait can be used to implement the equivalent interface easily in any class. It gives you access to $this->logger.

6、The Psr\Log\LogLevel class holds constants for the eight log levels.

  1. <?php
  2.  
  3. namespace Psr\Log;
  4.  
  5. /**
  6. * Describes log levels
  7. */
  8. class LogLevel
  9. {
  10. const EMERGENCY = 'emergency';
  11. const ALERT = 'alert';
  12. const CRITICAL = 'critical';
  13. const ERROR = 'error';
  14. const WARNING = 'warning';
  15. const NOTICE = 'notice';
  16. const INFO = 'info';
  17. const DEBUG = 'debug';
  18. }

总结

如果你想自己写个PSR-3日志记录器,那可没什么必要了,因为已经有很多人干过这件事了。

如果你正在使用Yii2.0框架写代码,你可以搜索下Logger.php这个文件,已经实现的非常好了。你需要做的只是一句简单的:

  1. Yii::info($message, $category);

即可,后面我会带大家讨论更多框架的事。

如果你不适用框架,枫爷这里给大家推荐一个很好的组件:monolog/monolog。

Monolog已经完全实现了PSR-3的接口,而且便于使用自定义的消息格式化程序和处理程序扩展功能。

如果大家对monolog感兴趣,可以去到他的官网进行查看,http://monolog.ow2.org/doc/index.html。

有了日志收集功能,如何进行日志的筛选,日志的盘查啥的,枫爷再推荐大家一款非常好用的软件,splunk,免费500M,超过部分要收钱,当然了,国人不会放过任何领域的,如果要免费,那就用用日志易吧,我就用的他,感觉不错的。

splunk:http://10data.com/splunk/

日志易:https://www.rizhiyi.com/

至于怎么用,大家可以先行去他们的官网先行了解,以后有机会,枫爷再教大家搭建日志平台的相关知识。

【PHP系列】PHP推荐标准之PSR-3,日志记录器接口的更多相关文章

  1. 【PHP系列】PHP推荐标准之PSR-1,PSR-2

    说起码代码,刚上大学那会,老师就教导我们,要严格,规范的,把代码写好.代码如人,工工整整.提起规范化的代码,从一开始用命令行编辑C语言代码就开始控制,强制自己按照相关的标准来,所以,现在写代码,不规范 ...

  2. 【PHP系列】PHP推荐标准之PSR-4,自动加载器策略

    接上回的继续说,上回说到PSR-3日志记录器接口,这回我们来说说PSR的最后一个标准,PSR-4,自动加载器策略. 缘由 自动加载器策略是指,在运行时按需查找PHP类.接口或性状,并将其载入PHP解释 ...

  3. Atitit 提升效率 界面gui方面的前后端分离与cbb体系建设 规范与推荐标准

    Atitit 提升效率 界面gui方面的前后端分离与cbb体系建设 规范与推荐标准 1. 界面gui方面的前后端分离重大意义1 2. 业务逻辑也适当的迁移js化1 3. 常用分离方法2 3.1. 页面 ...

  4. Atitit 我们的devops战略与规划 规范 推荐标准

    Atitit 我们的devops战略与规划 规范 推荐标准 1. Vm容器化1 2. 热部署tomcat+jrebel 或者resin1 3. 增量更新与差异更新1 4. 补丁提取与应用2 为了方便提 ...

  5. [译]新的CCSDS图像压缩推荐标准

    摘要——空间数据系统咨询委员会(CCSDS)的数据压缩工作组最近通过了图像数据压缩议案,最终版本预计在2005年发布.议案中采用的算法由两部分组成,先是一个对图像的二维离散小波变换,然后是对变换后的数 ...

  6. Keil MDK STM32系列(一) 基于标准外设库SPL的STM32F103开发

    Keil MDK STM32系列 Keil MDK STM32系列(一) 基于标准外设库SPL的STM32F103开发 Keil MDK STM32系列(二) 基于标准外设库SPL的STM32F401 ...

  7. Keil MDK STM32系列(二) 基于标准外设库SPL的STM32F401开发

    Keil MDK STM32系列 Keil MDK STM32系列(一) 基于标准外设库SPL的STM32F103开发 Keil MDK STM32系列(二) 基于标准外设库SPL的STM32F401 ...

  8. Keil MDK STM32系列(三) 基于标准外设库SPL的STM32F407开发

    Keil MDK STM32系列 Keil MDK STM32系列(一) 基于标准外设库SPL的STM32F103开发 Keil MDK STM32系列(二) 基于标准外设库SPL的STM32F401 ...

  9. 【开源】OSharp3.0框架解说系列(6.2):操作日志与数据日志

    OSharp是什么? OSharp是个快速开发框架,但不是一个大而全的包罗万象的框架,严格的说,OSharp中什么都没有实现.与其他大而全的框架最大的不同点,就是OSharp只做抽象封装,不做实现.依 ...

随机推荐

  1. iOS 之 const

    const int a与 int const a一样. const int *a ;//指针可以修改,指向常整形的指针 int* const a;// 常指针, int* 作为一个整体被限制, 所以指 ...

  2. Repeated Substring Pattern Leetcode

    Given a non-empty string check if it can be constructed by taking a substring of it and appending mu ...

  3. 上传预览 easyui部分控件获取focuse 表单验证

    js: $(document).ready(function () { //$('#creater').combobox({ // url: '/VMS.UI/BindData/ScheamData? ...

  4. HTML 布局

    网站布局 大多数网站会把内容安排到多个列中(就像杂志或报纸那样). 大多数网站可以使用 <div> 或者 <table> 元素来创建多列.CSS 用于对元素进行定位,或者为页面 ...

  5. jQuery的$(window).load与、(document).ready和window.onload的关系

    jQuery的$(window).load与.(document).ready和window.onload的关系 $(function() { console.log('document.ready ...

  6. JSP EL表达式 获得 request的GET/POST方法

    JSP EL表达式 获得 request的GET/POST方法: 不在requestScopse中: <p>得到request的方法</p> <p>pageCont ...

  7. open in browser

    Sublime Text 3 Build 3065 Preferences-Key Bindings User: 直接key binding:{ "keys": ["al ...

  8. css 清除浮动的方法

    /*方法一*/ /*局部清除*/ ;visibility:hidden;display:block;clear:both;} .clr{display:inline-block;} .clr{disp ...

  9. POJ3254(入门状态压缩dp)

    Corn Fields Time Limit: 2000MS   Memory Limit: 65536K Total Submissions: 13203   Accepted: 6921 Desc ...

  10. python爆破定长密码脚本

    def get_pwd(str, num):#str为可选字符集,num为密码长度 if(num == 1): for x in str: yield x else: for x in str: fo ...