当前位置: 首页 > 编程文章 >

ThinkPHP 5 基于 Composer 和 PSR-3 实现自定义日志记录

ThinkPHP 5 基于 Composer 和 PSR-3 实现自定义日志记录

作者:顾澄时间:2025-06-17 13:23:14浏览:114

本文介绍在 ThinkPHP 5 框架中,通过 Composer 安装 psr/log 依赖来实现标准化的日志记录功能。利用 PSR-3 接口规范,定义包含 id、level、message、context、ip、url 等字段的日志表结构,并创建对应的 Model 将日志数据持久化至数据库。该方法有效捕捉接口报错信息,便于后续排查与分析。

本文目录展开

ThinkPHP 5 日志记录实现方案

本示例演示如何在 ThinkPHP 5 框架中借助 Composer 完成日志记录功能的配置与实现,供开发者参考实践。

ThinkPHP 5 日志记录实现方案

第一步:安装 psr/log 组件


composer require psr/log

该组件的核心作用是提供一套标准的日志接口规范,从而支持常规的日志记录行为。

接下来深入分析 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";
  }
}

总结:

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"];
}

希望本文所述对大家基于 ThinkPHP 框架的 PHP 程序设计有所帮助。

上一篇
VBScript版的PHP extract()函数

本文介绍在ASP/VBScript环境中模拟PHP extract()函数的实现思路,将字典或集合转换为可访问的对象属性。通过自定义extract函数,支持指定必需字段、添加前缀及回调过滤,结合hasattr_和getattr_方法解决属性缺失报错问题,简化表单参数处理逻辑。

下一篇
MySQL分页使用limit+orderby出现数据重复问题的分析与解决

在 MySQL 5.6 及以上版本中,使用 LIMIT 配合 ORDER BY 进行分页查询时,若排序字段存在相同值,第二页可能出现与第一页重复的记录。这是由于优化器引入了 priority queue 机制,采用不稳定的堆排序算法导致顺序不确定。通过为排序字段添加索引或增加唯一主键作为次要排序条件,可有效规避该问题。

相关文章

更多
ThinkPHP项目中自定义日志记录功能的实现

本文介绍在ThinkPHP开发中通过自定义函数实现操作日志记录的方法。首先创建包含用户、动作及请求参数的日志数据表,随后在Common/common.php中定义获取数据库配置、连接MySQL并执行INSERT语句的addOperationLog函数,最后在其他控制器中直接调用该函数完成日志写入。

2026.04.09 868
ThinkPHP框架安装Composer扩展包全流程指南

本文梳理在ThinkPHP框架中安装Composer扩展包的完整流程。首先需确保PHP环境移除了putenv禁用函数,接着配置国内镜像源以加速下载。文中详细列举了查看版本、升级、切换1.x/2.x版本、更新插件及配置镜像等常用Composer命令,并解释了关联包机制对移除操作的影响。针对更新时出现的版本不匹配或插件丢失问题,提供了删除lock文件和vendor目录并忽略平台要求的解决方案,帮助开发者高效管理项目依赖。

2026.08.18 509
Composer安装配置及TP框架部署指南

本文介绍在Windows环境下使用PHPstudy安装Composer的具体步骤。主要内容包括配置PHP根目录环境变量、启用OpenSSL扩展、通过命令行执行全局安装脚本,以及配置国内镜像源以提升下载速度。此外,还简述了如何利用Composer快速创建和安装ThinkPHP框架项目。

2026.07.17 418
ThinkPHP调试模式开启与日志记录配置详解

在ThinkPHP项目开发中,掌握调试模式与日志记录功能至关重要。通过修改config.php中的'APP_DEBUG'参数可开启调试状态,页面将显示运行时间、内存开销等详细Trace信息。开发者还可自定义trace.php文件或使用$this->trace()方法定制页面底部提示。此外,启用LOG_RECORD并配置级别后,系统会自动记录EMERG至SQL级别的日志,配合getLastSql()等方法可有效排查数据库问题。

2025.08.19 207
Windows环境下使用Composer安装ThinkPHP5完整指南

本文详细介绍在Windows环境下如何利用Composer工具快速安装ThinkPHP5框架。内容涵盖镜像配置、项目创建命令执行、目录结构确认以及本地服务启动访问全流程,帮助开发者高效完成开发环境搭建。

2025.04.18 140
ThinkPHP 3集成阿里云OSS对象存储完整指南

本文介绍在ThinkPHP 3框架中集成阿里云对象存储(OSS)的具体步骤。内容涵盖从阿里云控制台开通服务并获取Access Key,到通过Composer安装OSS PHP SDK,再到修改配置文件及编写实例化函数和控制器调用代码的完整流程,帮助开发者快速实现文件上传与管理功能。

2025.03.10 131

专题推荐

更多
PHP 类与对象定义及继承

先看类声明、对象实例与属性访问。理解对象的创建和销毁后,再读继承、方法重载和关键字对照。已有代码遇到继承行为差异时,可进一步查看 final 方法与反射实例。

PHP 定时任务配置与运行

先确定任务运行间隔以及是否允许重叠。固定时间触发先看 Cron 案例,框架内和常驻服务再读对应示例。

Yii2 队列配置与常驻运行

先用一个最小任务跑通入队和消费,再检查 Web 与 Console 是否加载了相同的队列配置。确认命令能手动运行后再配置 Supervisor,最后验证进程重启时的处理情况。

PHP Session 过期时间设置方法

浏览器关闭、服务端回收和业务规定的闲置超时,可能在不同时间发生。对照配置项与应用层时间戳的做法,检查会话何时仍可读、何时应要求重新登录。

PHP URL 编码和解码方法

URL 路径片段和查询参数对空格的处理方式不同。先比较 urlencode 与 rawurlencode,再沿解码过程核对中文、加号和百分号,检查地址是否被重复编码或提前解码。

在线工具箱

更多
键码查询
键码查询

按下键盘按键时查看浏览器记录的键名和事件信息。

.env 配置检查
.env 配置检查

本地检查 .env 键值语法、引号、重复键及空值,预览解析结果,辅助排查 PHP 和 Laravel 环境配置。

进制转换
进制转换

转换二进制、十进制、十六进制等数值表示,辅助程序调试与进制学习。

HTML 标签安全清理
HTML 标签安全清理

清理 HTML 片段中的标签或危险内容,辅助整理待展示的文本。

文件 Base64 转换
文件 Base64 转换

把文件转为 Base64 文本,也可将编码内容还原为文件,方便接口传输与调试。