工作中需要用到php寫日誌,log4php需要複雜的設定檔,不想去弄。雖然跟log4j的配置差不多,但也沒必要去維護一個日誌設定檔。
就自己寫了一個單檔案的logger類,只需要include進來使用即可。
不多說,貼代碼
<?php/* * PHP Logger Class * Created: 2011-10-26 * Author: xingfei(http://blog.csdn.net/jakieyoung) * Licence: Free of use and redistribution */if(!defined('_LOGGER_PHP_')) { define('_LOGGER_PHP_', '1');if(!defined('LOG_ROOT')) { define('LOG_ROOT', '/webroot/logs/');}define('LEVEL_FATAL', 0);define('LEVEL_ERROR', 1);define('LEVEL_WARN', 2);define('LEVEL_INFO', 3);define('LEVEL_DEBUG', 4);class Logger { static $LOG_LEVEL_NAMES = array( 'FATAL', 'ERROR', 'WARN', 'INFO', 'DEBUG' ); private $level = LEVEL_DEBUG; static function getInstance() { return new Logger; } function setLogLevel($lvl) { if($lvl >= count(Logger::$LOG_LEVEL_NAMES) || $lvl < 0) { throw new Exception('invalid log level:' . $lvl); } $this->level = $lvl; } function _log($level, $message, $name) { if($level > $this->level) { return; } $log_file_path = LOG_ROOT . $name . '.log'; $log_level_name = Logger::$LOG_LEVEL_NAMES[$this->level]; $content = date('Y-m-d H:i:s') . ' [' . $log_level_name . '] ' . $message . "\n"; file_put_contents($log_file_path, $content, FILE_APPEND); } function debug($message, $name = 'root') { $this->_log(LEVEL_DEBUG, $message, $name); } function info($message, $name = 'root') { $this->_log(LEVEL_INFO, $message, $name); } function warn($message, $name = 'root') { $this->_log(LEVEL_WARN, $message, $name); } function error($message, $name = 'root') { $this->_log(LEVEL_ERROR, $message, $name); } function fatal($message, $name = 'root') { $this->_log(LEVEL_FATAL, $message, $name); }}}
使用時,先擷取一個logger執行個體,然後調用logger的debug,info,warn,error,fatal等方法。
第一個參數是需要log的內容,第二個參數表示log的名稱,作為log檔案的檔案名稱。log目錄
使用LOG_ROOT來定義。如果需要不同的log目錄,則在include之前,首先define自己的LOG_ROOT。
舉例如下
<?phpdefine('LOG_ROOT', '/myweb/logs/');include('logger.php');$logger = Logger::getInstance();$logger->debug('this is my first log', 'test');
注意:LOG_ROOT需要在最後添加反斜線‘/’。
記錄日誌時,會判斷loglevel,如果設定的loglevel比使用的loglevel高,則不會寫入任何日誌。
在需要禁用日誌時,就可以setLogLevel(LEVEL_FATAL)來只記錄嚴重層級的日誌。
預設的loglevel是最低層級的debug,即記錄所有的日誌。
在開發階段使用預設的即可。在生產環境下,一般使用WARN較為妥當。