Home Backend Development PHP Tutorial A PHP log class for debuging

A PHP log class for debuging

Jun 23, 2016 pm 01:30 PM

分享一个我自己用的在 WordPress 开发中用得到的一个调试日志类。

<?php/** * @author: suifengtec coolwp.com * @date:   2013-02-03 09:55:55 * @last Modified by:   suifengtec coolwp.com * @last Modified time: 2015-07-12 18:40:02 */if(function_exists('add_action')){    defined('ABSPATH') or exit;}if(!class_exists('CoolWP_com_Log')){    final class CoolWP_com_Log{        private $dir = null;        private $debug_file_name = null;        private $f_path = null;        public function __clone() {            _doing_it_wrong( __FUNCTION__, 'Cheatin&#8217; huh?', '0.9.0' );        }        public function __wakeup() {            _doing_it_wrong( __FUNCTION__, 'Cheatin&#8217; huh?', '0.9.0' );        }        public function __construct($main_file=''){            $main_file = (''==$main_file)?__FILE__:$main_file;            $this->dir = dirname($main_file).DIRECTORY_SEPARATOR.'debug'.DIRECTORY_SEPARATOR;            $file_name = 'debug_'.md5($main_file).'.log';            $this->debug_file_name = (function_exists('apply_filters'))?apply_filters('cwp_debug_log_file_name',$file_name).'.log':$file_name.'.log';            $this->f_path = $this->dir.$this->debug_file_name;            $this->check_log_file();         }        /**         * adding log item         * @param string $text : adding content         */        public function  add($text) {            date_default_timezone_set('Asia/Shanghai');            if(is_array($text)||is_obeject($text)){                $text = json_encode($text);            }            $fp = fopen( $this->f_path,"a");            flock($fp, LOCK_EX) ;            fwrite($fp,"".date("Y-m-d H:i:s",time())."\n".$text."\n\n");            flock($fp, LOCK_UN);            fclose($fp);            //return true;            //        }        /**         * checking the log file and path.         * @return null         */        private function check_log_file(){            $is_dir = is_dir($this->dir);            $is_file = file_exists($this->f_path);            if($is_dir && $is_file) return;            if(!$is_dir||!$is_file){                if(!$is_dir){                    $md = mkdir($this->dir,0777,true);                }                if(!$is_file){                    $fp = fopen( $this->f_path,"a");                      fclose($fp);                 }            }        }    }/*//CLASS*/}/*ALL DONE.*/?>

以 WordPress 插件为例的用例:
在插件主文件的适当位置加入(假如上述代码放置在class-coolwp-debug-log.php文件中):

$this->is_debug = true;if($this->is_debug){    require_once( plugin_dir_path(__FILE__).'classes/class-coolwp-debug-log.php');    $this->Log = new CoolWP_com_Log();}

如果在插件主文件中将__FILE__定义为常量 SOMEONE_THIS,那么,可以将SOMEONE_THIS 作为参数传给CoolWP_com_Log(),例如:

$this->Log = new CoolWP_com_Log(SOMEONE_THIS);

传不传参数的区别是日志文件的位置不同,如果不传参数,日志文件位于class-coolwp-debug-log.php所在目录下的debug目录下;如果传递了SOMEONE_THIS参数,那么,日志文件位于插件主目录下的debug目录下。日志文件的文件名称为debug_*******log。

日志条目默认采用北京时间。

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

Undress AI Tool

Undress AI Tool

Undress images for free

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.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Hot Topics

PHP Tutorial
1596
276
Object-Relational Mapping (ORM) Performance Tuning in PHP Object-Relational Mapping (ORM) Performance Tuning in PHP Jul 29, 2025 am 05:00 AM

Avoid N 1 query problems, reduce the number of database queries by loading associated data in advance; 2. Select only the required fields to avoid loading complete entities to save memory and bandwidth; 3. Use cache strategies reasonably, such as Doctrine's secondary cache or Redis cache high-frequency query results; 4. Optimize the entity life cycle and call clear() regularly to free up memory to prevent memory overflow; 5. Ensure that the database index exists and analyze the generated SQL statements to avoid inefficient queries; 6. Disable automatic change tracking in scenarios where changes are not required, and use arrays or lightweight modes to improve performance. Correct use of ORM requires combining SQL monitoring, caching, batch processing and appropriate optimization to ensure application performance while maintaining development efficiency.

Building Immutable Objects in PHP with Readonly Properties Building Immutable Objects in PHP with Readonly Properties Jul 30, 2025 am 05:40 AM

ReadonlypropertiesinPHP8.2canonlybeassignedonceintheconstructororatdeclarationandcannotbemodifiedafterward,enforcingimmutabilityatthelanguagelevel.2.Toachievedeepimmutability,wrapmutabletypeslikearraysinArrayObjectorusecustomimmutablecollectionssucha

The Serverless Revolution: Deploying Scalable PHP Applications with Bref The Serverless Revolution: Deploying Scalable PHP Applications with Bref Jul 28, 2025 am 04:39 AM

Bref enables PHP developers to build scalable, cost-effective applications without managing servers. 1.Bref brings PHP to AWSLambda by providing an optimized PHP runtime layer, supports PHP8.3 and other versions, and seamlessly integrates with frameworks such as Laravel and Symfony; 2. The deployment steps include: installing Bref using Composer, configuring serverless.yml to define functions and events, such as HTTP endpoints and Artisan commands; 3. Execute serverlessdeploy command to complete the deployment, automatically configure APIGateway and generate access URLs; 4. For Lambda restrictions, Bref provides solutions.

A Deep Dive into PHP's Internal Garbage Collection Mechanism A Deep Dive into PHP's Internal Garbage Collection Mechanism Jul 28, 2025 am 04:44 AM

PHP's garbage collection mechanism is based on reference counting, but circular references need to be processed by a periodic circular garbage collector; 1. Reference count releases memory immediately when there is no reference to the variable; 2. Reference reference causes memory to be unable to be automatically released, and it depends on GC to detect and clean it; 3. GC is triggered when the "possible root" zval reaches the threshold or manually calls gc_collect_cycles(); 4. Long-term running PHP applications should monitor gc_status() and call gc_collect_cycles() in time to avoid memory leakage; 5. Best practices include avoiding circular references, using gc_disable() to optimize performance key areas, and dereference objects through the ORM's clear() method.

Integrating PHP with Machine Learning Models Integrating PHP with Machine Learning Models Jul 28, 2025 am 04:37 AM

UseaRESTAPItobridgePHPandMLmodelsbyrunningthemodelinPythonviaFlaskorFastAPIandcallingitfromPHPusingcURLorGuzzle.2.RunPythonscriptsdirectlyfromPHPusingexec()orshell_exec()forsimple,low-trafficusecases,thoughthisapproachhassecurityandperformancelimitat

Handling Cryptocurrency Calculations: Why BCMath is Essential in PHP Handling Cryptocurrency Calculations: Why BCMath is Essential in PHP Aug 01, 2025 am 07:48 AM

BCMathisessentialforaccuratecryptocurrencycalculationsinPHPbecausefloating-pointarithmeticintroducesunacceptableroundingerrors.1.Floating-pointnumberslike0.1 0.2yieldimpreciseresults(e.g.,0.30000000000000004),whichisproblematicincryptowhereprecisionu

Understanding Constant Expression Evaluation in PHP's Engine Understanding Constant Expression Evaluation in PHP's Engine Jul 29, 2025 am 05:02 AM

PHPevaluatesconstantexpressionsatcompiletimetoimproveperformanceandenableearlyerrordetection.1.Constantexpressionevaluationmeanscomputingvaluesduringcompilationwhenalloperandsareknownconstantslikeliterals,classconstants,orpredefinedconstants.2.PHP’se

Strings as Value Objects: A Modern Approach to Domain-Specific String Types Strings as Value Objects: A Modern Approach to Domain-Specific String Types Aug 01, 2025 am 07:48 AM

Rawstringsindomain-drivenapplicationsshouldbereplacedwithvalueobjectstopreventbugsandimprovetypesafety;1.Usingrawstringsleadstoprimitiveobsession,whereinterchangeablestringtypescancausesubtlebugslikeargumentswapping;2.ValueobjectssuchasEmailAddressen

See all articles