<?php /* [Filename] crifanLib.php [Function] crifan's php lib, implement common functions [Author] Crifan Li [Contact] [Note] 1.online see code: [TODO] [History] [v2015-07-27] 1.add logInit, logWrite [v1.0] 1.initial version, need clean up later */ class crifanLib { private $logFile; private $logFp; /* Init log file */ function logInit($inputLogFile = null){ // set default log file name // in case of Windows set default log file //http://stackoverflow.com/questions/1482260/how-to-get-the-os-on-which-php-is-running //http://php.net/manual/zh/function.php-uname.php if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { $defautLogFile = 'C:/php/defLogFile.log'; } // set default log file for Linux and other systems else { $defautLogFile = '/tmp/defLogFile.log'; } $this->logFile = $inputLogFile ? $inputLogFile : $defautLogFile; } /* Write log info to file */ function logWrite($logContent){ // define script name $scriptName = pathinfo($_SERVER['PHP_SELF'], PATHINFO_FILENAME); // define current time and suppress E_WARNING if using the system TZ settings // (don't forget to set the INI setting date.timezone) $timeStr = @date('[Y-m-d H:i:s]'); // write current time, script name and message to the log file file_put_contents($this->logFile, "$timeStr ($scriptName) $logContent" . PHP_EOL, FILE_APPEND); } } ?>
测试文件为:
<?php /* Author: Crifan Li Version: 2015-07-27 Contact: Function: test crifanLib log */ include_once "crifanLib.php"; //test log $crifanLib = new crifanLib(); $crifanLib->logInit("/xxx/logTest.log"); $crifanLib->logWrite("This is crifanLib log test message using file_put_contents"); ?>
效果是:
root@chantyou:access_token# ll
total 16
-rw-r--r-- 1 root root 9524 Jul 27 18:16 crifanLib.php
-rwxrwxrwx 1 root root 561 Jul 27 18:18 wx_access_token.php
root@chantyou:access_token# ll
total 20
-rw-r--r-- 1 root root 9524 Jul 27 18:16 crifanLib.php
-rw-r--r-- 1 apache apache 76 Jul 27 18:19 logTest.log
-rwxrwxrwx 1 root root 561 Jul 27 18:18 wx_access_token.php
root@chantyou:access_token# cat logTest.log
[2015-07-27 12:05:47] (wx_access_token) This is crifanLib log test message using file_put_contents
root@chantyou:access_token#
如图:
注:
期间参考:
PHP: is_resource – Manual
【总结】
1.此处可以通过:
fopen创建log文件
fwrite写入文件信息
fclose关闭文件
去实现log信息写入到文件中的。
2.更好的做法是:
直接用更方便的
file_put_contents直接输出内容到log文件
即可。
以上就是将log信息写入服务器中的log文件文件全部内容,希望大家喜欢。
您可能感兴趣的文章: