Home Backend Development PHP Tutorial PHP 日志工具类

PHP 日志工具类

Jun 20, 2016 pm 12:32 PM

好久没写php了,突然做个实验,发现竟然没有日志,哎

<?phpdefined('API') or exit('Access Denied');class Log{    private $FilePath;    private $FileName;    private $m_MaxLogFileNum;    private $m_RotaType;    private $m_RotaParam;    private $m_InitOk;    private $m_Priority;    private $m_LogCount;            const EMERG  = 0;    const FATAL  = 0;    const ALERT  = 100;    const CRIT   = 200;    const ERROR  = 300;    const WARN   = 400;    const NOTICE = 500;    const INFO   = 600;    const DEBUG  = 700;    const LOG_SUFFIXED = ".log.txt";     const DEFAULT_ROTE = 5242880;    /**     * @abstract 初始化     * @param String $dir 文件路径     * @param String $filename 文件名     * @return      */    public function __construct($dir, $filename, $priority = Log::INFO, $maxlogfilenum = 3, $rotatype = 1, $rotaparam = LOG::DEFAULT_ROTE)    {        $dot_offset = strpos($filename, ".");        if ($dot_offset !== false)            $this->FileName = substr($filename,0, $dot_offset);        else            $this->FileName = $filename;        $this->FilePath = $dir;        $this->m_MaxLogFileNum = intval($maxlogfilenum);        $this->m_RotaParam = intval($rotaparam);        $this->m_RotaType = intval($rotatype);        $this->m_Priority = intval($priority);        $this->m_LogCount = 0;        $this->m_InitOk = $this->InitDir();        umask(0000);         $path=$this->createPath($this->FilePath,$this->FileName);        if(!$this->isExist($path))        {            if(!$this->createDir($this->FilePath))            {                #echo("创建目录失败!");            }            if(!$this->createLogFile($path)){                #echo("创建文件失败!");            }        }    }                private function createPath($dir,$file)    {                $file = fopen($dir.DIRECTORY_SEPARATOR.$file,'w');        if($file)        {          fclose($file);        }                return $dir.DIRECTORY_SEPARATOR.$file;    }        private function InitDir()    {        if (is_dir($this->FilePath) === false)        {            if(!$this->createDir($this->FilePath))            {                //echo("创建目录失败!");                //throw exception                return false;            }        }        return true;    }  function console($priority, $log)      {          if ($this->m_InitOk == false)              return;          if ($priority > $this->m_Priority)              return;          $path = $this->getLogFilePath($this->FilePath, $this->FileName).Log::LOG_SUFFIXED;          $handle= fopen($path,"a+");          if ($handle === false)          {              return;          }                  $datestr = strftime("%Y-%m-%d %H:%M:%S ");          $caller_info = $this->get_caller_info();                 $status = fwrite($handle, $caller_info.$datestr.$log."\n");        if(!$status){//写日志失败              echo("写入日志失败");          }          fclose($handle);          $this->RotaLog();      }      /**     * @abstract 写入日志     * @param String $log 内容     */    function setLog($log)    {        $this->console(Log::NOTICE, $log);    }    function LogDebug($log)    {        $this->console(Log::DEBUG, $log);    }    function LogError($log)    {        $this->console(Log::ERROR, $log);    }    function LogNotice($log)    {        $this->console(Log::NOTICE, $log);    }       private function get_caller_info()    {    	$ret = debug_backtrace();    	foreach ($ret as $item)    	{    		if(isset($item['class']) && 'Logs' == $item['class'])    		{    			continue;    		}    		$file_name = basename($item['file']);    		return <<<S        {$file_name}:{$item['line']}  S;    	}    }    private function RotaLog()    {        $file_path = $this->getLogFilePath($this->FilePath, $this->FileName).LOG::LOG_SUFFIXED;        if ($this->m_LogCount%10==0)            clearstatcache();        ++$this->m_LogCount;        $file_stat_info = stat($file_path);        if ($file_stat_info === FALSE)            return;        if ($this->m_RotaType != 1)            return;             //echo "file: ".$file_path." vs ".$this->m_RotaParam."\n";        if ($file_stat_info['size'] < $this->m_RotaParam)            return;        $raw_file_path = $this->getLogFilePath($this->FilePath, $this->FileName);        $file_path = $raw_file_path.($this->m_MaxLogFileNum - 1).LOG::LOG_SUFFIXED;        //echo "lastest file:".$file_path."\n";        if ($this->isExist($file_path))        {            unlink($file_path);        }        for ($i = $this->m_MaxLogFileNum - 2; $i >= 0; $i--)        {            if ($i == 0)                $file_path = $raw_file_path.LOG::LOG_SUFFIXED;            else                $file_path = $raw_file_path.$i.LOG::LOG_SUFFIXED;            if ($this->isExist($file_path))            {                $new_file_path = $raw_file_path.($i+1).LOG::LOG_SUFFIXED;                if (rename($file_path, $new_file_path) < 0)                {                    continue;                }            }        }    }    function isExist($path){        return file_exists($path);    }    /**     * @abstract 创建目录     * @param <type> $dir 目录名     * @return bool     */    function createDir($dir){        //判断目录是否存在        return is_dir($dir) or ($this->createDir(dirname($dir)) and mkdir($dir, 0777));    }    /**     * @abstract 创建日志文件     * @param String $path     * @return bool     */    function createLogFile($path){        $handle=fopen($path,"w"); //创建文件        if($handle)        {        fclose($handle);        }        return $this->isExist($path);    }    /**     * @abstract 创建路径     * @param String $dir 目录名     * @param String $filename      */    function getLogFilePath($dir,$filename){        return $dir."/".$filename;    }}?>
Copy after login


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Customizing/Extending Frameworks: How to add custom functionality. Customizing/Extending Frameworks: How to add custom functionality. Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

What exactly is the non-blocking feature of ReactPHP? How to handle its blocking I/O operations? What exactly is the non-blocking feature of ReactPHP? How to handle its blocking I/O operations? Apr 01, 2025 pm 03:09 PM

An official introduction to the non-blocking feature of ReactPHP in-depth interpretation of ReactPHP's non-blocking feature has aroused many developers' questions: "ReactPHPisnon-blockingbydefault...

See all articles