自己寫的PHP的Logger____PHP

來源:互聯網
上載者:User

工作中需要用到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較為妥當。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.