search
HomeBackend DevelopmentPHP TutorialPHP implements log processing class library_PHP tutorial

Following the previous article [Micro-e-commerce website developed by WeChat] one of the technical notes , yesterday we implemented the log processing function.

For today’s applications, the importance of logs is self-evident. It's hard to imagine an application running in a production environment without any logging capabilities. The functions that logs can provide are diverse, including recording error information, status information, debugging information and execution time information generated when the program is running. In a production environment, logs are an important basis for finding the source of problems. Various information generated when the application is running should be recorded through the log library .

Without further ado, here is the source code of the log library:

<span   1</span> <span /*</span><span *
</span><span   2</span> <span  * 日志处理类
</span><span   3</span> <span  * 
</span><span   4</span> <span  * @since alpha 0.0.1
</span><span   5</span> <span  * @date 2014.03.04
</span><span   6</span> <span  * @author genialx
</span><span   7</span> <span  * 
</span><span   8</span>  <span */</span>
<span   9</span>  
<span  10</span> <span class</span> <span Log</span><span {
</span><span  11</span>      
<span  12</span>     <span //</span><span 单例模式</span>
<span  13</span>     <span private</span> <span static</span> <span $instance</span>    = <span NULL</span><span ;
</span><span  14</span>     <span //</span><span 文件句柄</span>
<span  15</span>     <span private</span> <span static</span> <span $handle</span>      = <span NULL</span><span ;
</span><span  16</span>     <span //</span><span 日志开关</span>
<span  17</span>     <span private</span> <span $log_switch</span>     = <span NULL</span><span ;
</span><span  18</span>     <span //</span><span 日志相对目录</span>
<span  19</span>     <span private</span> <span $log_file_path</span>      = <span NULL</span><span ;
</span><span  20</span>     <span //</span><span 日志文件最大长度,超出长度重新建立文件</span>
<span  21</span>     <span private</span> <span $log_max_len</span>        = <span NULL</span><span ;
</span><span  22</span>     <span //</span><span 日志文件前缀,入 log_0</span>
<span  23</span>     <span private</span> <span $log_file_pre</span>       = 'log_'<span ;
</span><span  24</span>  
<span  25</span>          
<span  26</span>     <span /*</span><span *
</span><span  27</span> <span      * 构造函数
</span><span  28</span> <span      * 
</span><span  29</span> <span      * @since alpha 0.0.1
</span><span  30</span> <span      * @date 2014.02.04
</span><span  31</span> <span      * @author genialx
</span><span  32</span>      <span */</span>
<span  33</span>     <span protected</span> <span function</span> __construct(){<span //</span><span 注意:以下是配置文件中的常量,请读者自行更改</span>
<span  34</span>          
<span  35</span>         <span $this</span>->log_file_path     =<span  LOG_FILE_PATH;
</span><span  36</span>          
<span  37</span>         <span $this</span>->log_switch     =<span  LOG_SWITCH;  
</span><span  38</span>      
<span  39</span>         <span $this</span>->log_max_len    =<span  LOG_MAX_LEN;
</span><span  40</span>      
<span  41</span> <span     }
</span><span  42</span>      
<span  43</span>     <span /*</span><span *
</span><span  44</span> <span      * 单利模式
</span><span  45</span> <span      * 
</span><span  46</span> <span      * @since alpha 0.0.1
</span><span  47</span> <span      * @date 2014.02.04
</span><span  48</span> <span      * @author genialx
</span><span  49</span>      <span */</span>
<span  50</span>     <span public</span> <span static</span> <span function</span><span  get_instance(){
</span><span  51</span>         <span if</span>(!self::<span $instance</span><span  instanceof self){
</span><span  52</span>             self::<span $instance</span> = <span new</span><span  self;
</span><span  53</span> <span         }
</span><span  54</span>         <span return</span> self::<span $instance</span><span ;
</span><span  55</span> <span     }
</span><span  56</span>      
<span  57</span>     <span /*</span><span *
</span><span  58</span> <span      * 
</span><span  59</span> <span      * 日志记录
</span><span  60</span> <span      * 
</span><span  61</span> <span      * @param int $type  0 -> 记录(THING LOG) / 1 -> 错误(ERROR LOG)
</span><span  62</span> <span      * @param string $desc
</span><span  63</span> <span      * @param string $time
</span><span  64</span> <span      * 
</span><span  65</span> <span      * @since alpha 0.0.1
</span><span  66</span> <span      * @date 2014.02.04
</span><span  67</span> <span      * @author genialx
</span><span  68</span> <span      * 
</span><span  69</span>      <span */</span>
<span  70</span>     <span public</span> <span function</span> <span log</span>(<span $type</span>,<span $desc</span>,<span $time</span><span ){
</span><span  71</span>         <span if</span>(<span $this</span>-><span log_switch){
</span><span  72</span>              
<span  73</span>             <span if</span>(self::<span $handle</span> == <span NULL</span><span ){
</span><span  74</span>                 <span $filename</span> = <span $this</span>->log_file_pre . <span $this</span>-><span get_max_log_file_suf();
</span><span  75</span>                 self::<span $handle</span> = <span fopen</span>(<span $this</span>->log_file_path . <span $filename</span>, 'a'<span );
</span><span  76</span> <span             }
</span><span  77</span>             <span switch</span>(<span $type</span><span ){
</span><span  78</span>                 <span case</span> 0:
<span  79</span>                     <span fwrite</span>(self::<span $handle</span>, 'THING LOG:' . ' ' . <span $desc</span> . ' ' . <span $time</span> . <span chr</span>(13<span ));
</span><span  80</span>                     <span break</span><span ;
</span><span  81</span>                 <span case</span> 1:
<span  82</span>                     <span fwrite</span>(self::<span $handle</span>, 'ERROR LOG:' . ' ' . <span $desc</span> . ' ' . <span $time</span> . <span chr</span>(13<span ));
</span><span  83</span>                     <span break</span><span ;
</span><span  84</span>                 <span default</span>:
<span  85</span>                     <span fwrite</span>(self::<span $handle</span>, 'THING LOG:' . ' ' . <span $desc</span> . ' ' . <span $time</span> . <span chr</span>(13<span ));
</span><span  86</span>                     <span break</span><span ;
</span><span  87</span> <span             }
</span><span  88</span>              
<span  89</span> <span         }
</span><span  90</span> <span     }
</span><span  91</span>      
<span  92</span>     <span /*</span><span *
</span><span  93</span> <span      * 获取当前日志的最新文档的后缀
</span><span  94</span> <span      * 
</span><span  95</span> <span      * @since alpha 0.0.1
</span><span  96</span> <span      * @date 2014.02.04
</span><span  97</span> <span      * @author genialx
</span><span  98</span>      <span */</span>
<span  99</span>     <span private</span> <span function</span><span  get_max_log_file_suf(){
</span><span 100</span>         <span $log_file_suf</span> = <span null</span><span ;
</span><span 101</span>         <span if</span>(<span is_dir</span>(<span $this</span>-><span log_file_path)){
</span><span 102</span>             <span if</span>(<span $dh</span> = <span opendir</span>(<span $this</span>-><span log_file_path)){
</span><span 103</span>                 <span while</span>((<span $file</span> = <span readdir</span>(<span $dh</span>)) != <span FALSE</span><span ){
</span><span 104</span>                     <span if</span>(<span $file</span> != '.' && <span $file</span> != '..'<span ){
</span><span 105</span>                         <span if</span>(<span filetype</span>( <span $this</span>->log_file_path . <span $file</span>) == 'file'<span ){
</span><span 106</span>                             <span $rs</span> = <span split</span>('_', <span $file</span><span );
</span><span 107</span>                             <span if</span>(<span $log_file_suf</span> < <span $rs</span>[1<span ]){
</span><span 108</span>                                 <span $log_file_suf</span> = <span $rs</span>[1<span ];
</span><span 109</span> <span                             }
</span><span 110</span> <span                         }
</span><span 111</span> <span                     }
</span><span 112</span> <span                 }
</span><span 113</span>                  
<span 114</span>                 <span if</span>(<span $log_file_suf</span> == <span NULL</span><span ){
</span><span 115</span>                     <span $log_file_suf</span> = 0<span ;
</span><span 116</span> <span                 }
</span><span 117</span>                 <span //</span><span 截断文件</span>
<span 118</span>                 <span if</span>( <span file_exists</span>(<span $this</span>->log_file_path . <span $this</span>->log_file_pre . <span $log_file_suf</span>) && <span filesize</span>(<span $this</span>->log_file_path . <span $this</span>->log_file_pre . <span $log_file_suf</span>) >= <span $this</span>-><span log_max_len){
</span><span 119</span>                     <span $log_file_suf</span> = <span intval</span>(<span $log_file_suf</span>) + 1<span ;
</span><span 120</span> <span                 }
</span><span 121</span>                  
<span 122</span>                 <span return</span> <span $log_file_suf</span><span ;
</span><span 123</span> <span             }   
</span><span 124</span> <span         }
</span><span 125</span>          
<span 126</span>         <span return</span> 0<span ;
</span><span 127</span>          
<span 128</span> <span     }
</span><span 129</span>      
<span 130</span>     <span /*</span><span *
</span><span 131</span> <span      * 关闭文件句柄
</span><span 132</span> <span      * 
</span><span 133</span> <span      * @since alpha 0.0.1
</span><span 134</span> <span      * @date 2014.02.04
</span><span 135</span> <span      * @author genialx
</span><span 136</span>      <span */</span>
<span 137</span>     <span public</span> <span function</span><span  close(){
</span><span 138</span>         <span fclose</span>(self::<span $handle</span><span );
</span><span 139</span> <span     }
</span><span 140</span> }

Function description:
This log class uses the singleton mode to save resources. Determine the file size by yourself. If the size exceeds the specified size, create files in sequence. For example: the file log_0 is larger than the specified size, then the log_1 file is re-created (note: the created file is based on the number of the file name suffix, please do not change the log file name at will).

To be optimized: does not specify the maximum number of files, so excessive log files must be manually deleted regularly.


Call example:

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

Thank you for checking it out!

Article source: http://www.ihuxu.com/p/223.html

WeChat public account (share valuable Internet information every day): Hu Xu’s personal blog

Sina Weibo: @ the Internet around me

Programming discussion group: 235173087

QQ:2252065614

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/732360.htmlTechArticleFollowing the previous article [WeChat development of micro-e-commerce website] one of the technical notes, I did the log processing yesterday Function. For today's applications, the importance of logs is self-evident. ...
Statement
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
PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

See all articles

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)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor