自定义php日志类收集应用日志
<?php
class MiniLog {
private static $_instance;
private $_path;
private $_pid;
private $_handleArr;
function __construct($path) {
$this->_path = $path;
$this->_pid = getmypid();
}
private function __clone() {
}
public static function instance($path = '/tmp/') {
if(!(self::$_instance instanceof self)) {
self::$_instance = new self($path);
}
return self::$_instance;
}
private function getHandle($fileName) {
if($this->_handleArr[$fileName]) {
return $this->_handleArr[$fileName];
}
date_default_timezone_set('PRC');
$nowTime = time();
$logSuffix = date('Ymd', $nowTime);
$handle = fopen($this->_path . '/' . $fileName . $logSuffix . ".log", 'a');
$this->_handleArr[$fileName] = $handle;
return $handle;
}
public function log($fileName, $message) {
$handle = $this->getHandle($fileName);
$nowTime = time();
$logPreffix = date('Y-m-d H:i:s', $nowTime);
fwrite($handle, "[$logPreffix][$this->_pid]$message\n");
return true;
}
function __destruct(){
foreach ($this->_handleArr as $key => $item) {
if($item) {
fclose($item);
}
}
}
}
?>
该日志类特点:1. 消息记录了进程id,在消息交错时方便调试 2.打开文件后保存了文件的fd,避免重复打开文件。
调用代码:
/*
* 默认打开所有的日志文件文件
* ERROR,INFO,DEBUG日志级别分别对应的关闭标记文件为:NO_ERROR, NO_INFO, NO_DEBUG
*/
function isLogLevelOff($logLevel)
{
$swithFile = ROOT_PATH . '/log/' . 'NO_' . $logLevel;
if (file_exists($swithFile)){
return true;
}else {
return false;
}
}
/**
* @author pacozhong
* 日志函数的入口
* @param string $confName 日志配置名
* @param string $logLevel 级别
* @param int $errorCode 错误码
* @param string $logMessage 日志内容
*/
function ccdb_log($confName ,$logLevel, $errorCode, $logMessage = "no error msg")
{
if (isLogLevelOff($logLevel)){
return;
}
$st = debug_backtrace();
$function = ''; //调用interface_log的函数名
$file = ''; //调用interface_log的文件名
$line = ''; //调用interface_log的行号
foreach($st as $item) {
if($file) {
$function = $item['function'];
break;
}
if($item['function'] == 'interface_log') {
$file = $item['file'];
$line = $item['line'];
}
}
$function = $function ? $function : 'main';
//为了缩短日志的输出,file只取最后一截文件名
$file = explode("/", rtrim($file, '/'));
$file = $file[count($file)-1];
$prefix = "[$file][$function][$line][$logLevel][$errorCode] ";
if($logLevel == INFO || $logLevel == STAT) {
$prefix = "[$logLevel]" ;
}
$logMessage = genErrMsg($errorCode , $logMessage);
$logFileName = $confName . "_" . strtolower($logLevel);
MiniLog::instance(ROOT_PATH . "/log/")->log($logFileName, $prefix . $logMessage);
if (isLogLevelOff("DEBUG") || $logLevel == "DEBUG"){
return ;
}else {
MiniLog::instance(ROOT_PATH . "/log/")->log($confName . "_" . "debug", $prefix . $logMessage);
}
}
/**
* @author pacozhong
* 接口层日志函数
*/
function interface_log($logLevel, $errorCode, $logMessage = "no error msg")
{
ccdb_log('interface', $logLevel, $errorCode, $logMessage);
}
在文件夹放NO_XX控制日志的开启和关闭。
以上为《微信公众平台开发实战》学习笔记
浙公网安备 33010602011771号