tp5下通过composer实现日志记录功能

简介:

tp5实现日志记录

1.安装 psr/log

composer require psr/log

422101-20171116115527406-1866179480.png

它的作用就是提供一套接口,实现正常的日志功能!

我们可以来细细的分析一下,LoggerInterface.php

<?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 void
     */
    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 void
     */
    public function alert($message, array $context = array());

    /**
     * Critical conditions.
     *
     * Example: Application component unavailable, unexpected exception.
     *
     * @param string $message
     * @param array  $context
     *
     * @return void
     */
    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 void
     */
    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 void
     */
    public function warning($message, array $context = array());

    /**
     * Normal but significant events.
     *
     * @param string $message
     * @param array  $context
     *
     * @return void
     */
    public function notice($message, array $context = array());

    /**
     * Interesting events.
     *
     * Example: User logs in, SQL logs.
     *
     * @param string $message
     * @param array  $context
     *
     * @return void
     */
    public function info($message, array $context = array());

    /**
     * Detailed debug information.
     *
     * @param string $message
     * @param array  $context
     *
     * @return void
     */
    public function debug($message, array $context = array());

    /**
     * Logs with an arbitrary level.
     *
     * @param mixed  $level
     * @param string $message
     * @param array  $context
     *
     * @return void
     */
    public function log($level, $message, array $context = array());
}

这是一套日志正常的接口,有层级,有消息,有具体的内容。

LogLevel.php

<?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';
}

定义一些错误常量。

AbstractLogger.php实现接口

<?php

namespace Psr\Log;

/**
 * This is a simple Logger implementation that other Loggers can inherit from.
 *
 * It simply delegates all log-level-specific methods to the `log` method to
 * reduce boilerplate code that a simple Logger that does the same thing with
 * messages regardless of the error level has to implement.
 */
abstract class AbstractLogger implements LoggerInterface
{
    /**
     * System is unusable.
     *
     * @param string $message
     * @param array  $context
     *
     * @return void
     */
    public function emergency($message, array $context = array())
    {
        $this->log(LogLevel::EMERGENCY, $message, $context);
    }

    /**
     * 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 void
     */
    public function alert($message, array $context = array())
    {
        $this->log(LogLevel::ALERT, $message, $context);
    }

    /**
     * Critical conditions.
     *
     * Example: Application component unavailable, unexpected exception.
     *
     * @param string $message
     * @param array  $context
     *
     * @return void
     */
    public function critical($message, array $context = array())
    {
        $this->log(LogLevel::CRITICAL, $message, $context);
    }

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

    /**
     * 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 void
     */
    public function warning($message, array $context = array())
    {
        $this->log(LogLevel::WARNING, $message, $context);
    }

    /**
     * Normal but significant events.
     *
     * @param string $message
     * @param array  $context
     *
     * @return void
     */
    public function notice($message, array $context = array())
    {
        $this->log(LogLevel::NOTICE, $message, $context);
    }

    /**
     * Interesting events.
     *
     * Example: User logs in, SQL logs.
     *
     * @param string $message
     * @param array  $context
     *
     * @return void
     */
    public function info($message, array $context = array())
    {
        $this->log(LogLevel::INFO, $message, $context);
    }

    /**
     * Detailed debug information.
     *
     * @param string $message
     * @param array  $context
     *
     * @return void
     */
    public function debug($message, array $context = array())
    {
        $this->log(LogLevel::DEBUG, $message, $context);
    }
}

Logger.php继承AbstractLogger.php

<?php

namespace Psr\Log;
use app\index\model\LogModel;

/**
 * This Logger can be used to avoid conditional log calls.
 *
 * Logging should always be optional, and if no logger is provided to your
 * library creating a NullLogger instance to have something to throw logs at
 * is a good way to avoid littering your code with `if ($this->logger) { }`
 * blocks.
 */
class Logger extends AbstractLogger
{
    /**
     * Logs with an arbitrary level.
     *
     * @param mixed  $level
     * @param string $message
     * @param array  $context
     *
     * @return void
     */
    public function log($level, $message, array $context = array())
    {
        // noop
        $logModel = new LogModel();
        $logModel->add($level,$message,json_encode($context));
        echo $logModel->id;
    }
}

这里面的log方法是我自己写的!!!

我们需要把日志存储到数据库中!!!

这里我设计了一个log表,包含id、level、message、 context、ip、url、create_on等。

我创建了一个LogModel.php

<?php
/**
 * @author: jim
 * @date: 2017/11/16
 */

namespace app\index\model;

use think\Model;

/**
 * Class LogModel
 * @package app\index\model
 *
 * 继承Model之后,就可以使用继承它的属性和方法
 *
 */
class LogModel extends Model
{
    protected $pk = 'id'; // 配置主键
    protected $table = 'log'; // 默认的表名是log_model

    public function add($level = "error",$message = "出错啦",$context = "") {
        $this->data([
            'level'  =>  $level,
            'message' =>  $message,
            'context' => $context,
            'ip' => getIp(),
            'url' => getUrl(),
            'create_on' => date('Y-m-d H:i:s',time())

        ]);
        $this->save();
        return $this->id;
    }

}

一切都准备好了,可以在控制器中使用了!

<?php
namespace app\index\controller;

use think\Controller;
use Psr\Log\Logger;

class Index extends Controller
{
    public function index()
    {
        $logger = new Logger();

        $context = array();
        $context['err'] = "缺少参数id";

        $logger->info("有新消息");
    }


    public function _empty() {
        return "empty";
    }
}

422101-20171116134011702-76171537.png

小结:

composer很好很强大!

这里是接口Interface的典型案例,定义接口,定义抽象类,定义具体类。

有了命名空间,可以很好的引用不同文件夹下的库!

互相使用,能够防止高内聚!即便是耦合也相对比较独立!

有了这个日志小工具,平时接口的一些报错信息就能很好的捕捉了!

只要

use Psr\Log\Logger;

然后

$logger = new Logger();
$logger->info("info信息");

使用非常方便!!!

附上获取ip、获取url的方法。


//获取用户真实IP
function getIp() {
    if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
        $ip = getenv("HTTP_CLIENT_IP");
    else
        if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
            $ip = getenv("HTTP_X_FORWARDED_FOR");
        else
            if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
                $ip = getenv("REMOTE_ADDR");
            else
                if (isset ($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
                    $ip = $_SERVER['REMOTE_ADDR'];
                else
                    $ip = "unknown";
    return ($ip);
}


// 获取url
function getUrl() {
    return 'http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
}


本文转自TBHacker博客园博客,原文链接:http://www.cnblogs.com/jiqing9006/p/7850916.html,如需转载请自行联系原作者

相关实践学习
日志服务之使用Nginx模式采集日志
本文介绍如何通过日志服务控制台创建Nginx模式的Logtail配置快速采集Nginx日志并进行多维度分析。
相关文章
|
3月前
|
存储 Go
Go 浅析主流日志库:从设计层学习如何集成日志轮转与切割功能
本文将探讨几个热门的 go 日志库如 logrus、zap 和官网的 slog,我将分析这些库的的关键设计元素,探讨它们是如何支持日志轮转与切割功能的配置。
93 0
Go 浅析主流日志库:从设计层学习如何集成日志轮转与切割功能
|
6月前
|
C++
C++-实现日志log功能
C++-实现日志log功能
|
6月前
|
存储 运维 监控
如何在 Spring Boot 中设计和实现业务操作日志功能?
如何在 Spring Boot 中设计和实现业务操作日志功能?
954 4
|
3月前
|
数据可视化 API 开发工具
Baumer工业相机堡盟工业相机如何通过NEOAPI SDK使用相机日志跟踪功能(C++)
Baumer工业相机堡盟工业相机如何通过NEOAPI SDK使用相机日志跟踪功能(C++)
33 0
|
9月前
|
SQL XML 前端开发
Spring Boot + vue-element 开发个人博客项目实战教程(十八、操作日志功能实现)2
Spring Boot + vue-element 开发个人博客项目实战教程(十八、操作日志功能实现)2
90 0
Spring Boot + vue-element 开发个人博客项目实战教程(十八、操作日志功能实现)2
|
4月前
|
设计模式 Java 数据库连接
设计模式与面向对象编程:举例说明在Java中应用工厂模式的场景,并编写一个简单的工厂模式实现。编写一个Java装饰器,用于添加日志记录功能到现有方法上。
设计模式与面向对象编程:举例说明在Java中应用工厂模式的场景,并编写一个简单的工厂模式实现。编写一个Java装饰器,用于添加日志记录功能到现有方法上。
23 0
|
5月前
|
JSON 监控 数据可视化
实时日志分析:通过Golang编写实时日志分析模块,加强公司监控管理软件的日志监控功能
在当今数字化时代,企业面临着庞大而复杂的网络环境,对实时监控和日志分析的需求变得日益迫切。本文将介绍如何使用Golang编写实时日志分析模块,以增强公司监控管理软件的日志监控功能。通过本文的指导,你将能够建立一个定制的实时日志分析系统,更好地监测和管理公司的网络活动。
219 0
|
5月前
|
消息中间件 监控 关系型数据库
134 日志监控告警系统案例(功能架构分析)
134 日志监控告警系统案例(功能架构分析)
70 0
|
8月前
|
Java API 数据安全/隐私保护
一张思维导图带你学会SpringBoot使用AOP实现日志管理功能
一张思维导图带你学会SpringBoot使用AOP实现日志管理功能
118 0
|
8月前
|
监控 数据可视化 安全
Baumer工业相机堡盟相机如何使用Trace功能(相机日志追踪的使用和优点以及行业应用)(C++)
Baumer工业相机堡盟相机如何使用Trace功能(相机日志追踪的使用和优点以及行业应用)(C++)
70 0