• 售前

  • 售后

热门帖子
入门百科

tp5框架利用composer实现日记记录功能示例

[复制链接]
无奈的剑侠站 显示全部楼层 发表于 2021-10-26 13:20:58 |阅读模式 打印 上一主题 下一主题
本文实例讲述了tp5框架利用composer实现日记记录功能。分享给大家供大家参考,详细如下:
tp5实现日记记录
1.安装 psr/log
  1. composer require psr/log
复制代码
它的作用就是提供一套接口,实现正常的日记功能!
我们可以来细细的分析一下,LoggerInterface.php
  1. <?php
  2. namespace Psr\Log;
  3. /**
  4. * Describes a logger instance.
  5. *
  6. * The message MUST be a string or object implementing __toString().
  7. *
  8. * The message MAY contain placeholders in the form: {foo} where foo
  9. * will be replaced by the context data in key "foo".
  10. *
  11. * The context array can contain arbitrary data. The only assumption that
  12. * can be made by implementors is that if an Exception instance is given
  13. * to produce a stack trace, it MUST be in a key named "exception".
  14. *
  15. * See https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-3-logger-interface.md
  16. * for the full interface specification.
  17. */
  18. interface LoggerInterface
  19. {
  20.   /**
  21.    * System is unusable.
  22.    *
  23.    * @param string $message
  24.    * @param array $context
  25.    *
  26.    * @return void
  27.    */
  28.   public function emergency($message, array $context = array());
  29.   /**
  30.    * Action must be taken immediately.
  31.    *
  32.    * Example: Entire website down, database unavailable, etc. This should
  33.    * trigger the SMS alerts and wake you up.
  34.    *
  35.    * @param string $message
  36.    * @param array $context
  37.    *
  38.    * @return void
  39.    */
  40.   public function alert($message, array $context = array());
  41.   /**
  42.    * Critical conditions.
  43.    *
  44.    * Example: Application component unavailable, unexpected exception.
  45.    *
  46.    * @param string $message
  47.    * @param array $context
  48.    *
  49.    * @return void
  50.    */
  51.   public function critical($message, array $context = array());
  52.   /**
  53.    * Runtime errors that do not require immediate action but should typically
  54.    * be logged and monitored.
  55.    *
  56.    * @param string $message
  57.    * @param array $context
  58.    *
  59.    * @return void
  60.    */
  61.   public function error($message, array $context = array());
  62.   /**
  63.    * Exceptional occurrences that are not errors.
  64.    *
  65.    * Example: Use of deprecated APIs, poor use of an API, undesirable things
  66.    * that are not necessarily wrong.
  67.    *
  68.    * @param string $message
  69.    * @param array $context
  70.    *
  71.    * @return void
  72.    */
  73.   public function warning($message, array $context = array());
  74.   /**
  75.    * Normal but significant events.
  76.    *
  77.    * @param string $message
  78.    * @param array $context
  79.    *
  80.    * @return void
  81.    */
  82.   public function notice($message, array $context = array());
  83.   /**
  84.    * Interesting events.
  85.    *
  86.    * Example: User logs in, SQL logs.
  87.    *
  88.    * @param string $message
  89.    * @param array $context
  90.    *
  91.    * @return void
  92.    */
  93.   public function info($message, array $context = array());
  94.   /**
  95.    * Detailed debug information.
  96.    *
  97.    * @param string $message
  98.    * @param array $context
  99.    *
  100.    * @return void
  101.    */
  102.   public function debug($message, array $context = array());
  103.   /**
  104.    * Logs with an arbitrary level.
  105.    *
  106.    * @param mixed $level
  107.    * @param string $message
  108.    * @param array $context
  109.    *
  110.    * @return void
  111.    */
  112.   public function log($level, $message, array $context = array());
  113. }
复制代码
这是一套日记正常的接口,有层级,有消息,有详细的内容。
LogLevel.php
  1. <?php
  2. namespace Psr\Log;
  3. /**
  4. * Describes log levels.
  5. */
  6. class LogLevel
  7. {
  8.   const EMERGENCY = 'emergency';
  9.   const ALERT   = 'alert';
  10.   const CRITICAL = 'critical';
  11.   const ERROR   = 'error';
  12.   const WARNING  = 'warning';
  13.   const NOTICE  = 'notice';
  14.   const INFO   = 'info';
  15.   const DEBUG   = 'debug';
  16. }
复制代码
界说一些错误常量。
AbstractLogger.php实现接口
  1. <?php
  2. namespace Psr\Log;
  3. /**
  4. * This is a simple Logger implementation that other Loggers can inherit from.
  5. *
  6. * It simply delegates all log-level-specific methods to the `log` method to
  7. * reduce boilerplate code that a simple Logger that does the same thing with
  8. * messages regardless of the error level has to implement.
  9. */
  10. abstract class AbstractLogger implements LoggerInterface
  11. {
  12.   /**
  13.    * System is unusable.
  14.    *
  15.    * @param string $message
  16.    * @param array $context
  17.    *
  18.    * @return void
  19.    */
  20.   public function emergency($message, array $context = array())
  21.   {
  22.     $this->log(LogLevel::EMERGENCY, $message, $context);
  23.   }
  24.   /**
  25.    * Action must be taken immediately.
  26.    *
  27.    * Example: Entire website down, database unavailable, etc. This should
  28.    * trigger the SMS alerts and wake you up.
  29.    *
  30.    * @param string $message
  31.    * @param array $context
  32.    *
  33.    * @return void
  34.    */
  35.   public function alert($message, array $context = array())
  36.   {
  37.     $this->log(LogLevel::ALERT, $message, $context);
  38.   }
  39.   /**
  40.    * Critical conditions.
  41.    *
  42.    * Example: Application component unavailable, unexpected exception.
  43.    *
  44.    * @param string $message
  45.    * @param array $context
  46.    *
  47.    * @return void
  48.    */
  49.   public function critical($message, array $context = array())
  50.   {
  51.     $this->log(LogLevel::CRITICAL, $message, $context);
  52.   }
  53.   /**
  54.    * Runtime errors that do not require immediate action but should typically
  55.    * be logged and monitored.
  56.    *
  57.    * @param string $message
  58.    * @param array $context
  59.    *
  60.    * @return void
  61.    */
  62.   public function error($message, array $context = array())
  63.   {
  64.     $this->log(LogLevel::ERROR, $message, $context);
  65.   }
  66.   /**
  67.    * Exceptional occurrences that are not errors.
  68.    *
  69.    * Example: Use of deprecated APIs, poor use of an API, undesirable things
  70.    * that are not necessarily wrong.
  71.    *
  72.    * @param string $message
  73.    * @param array $context
  74.    *
  75.    * @return void
  76.    */
  77.   public function warning($message, array $context = array())
  78.   {
  79.     $this->log(LogLevel::WARNING, $message, $context);
  80.   }
  81.   /**
  82.    * Normal but significant events.
  83.    *
  84.    * @param string $message
  85.    * @param array $context
  86.    *
  87.    * @return void
  88.    */
  89.   public function notice($message, array $context = array())
  90.   {
  91.     $this->log(LogLevel::NOTICE, $message, $context);
  92.   }
  93.   /**
  94.    * Interesting events.
  95.    *
  96.    * Example: User logs in, SQL logs.
  97.    *
  98.    * @param string $message
  99.    * @param array $context
  100.    *
  101.    * @return void
  102.    */
  103.   public function info($message, array $context = array())
  104.   {
  105.     $this->log(LogLevel::INFO, $message, $context);
  106.   }
  107.   /**
  108.    * Detailed debug information.
  109.    *
  110.    * @param string $message
  111.    * @param array $context
  112.    *
  113.    * @return void
  114.    */
  115.   public function debug($message, array $context = array())
  116.   {
  117.     $this->log(LogLevel::DEBUG, $message, $context);
  118.   }
  119. }
复制代码
Logger.php继续AbstractLogger.php
  1. <?php
  2. namespace Psr\Log;
  3. use app\index\model\LogModel;
  4. /**
  5. * This Logger can be used to avoid conditional log calls.
  6. *
  7. * Logging should always be optional, and if no logger is provided to your
  8. * library creating a NullLogger instance to have something to throw logs at
  9. * is a good way to avoid littering your code with `if ($this->logger) { }`
  10. * blocks.
  11. */
  12. class Logger extends AbstractLogger
  13. {
  14.   /**
  15.    * Logs with an arbitrary level.
  16.    *
  17.    * @param mixed $level
  18.    * @param string $message
  19.    * @param array $context
  20.    *
  21.    * @return void
  22.    */
  23.   public function log($level, $message, array $context = array())
  24.   {
  25.     // noop
  26.     $logModel = new LogModel();
  27.     $logModel->add($level,$message,json_encode($context));
  28.     echo $logModel->id;
  29.   }
  30. }
复制代码
这内里的log方法是我自己写的!!!
我们需要把日记存储到数据库中!!!
这里我设计了一个log表,包含id、level、message、 context、ip、url、create_on等。
我创建了一个LogModel.php
  1. <?php
  2. /**
  3. * @author: jim
  4. * @date: 2017/11/16
  5. */
  6. namespace app\index\model;
  7. use think\Model;
  8. /**
  9. * Class LogModel
  10. * @package app\index\model
  11. *
  12. * 继承Model之后,就可以使用继承它的属性和方法
  13. *
  14. */
  15. class LogModel extends Model
  16. {
  17.   protected $pk = 'id'; // 配置主键
  18.   protected $table = 'log'; // 默认的表名是log_model
  19.   public function add($level = "error",$message = "出错啦",$context = "") {
  20.     $this->data([
  21.       'level' => $level,
  22.       'message' => $message,
  23.       'context' => $context,
  24.       'ip' => getIp(),
  25.       'url' => getUrl(),
  26.       'create_on' => date('Y-m-d H:i:s',time())
  27.     ]);
  28.     $this->save();
  29.     return $this->id;
  30.   }
  31. }
复制代码
统统都准备好了,可以在控制器中利用了!
  1. <?php
  2. namespace app\index\controller;
  3. use think\Controller;
  4. use Psr\Log\Logger;
  5. class Index extends Controller
  6. {
  7.   public function index()
  8.   {
  9.     $logger = new Logger();
  10.     $context = array();
  11.     $context['err'] = "缺少参数id";
  12.     $logger->info("有新消息");
  13.   }
  14.   public function _empty() {
  15.     return "empty";
  16.   }
  17. }
复制代码
小结:
composer很好很强大!
这里是接口Interface的典型案例,界说接口,界说抽象类,界说详细类。
有了命名空间,可以很好的引用不同文件夹下的库!
互相利用,能够防止高内聚!即便是耦合也相对比力独立!
有了这个日记小工具,平常接口的一些报错信息就能很好的捕获了!
只要
  1. use Psr\Log\Logger;
复制代码
然后
  1. $logger = new Logger();
  2. $logger->info("info信息");
复制代码
利用非常方便!!!
附上获取ip、获取url的方法。
  1. //获取用户真实IP
  2. function getIp() {
  3.   if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
  4.     $ip = getenv("HTTP_CLIENT_IP");
  5.   else
  6.     if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
  7.       $ip = getenv("HTTP_X_FORWARDED_FOR");
  8.     else
  9.       if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
  10.         $ip = getenv("REMOTE_ADDR");
  11.       else
  12.         if (isset ($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
  13.           $ip = $_SERVER['REMOTE_ADDR'];
  14.         else
  15.           $ip = "unknown";
  16.   return ($ip);
  17. }
  18. // 获取url
  19. function getUrl() {
  20.   return 'http://'.$_SERVER['SERVER_NAME'].':'.$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
  21. }
复制代码
更多关于thinkPHP相关内容感爱好的读者可检察本站专题:《ThinkPHP入门教程》、《thinkPHP模板操作技巧总结》、《ThinkPHP常用方法总结》、《codeigniter入门教程》、《CI(CodeIgniter)框架进阶教程》、《Zend FrameWork框架入门教程》及《PHP模板技能总结》。
盼望本文所述对大家基于ThinkPHP框架的PHP步伐设计有所帮助。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有帐号?立即注册

x

帖子地址: 

回复

使用道具 举报

分享
推广
火星云矿 | 预约S19Pro,享500抵1000!
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

草根技术分享(草根吧)是全球知名中文IT技术交流平台,创建于2021年,包含原创博客、精品问答、职业培训、技术社区、资源下载等产品服务,提供原创、优质、完整内容的专业IT技术开发社区。
  • 官方手机版

  • 微信公众号

  • 商务合作