php文件日志类,按年月日组织目录结构。
<?php class FileLog
{
private $_filepath; //文件路径
private $_filename; //日志文件名
private $_filehandle; //文件句柄 function __construct($fileName = 'log')
{
date_default_timezone_set('PRC');
$this->_filename = $fileName;
$this->init();
} /*
* 构造函数调用,初始化文件保存路径,文件名
*/
function init()
{
//如果有定义LOG_PATH常量,日志记录在LOG_PATH下,如果没有定义记录在当前目录 的logs
$this->_filepath = defined('LOG_PATH') ? LOG_PATH : './logs';
$this->_filepath = rtrim($this->_filepath, '/');
$this->_filepath .= '/' . date('y', time()) . '/' . date('m', time());
if (!is_dir($this->_filepath)) {
mkdir($this->_filepath, 0777, true);
}
if (!is_dir($this->_filepath)) {
//如果目录创建失败直接返回
$this->_filehandle = null;
return;
}
//拼接完整的文件名
$pathinfo = pathinfo($this->_filename);
$extension = isset($pathinfo['extension']) ? $pathinfo['extension'] : '';//取文件的扩展名
$this->_filename = $this->_filepath . '/' . $pathinfo['filename'] . '_' . date('d', time());
$this->_filename .= empty($extension) ? '.log' : '.' . $extension;
//打开文件
$this->_filehandle = fopen($this->_filename, "a+");
} /**
*作用:初始化记录类,写入记录
*输入:要写入的记录,可以是数组
*输出:写入成功返回true失败返回false
*/
public function addLog($log)
{
if (empty($this->_filehandle))
return false;
$strLog = '';
$strLog .= date("Y-m-d H:i:s") . ' ' . $this->_getUrl() . "\r\n";
$strLog .= "POST: " . $this->_postData() . "\r\n";
if (is_array($log)) {
$strLog .= $this->array2string($log);
} else {
$strLog .= $log . "\r\n";
}
$strLog .= "\r\n"; //写日志
fwrite($this->_filehandle, $strLog) !== false;
} function array2string($data)
{
$log_a = "";
foreach ($data as $key => $value) {
if (is_array($value)) $log_a .= "[" . $key . "] => (" . $this->array2string($value) . ") \r\n";
else $log_a .= "[" . $key . "] => " . $value . "\r\n";
}
return $log_a;
} /**
*作用:获取完整URL路径
*输入:完整URL路径
*输出:URL路径字串
*/
private function _getUrl()
{
$host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : (isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : 'localhost');
return 'http' . (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ? 's' : '')
. '://'
. $host
. $_SERVER['REQUEST_URI'];
} /**
*作用:获取POST数据
*输入:POST数据
*输出:POST数组
*/
private function _postData()
{
$strPost = '';
if (isset($_POST) && count($_POST) > 0) {
foreach ($_POST as $key => $val) {
$strPost .= $key . '=' . $val . '&';
}
}
$strPost=trim($strPost,'&');
return $strPost;
} /**
*功能: 析构函数,释放文件句柄
*输入: 无
*输出: 无
*/
function __destruct()
{
//关闭文件
if (!empty($this->_filehandle))
fclose($this->_filehandle);
}
} ?>