Home Backend Development PHP Tutorial php利用单例模式实现日志处理类库_php实例

php利用单例模式实现日志处理类库_php实例

Jun 07, 2016 pm 05:22 PM
Singleton pattern log Class library

对于现在的应用程序来说,日志的重要性是不言而喻的。很难想象没有任何日志记录功能的应用程序运行在生产环境中。日志所能提供的功能是多种多样的,包括记录程序运行时产生的错误信息、状态信息、调试信息和执行时间信息等。在生产环境中,日志是查找问题来源的重要依据。应用程序运行时的产生的各种信息,都应该通过日志类库来进行记录。

复制代码 代码如下:

/**
 * 日志处理类
 *
 * @since alpha 0.0.1
 * @date 2014.03.04
 * @author genialx
 *
 */

class Log{

    //单例模式
    private static $instance    = NULL;
    //文件句柄
    private static $handle      = NULL;
    //日志开关
    private $log_switch     = NULL;
    //日志相对目录
    private $log_file_path      = NULL;
    //日志文件最大长度,超出长度重新建立文件
    private $log_max_len        = NULL;
    //日志文件前缀,入 log_0
    private $log_file_pre       = 'log_';

        
    /**
     * 构造函数
     *
     * @since alpha 0.0.1
     * @date 2014.02.04
     * @author genialx
     */
    protected function __construct(){//注意:以下是配置文件中的常量,请读者自行更改

        $this->log_file_path     = LOG_FILE_PATH;

        $this->log_switch     = LOG_SWITCH; 

        $this->log_max_len    = LOG_MAX_LEN;

    }

    /**
     * 单利模式
     *
     * @since alpha 0.0.1
     * @date 2014.02.04
     * @author genialx
     */
    public static function get_instance(){
        if(!self::$instance instanceof self){
            self::$instance = new self;
        }
        return self::$instance;
    }

    /**
     *
     * 日志记录
     *
     * @param int $type  0 -> 记录(THING LOG) / 1 -> 错误(ERROR LOG)
     * @param string $desc
     * @param string $time
     *
     * @since alpha 0.0.1
     * @date 2014.02.04
     * @author genialx
     *
     */
    public function log($type,$desc,$time){
        if($this->log_switch){

            if(self::$handle == NULL){
                $filename = $this->log_file_pre . $this->get_max_log_file_suf();
                self::$handle = fopen($this->log_file_path . $filename, 'a');
            }
            switch($type){
                case 0:
                    fwrite(self::$handle, 'THING LOG:' . ' ' . $desc . ' ' . $time . chr(13));
                    break;
                case 1:
                    fwrite(self::$handle, 'ERROR LOG:' . ' ' . $desc . ' ' . $time . chr(13));
                    break;
                default:
                    fwrite(self::$handle, 'THING LOG:' . ' ' . $desc . ' ' . $time . chr(13));
                    break;
            }

        }
    }

    /**
     * 获取当前日志的最新文档的后缀
     *
     * @since alpha 0.0.1
     * @date 2014.02.04
     * @author genialx
     */
    private function get_max_log_file_suf(){
        $log_file_suf = null;
        if(is_dir($this->log_file_path)){
            if($dh = opendir($this->log_file_path)){
                while(($file = readdir($dh)) != FALSE){
                    if($file != '.' && $file != '..'){
                        if(filetype( $this->log_file_path . $file) == 'file'){
                            $rs = split('_', $file);
                            if($log_file_suf                                 $log_file_suf = $rs[1];
                            }
                        }
                    }
                }

                if($log_file_suf == NULL){
                    $log_file_suf = 0;
                }
                //截断文件
                if( file_exists($this->log_file_path . $this->log_file_pre . $log_file_suf) && filesize($this->log_file_path . $this->log_file_pre . $log_file_suf) >= $this->log_max_len){
                    $log_file_suf = intval($log_file_suf) + 1;
                }

                return $log_file_suf;
            }  
        }

        return 0;

    }

    /**
     * 关闭文件句柄
     *
     * @since alpha 0.0.1
     * @date 2014.02.04
     * @author genialx
     */
    public function close(){
        fclose(self::$handle);
    }
}

功能说明:
该日志类利用单例模式,节省资源。自行判断文件大小,超出指定大小则按序自行创建文件。如:文件log_0大于指定大小,则重新创建log_1文件(注意:创建文件是安装文件名后缀的数字的,请勿随意更改日志文件名)。

有待优化:没有指定文件的最大个数,所以定期要手动删除过多的日志文件。

调用示例:

复制代码 代码如下:

//LOG
$L = Log::get_instance();
//第一个参数 int 0代表事件记录(THING LOG:),1代表错误记录(ERROR LOG:)
//第二个参数 string 描述文字
//第三个参数 string 时间
$L->log(1,'日志描述', date('Y-n-j H:m:s'));
$L->close();
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
3 weeks 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)

What is event ID 6013 in win10? What is event ID 6013 in win10? Jan 09, 2024 am 10:09 AM

The logs of win10 can help users understand the system usage in detail. Many users must have encountered log 6013 when looking for their own management logs. So what does this code mean? Let’s introduce it below. What is win10 log 6013: 1. This is a normal log. The information in this log does not mean that your computer has been restarted, but it indicates how long the system has been running since the last startup. This log will appear once every day at 12 o'clock sharp. How to check how long the system has been running? You can enter systeminfo in cmd. There is one line in it.

Troubleshooting Event 7034 Error Log Issues in Win10 Troubleshooting Event 7034 Error Log Issues in Win10 Jan 11, 2024 pm 02:06 PM

The logs of win10 can help users understand the system usage in detail. Many users must have seen a lot of error logs when looking for their own management logs. So how to solve them? Let’s take a look below. . How to solve win10 log event 7034: 1. Click "Start" to open "Control Panel" 2. Find "Administrative Tools" 3. Click "Services" 4. Find HDZBCommServiceForV2.0, right-click "Stop Service" and change it to "Manual Start "

Detailed explanation of log viewing command in Linux system! Detailed explanation of log viewing command in Linux system! Mar 06, 2024 pm 03:55 PM

In Linux systems, you can use the following command to view the contents of the log file: tail command: The tail command is used to display the content at the end of the log file. It is a common command to view the latest log information. tail [option] [file name] Commonly used options include: -n: Specify the number of lines to be displayed, the default is 10 lines. -f: Monitor the file content in real time and automatically display the new content when the file is updated. Example: tail-n20logfile.txt#Display the last 20 lines of the logfile.txt file tail-flogfile.txt#Monitor the updated content of the logfile.txt file in real time head command: The head command is used to display the beginning of the log file

How to view your medication log history in the Health app on iPhone How to view your medication log history in the Health app on iPhone Nov 29, 2023 pm 08:46 PM

iPhone lets you add medications to the Health app to track and manage the medications, vitamins and supplements you take every day. You can then log medications you've taken or skipped when you receive a notification on your device. After you log your medications, you can see how often you took or skipped them to help you track your health. In this post, we will guide you to view the log history of selected medications in the Health app on iPhone. A short guide on how to view your medication log history in the Health App: Go to the Health App>Browse>Medications>Medications>Select a Medication>Options&a

Understand the meaning of event ID455 in win10 logs Understand the meaning of event ID455 in win10 logs Jan 12, 2024 pm 09:45 PM

The logs of win10 have a lot of rich content. Many users must have seen the event ID455 display error when looking for their own management logs. So what does it mean? Let’s take a look below. What is event ID455 in the win10 log: 1. ID455 is the error <error> that occurred in <file> when the information store opened the log file.

Different types of Linux log files and setting steps Different types of Linux log files and setting steps Feb 26, 2024 pm 10:54 PM

Types of Linux log files and configuration methods In Linux systems, log files are very important. They record the running status of the system, user operations, and the occurrence of various events. By checking log files, system administrators can discover problems in time and handle them accordingly. This article will introduce the common types of log files in Linux systems and how to configure logging. 1. Types of log files System log: System log is a log file that records the operating status of the system, including system startup, shutdown, service startup and stop, etc.

Performance optimization tips for logging mechanism in Java functions? Performance optimization tips for logging mechanism in Java functions? May 02, 2024 am 08:06 AM

Logging optimization tip: Disable debug logging to eliminate the impact. Batch log messages to reduce overhead. Use asynchronous logging to offload logging operations. Limit log file size to improve application startup and processing performance.

Use Java's logging framework to monitor system operation Use Java's logging framework to monitor system operation Nov 06, 2023 am 11:41 AM

In Java application development, monitoring the operation of the system is very important. By recording key information, exceptions, and performance indicators through the log framework, problems can be captured in a timely manner, troubleshooting can be performed, and system performance can be optimized. The following will introduce how to use Java's log framework to monitor system operation, and provide some practical skills and experience. 1. Choose a suitable log framework 1. Common log frameworks: Common Java log frameworks include Log4j, Logback and java.util.logging, etc. 2. Feature comparison: Different log frameworks have different characteristics. For example, Log4j has flexible configuration and rich output formats. Logback is the successor of Log4j and adopts more advanced

See all articles