您好,UncleToo欢迎您!  为了更好的浏览本站,请使用高版本浏览器
RSS  Tag     设为首页 | 加入收藏
 您所在的位置:首页 > PHP技术 > PHP应用

PHP教程 将程序运行错误记录到日志文件

作者:UncleToo  来源:原创  日期:2014-02-24 7:46:17
收藏  评论:( 0 )  阅读:876

       日志记录在应用程序运行时是非常重要的,它可以帮助开发者了解应用程序的哪些部分工作不正常,哪些地方需要进行修复或完善等等。因此,一个号的应用程序,日志记录是不可少的。

       在本文中,UncleToo给大家分享一个记录日志的PHP类,它可以使你在程序中很容易的记录运行日志。下面我们看看这个类及它的使用方法:

<?php
class KLogger {
    const EMERG  = 0;
    const ALERT  = 1;
    const CRIT   = 2;
    const ERR    = 3;
    const WARN   = 4;
    const NOTICE = 5;
    const INFO   = 6;
    const DEBUG  = 7;
    const OFF    = 8;
    const FATAL  = 2;
    const STATUS_LOG_OPEN    = 1;
    const STATUS_OPEN_FAILED = 2;
    const STATUS_LOG_CLOSED  = 3;
    private $_logStatus         = self::STATUS_LOG_CLOSED;
    private $_messageQueue      = array();
    private $_logFilePath       = null;
    private $_severityThreshold = self::INFO;
    private $_fileHandle        = null;
    private $_messages = array(
        'writefail'   => 'The file could not be written to. Check that appropriate permissions have been set.',
        'opensuccess' => 'The log file was opened successfully.',
        'openfail'    => 'The file could not be opened. Check permissions.',
    );
    private static $_defaultSeverity    = self::DEBUG;
    private static $_dateFormat         = 'Y-m-d G:i:s';
    private static $_defaultPermissions = 0755;
    private static $instances           = array();
    public static function instance( $logDirectory = false, $severity = false ) {
        if ($severity === false) {
            $severity = self::$_defaultSeverity;
        }
        if ($logDirectory === false) {
            if (count(self::$instances) > 0) {
                return current(self::$instances);
            } else {
                $logDirectory = dirname(__FILE__);
            }
        }
        if (in_array($logDirectory, self::$instances)) {
            return self::$instances[$logDirectory];
        }
        self::$instances[$logDirectory] = new self($logDirectory, $severity);
        return self::$instances[$logDirectory];
    }
    public function __construct( $logDirectory, $severity ) {
        $logDirectory = rtrim($logDirectory, '\\/');
        if ($severity === self::OFF) {
            return;
        }
        $this->_logFilePath = $logDirectory
            . DIRECTORY_SEPARATOR
            . 'log_'
            . date('Y-m-d')
            . '.txt';
        $this->_severityThreshold = $severity;
        if (!file_exists($logDirectory)) {
            mkdir($logDirectory, self::$_defaultPermissions, true);
        }
        if (file_exists($this->_logFilePath) && !is_writable($this->_logFilePath)) {
            $this->_logStatus = self::STATUS_OPEN_FAILED;
            $this->_messageQueue[] = $this->_messages['writefail'];
            return;
        }
        if (($this->_fileHandle = fopen($this->_logFilePath, 'a'))) {
            $this->_logStatus = self::STATUS_LOG_OPEN;
            $this->_messageQueue[] = $this->_messages['opensuccess'];
        } else {
            $this->_logStatus = self::STATUS_OPEN_FAILED;
            $this->_messageQueue[] = $this->_messages['openfail'];
        }
    }
    public function __destruct() {
        if ($this->_fileHandle) {
            fclose($this->_fileHandle);
        }
    }
    public function logDebug( $line ) {
        $this->log($line, self::DEBUG);
    }
    public function getMessage() {
        return array_pop($this->_messageQueue);
    }
    public function getMessages() {
        return $this->_messageQueue;
    }
    public function clearMessages() {
        $this->_messageQueue = array();
    }
    public static function setDateFormat( $dateFormat ) {
        self::$_dateFormat = $dateFormat;
    }
    public function logInfo( $line ) {
        $this->log($line, self::INFO);
    }
    public function logNotice( $line ) {
        $this->log($line, self::NOTICE);
    }
    public function logWarn( $line ) {
        $this->log($line, self::WARN);
    }
    public function logError( $line ) {
        $this->log($line, self::ERR);
    }
    public function logFatal( $line ) {
        $this->log($line, self::FATAL);
    }
    public function logAlert( $line ) {
        $this->log($line, self::ALERT);
    }
    public function logCrit( $line ) {
        $this->log($line, self::CRIT);
    }
    public function logEmerg( $line ) {
        $this->log($line, self::EMERG);
    }
    public function log( $line, $severity ) {
        if ($this->_severityThreshold >= $severity) {
            $status = $this->_getTimeLine($severity);
            $this->writeFreeFormLine("$status $line \n");
        }
    }
    public function writeFreeFormLine( $line ) {
        if ($this->_logStatus == self::STATUS_LOG_OPEN
            && $this->_severityThreshold != self::OFF) {
            if (fwrite($this->_fileHandle, $line) === false) {
                $this->_messageQueue[] = $this->_messages['writefail'];
            }
        }
    }
    private function _getTimeLine( $level ) {
        $time = date(self::$_dateFormat);
        switch ($level) {
            case self::EMERG:
                return "$time - EMERG -->";
            case self::ALERT:
                return "$time - ALERT -->";
            case self::CRIT:
                return "$time - CRIT -->";
            case self::FATAL:
                return "$time - FATAL -->";
            case self::NOTICE:
                return "$time - NOTICE -->";
            case self::INFO:
                return "$time - INFO -->";
            case self::WARN:
                return "$time - WARN -->";
            case self::DEBUG:
                return "$time - DEBUG -->";
            case self::ERR:
                return "$time - ERROR -->";
            default:
                return "$time - LOG -->";
        }
    }
}
?>


使用KLogger类

KLogger使用时非常简单,你只需要将类文件包含在需要输入日志的页面,并定义存储日志的目录即可。如:

include( KLogger.php );

$log = KLogger::instance('/logs/', KLogger::DEBUG);

上面代码将日志输出并存放在logs目录下。


输出日志

<?php
 //Prints to the log file
 $log -> logInfo ( 'logInfo:UncleToo' ) ;
                      
 //Prints to the log file
 $log -> logFatal ( 'logFatal:UncleToo中文网' ) ;
                      
 //Prints to the log file with a dump of the object
 $log -> logInfo ( 'logInfo:UncleToo中文网PHP教程' ,   $obj ) ;
?>

这样,很简单的几步就可以将我们的PHP应用程序运行日志保存到文件了。



除非特别声明,本站所有PHP教程及其他教程/文章均为原创、翻译或网友投稿,版权均归UncleToo中文网所有, 转载请注明作者及出处。
原文网址:http://www.uncletoo.com/html/application/828.html
读完这篇文章后,你是否有所收获? 分享是一种生活的信念!
  • 0
  • 0
我来说两句
更多>>网友评论