作为程序员一定要保持良好的睡眠,才能好编程

PHP-实现一个最精简的日志功能

发布时间:2018-11-19

  日志(Log)记录也是很重要的一种调试和监控手段。一般的原则是尽量要求多的存储日志,在查找问题的时候比较容易定位,特别是线上业务,没有记录日志,是不可想象的事情。

日志记录除了PHP解析级别的错误,更多是程序在执行过程中的一些错误,必须资源打开错误,文件不存在、没有权限等问题。所以务必尽量多的输出Log。


几个常用的的文件操作函数就可以完成日志的操作,比如说 fopen  、fwrite ,或者一步到位的file_put_contents() 函数。


为了节约磁盘IO操作,都可以放到一个对象,等对象析构的时候,再去执行物理写入操作。以减少对文件的多次操作,减少IO操作。从而提升PHP的性能。



下面就来看一个简单的日志操作类:

    

Log.php

class Log{


  const LOG_ERROR=1;
  const LOG_WARNING=2;
  const LOG_NOTICE=3;

  public static $message=[];
  public function __construct(){
    array_push(self::$message,"[".date('Y-m-d H:i:s')."] LOG LEVEL:".self::LOG_NOTICE."log init...");
  }


  public function error($log){

    $this->send($log,self::LOG_ERROR);
  
  }
  
  public function warning($log){
    $this->send($log,self::LOG_WARNING);
  }

  public function notice($log){
    $this->send($log,self::LOG_NOTICE);
  }


  private function send($log,$level){
    is_string($log)||$log=serialize($log);
    array_push(self::$message,"[".date('Y-m-d H:i:s')."] log Level:{$level}".$log);

  }
  
  
  public function __destruct(){

    if(count(self::$message)){
      file_put_contents('logs.log',implode("\n",self::$message),FILE_APPEND);
    }

  }


}


$log=new Log();



$log->notice('notice message');
$log->error('error message');
$log->warning('warning message');


$log->notice(['data'=>'123']);



日志记录结果:


[root@localhost php]# tailf logs.log 
log init...
[2018-11-19 15:05:04]log init...
[2018-11-19 15:06:00]log init...
[2018-11-19 15:06:00]this is test 
[2018-11-19 15:06:08]log init...
[2018-11-19 15:06:08]this is test 
[2018-11-19 15:33:39] LOG LEVEL:3log init...
[2018-11-19 15:33:39] log Level:3notice message
[2018-11-19 15:33:39] log Level:1error message
[2018-11-19 15:33:39] log Level:2warning message[2018-11-19 15:34:59] LOG LEVEL:3log init...
[2018-11-19 15:34:59] log Level:3notice message
[2018-11-19 15:34:59] log Level:1error message
[2018-11-19 15:34:59] log Level:2warning message
[2018-11-19 15:34:59] log Level:3a:1:{s:4:"data";s:3:"123";}^C