PHP开发 自定义log日志 舍弃var_dump和print_r
在网站根目录,创建log目录,然后按日期生成目录,当log日志大于512kb时,则进行按日期备份
其中,LOGFILE为当前日志文件名 LINE为分界符
class Loger
{
const LOGFILE = 'curr.log'; //建一个常量,代表日志文件的名称
const LINE = "---------------------------------------------------------------------------------------------------------------------------------------------------------------------";
//控制是否进行写日志
const isLog = true;
//禁止实例化
private function __construct()
{
}
// 写日志的
public static function write($cont)
{
if (self::isLog) {
$cont .= "\r\n";
// 判断是否备份
$log = self::isBak(); // 计算出日志文件的地址
$fh = fopen($log, 'ab');
fwrite($fh, $cont);
fclose($fh);
}
}
// 写sql语句日志 [sql] [18月05日 22:12:03] select * from gf_admin
public static function sql($sql)
{
$type = "sql";
self::format($sql, $type);
}
//记录一些日志 info
public static function info($msg)
{
$type = "info";
self::format($msg, $type);
}
public static function error($msg){
$type='error';
self::format($msg,$type);
}
//记录一些日志 自定义日志类型
public static function custom($msg, $type)
{
self::format($msg, $type);
}
//定义日志格式 支持字符串或数组类型
private static function format($msg, $type)
{
$now = date('m月d日 H:i:s');
if (is_array($msg)) {
$msg=json_encode($msg,true);
$msg = "[$type] [" . $now . '] ' . $msg;
self::write(self::LINE);
}
if (is_string($msg)||is_numeric($msg)||is_bool($msg)) {
$msg = "[$type] [" . $now . '] ' . $msg;
// $msg = self::LINE . "\r\n" . $msg . "\r\n" . self::LINE;
$msg = $msg . "\r\n" . self::LINE;
self::write($msg);
}
}
// 备份日志
private static function bak()
{
// 就是把原来的日志文件,改个名,存储起来
// 改成 年-月-日.bak这种形式
$log =$dir = $_SERVER['DOCUMENT_ROOT'] . '/log/' . date('Y-m') . '/' . date('d')."/" . self::LOGFILE;
var_dump(fileperms($log));
$bak = $_SERVER['DOCUMENT_ROOT'] . '/log/' . date('Y-m') . '/' . date('d')."/" . date('Y-m-dH:i:s') . '.bak';
return rename($log, $bak);
}
// 读取并判断日志的大小
private static function isBak()
{
$log = $_SERVER['DOCUMENT_ROOT'] . '/log/' . date('Y-m') . '/' . date('d') . '/' . self::LOGFILE;
$dir = $_SERVER['DOCUMENT_ROOT'] . '/log/' . date('Y-m') . '/' . date('d');
self::create_folders($dir);
if (!file_exists($log)) { //如果文件不存在,则创建该文件
touch($log); // touch在linux也有此命令,是快速的建立一个文件
return $log;
}
// 要是存在,则判断大小
// 清除缓存
clearstatcache(true, $log);
$size = filesize($log);
if ($size <= 1024 * 512) { //大于512kb
return $log;
}
// 走到这一行,说明>1M
if (!self::Bak()) {
return $log;
} else {
touch($log);
return $log;
}
}
//创建多级目录,若不存在
private static function create_folders($dir)
{
return is_dir($dir) or (self::create_folders(dirname($dir)) and mkdir($dir, 0777));
}
// public static function mkdirs($dir, $mode = 0777)
// {
// if (is_dir($dir)|| @mkdir($dir,$mode)){
// return true;
// }else{
// self::mkdirs(dirname($dir));
// if (@mkdir($dir,$mode)){
// return true;
// }
// }
// return false;
// }
}