【PHP系列】PHP推荐标准之PSR-3,日志记录器接口

上节聊完了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).

<?php

namespace 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());
}

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:

/**
 * 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);

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.

<?php

namespace 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、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.

<?php

namespace 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‘;
}

总结

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

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

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/

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

时间: 2024-08-06 17:42:18

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

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

说起码代码,刚上大学那会,老师就教导我们,要严格,规范的,把代码写好.代码如人,工工整整.提起规范化的代码,从一开始用命令行编辑C语言代码就开始控制,强制自己按照相关的标准来,所以,现在写代码,不规范都不行,还是为当时打下的好习惯给自己点个赞. 现在写到了PHP,对于PHP,是否也有相关的代码规范呢,当然,你或许在阅读其他博客或者PHP相关文档的时候经常提到这几个名词,PSR-1,PSR-2之类的,这是PHP-FIG制定的推荐规范,今天,我们就来讲解下PHP的推荐标准,PSR(PHP Stand

PHP推荐标准(PSR)

PSR是PHP Standards Recommendation的简称. PSR-1: 基本的代码风格 PHP标签 必须把PHP代码放在<?php ?> 或 <?= ?> 标签中.不得使用其他PHP标签语法. 编码 所有PHP文件都必须使用UTF-8字符集编码,而且不能有字节顺序标记 目的 一个PHP文件可以定义符号(类.性状.函数和常量等),或者执行有副作用的操作(例如生成结果或处理数据),但不能同时做这两件事. 自动加载 PHP命名空间和类必须遵守PSR-4自动加载器标准. 类

WebApi系列~基于RESTful标准的Web Api

WebApi系列~基于RESTful标准的Web Api 回到目录 微软的web api是在vs2012上的mvc4项目绑定发行的,它提出的web api是完全基于RESTful标准的,完全不同于之前的(同是SOAP协议的)wcf和webService,它是简单,代码可读性强的,上手快的,如果要拿它和web服务相比,我会说,它的接口更标准,更清晰,没有混乱的方法名称,有的只有几种标准的请求,如get,post,put,delete等,它们分别对应的几个操作,下面讲一下: GET:生到数据列表(默

Atitit 我们的devops战略与规划&#160;规范 推荐标准

Atitit 我们的devops战略与规划 规范 推荐标准 1. Vm容器化1 2. 热部署tomcat+jrebel 或者resin1 3. 增量更新与差异更新1 4. 补丁提取与应用2 为了方便提升部署友好性,所以搞了个devops 1. Vm容器化 Java项目,和jdk,web server整合到一个文件夹下,使用相对路径..作为一个容器可以整体发布. 2. 热部署tomcat+jrebel 或者resin 3. 增量更新与差异更新 部署项目的时候,初次可以打个war(其实就是zip包)

深入理解JavaScript系列(21):SOLID五大原则之接口隔离原则ISP(转载)

深入理解JavaScript系列(21):SOLID五大原则之接口隔离原则ISP 前言 本章我们要讲解的是S.O.L.I.D五大原则JavaScript语言实现的第4篇,接口隔离原则ISP(The Interface Segregation Principle). 英文原文:http://freshbrewedcode.com/derekgreer/2012/01/08/solid-javascript-the-interface-segregation-principle/注:这篇文章作者写得

ABP(现代ASP.NET样板开发框架)系列之19、ABP应用层——审计日志

点这里进入ABP系列文章总目录 基于DDD的现代ASP.NET开发框架--ABP系列之19.ABP应用层——审计日志 ABP是“ASP.NET Boilerplate Project (ASP.NET样板项目)”的简称. ABP的官方网站:http://www.aspnetboilerplate.com ABP在Github上的开源项目:https://github.com/aspnetboilerplate 维基百科定义:审计跟踪(也称为审核日志)是一个安全相关的时间顺序记录,记录这些记录的目

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

前言 在<[开源]OSharp框架解说系列(6.1):日志系统设计>中,我们已经设计并实现了一个可扩展的日志系统,只要定义好输出端的Adapter,就可以以任意形式输出日志信息. 在日志开发中,有些日志记录需求是常规需要的,比如操作日志,数据变更日志,系统异常日志等,我们希望把这些常规需求都集成到OSharp框架当中.有了内置的支持,在做开发的时候,只需要很简单的配置,就可以实现相关需求. 关于三类日志,这里先简要描述一下: 操作日志:粗略描述系统用户(如管理员.业务人员.会员等)对系统的业务

Mahout学习系列之推荐算法

参考: 从源代码剖析Mahout推荐引擎 mahout 推荐系统示例 Mahout推荐算法API详解 使用Mahout实现协同过滤 Mahout的taste推荐系统里的几种Recommender分析 前言:Mahout框架集成了大量的常用的机器学习算法,且都支持在Hadoop分布式环境下运行,很大程度上节约了数据处理的时间成本,其中的推荐算法引擎有cf.taste包实现,它提供了一套完整的推荐算法工具库,同时规范了数据结构,并标准了程序开发过程. 1:Mahout推荐算法介绍 2:Taste接口

Python基础笔记系列十一:标准输入输出、文件读写和指针等操作

本系列教程供个人学习笔记使用,如果您要浏览可能需要其它编程语言基础(如C语言),why?因为我写得烂啊,只有我自己看得懂!! 标准输入输出一.输入 在sublime中这个时候需要安装SublimeREPL插件. Ctrl+shift+p 键入 install packages,再继续键入 SublimeREPL 安装即可然后每次编译运行的操作是:tools->sublimeREPL->python->python-Run current file.点击之后会出现新的页面*REPL*[py