tp5处理独立日志
最近用fastadmin比较多,这个项目使用的是tp5.0,习惯了tp6的日志的channel的独立日志功能,tp5的日志就很不方便,这里写了一个独立的日志类,方便对一些特殊的日志进行记录
新建文件名为MyLog.php到application\common\library文件夹中,内容如下
<?php
namespace app\common\library;
use think\Request;
class MyLog
{
/**
* 存储位置
* @var string
*/
private static $dir= 'star';
/**
* @var array 日志类型
*/
protected static $type = ['error', 'info', 'alert'];
/**
* Notes:info
* DateTime 2022/7/21 16:41
* @Author wind
* @param $msg
* @param $channel
*/
public static function info($msg, $channel = '')
{
self::write($msg, 'info', $channel);
}
/**
* Notes:alert
* DateTime 2022/7/21 16:41
* @Author wind
* @param $msg
* @param $channel
*/
public static function alert($msg, $channel = '')
{
self::write($msg, 'alert', $channel);
}
/**
* Notes:error
* DateTime 2022/7/21 16:41
* @Author wind
* @param $msg
* @param $channel
*/
public static function error($msg, $channel = '')
{
self::write($msg, 'error', $channel);
}
/**
* Notes:写入日志
* DateTime 2022/7/21 16:42
* @Author wind
* @param $msg
* @param $level
* @param $channel
*/
protected static function write($msg, $level = 'info', $channel = '')
{
$log_filename = self::getLogFileName($channel);
self::checkFileSize($log_filename);
if(is_array($msg)){
$msg = var_export($msg, true);
}
$request = Request::instance();
$header = "[ ${level} ] " . date('Y-m-d H:i:s') . ' ' . $request->ip() . ' ' . $request->method() . ' ' . $request->url(true) . "\r\n";
file_put_contents($log_filename, $header . $msg . "\r\n------------------------ --------------------------\r\n", FILE_APPEND);
}
/**
* Notes:获取日志文件信息
* DateTime 2022/7/21 16:42
* @Author wind
* @param $channel
* @return string
*/
protected static function getLogFileName($channel = '')
{
$logDir = RUNTIME_PATH . self::$dir;
if (!is_dir($logDir)) {
mkdir($logDir, '0755', true);
}
if ($channel) {
$logDir .= DS . $channel;
if (!is_dir($logDir)) {
mkdir($logDir, '0755', true);
}
}
return $logDir . DS . date('Y-m-d') . '.log';
}
/**
* Notes:检测日志大小
* DateTime 2022/7/21 16:43
* @Author wind
* @param $log_filename
*/
protected static function checkFileSize($log_filename)
{
$max_size = 30000000;
if (file_exists($log_filename) && (abs(filesize($log_filename)) > $max_size)) {
rename($log_filename, dirname($log_filename) . DS . date('Ym-d-His') . ".log");
}
}
/**
* 静态方法调用
* @access public
* @param string $method 调用方法
* @param mixed $args 参数
* @return void
*/
public static function __callStatic($method, $args)
{
if (!in_array($method, self::$type)) {
array_push($args, $method);
call_user_func_array('self::write', $args);
}
}
}
使用的时候直接 MyLog::info('内容') MyLog::alert('内容') MyLog::error('内容') 即可
另外也可以自己定义日志类型,例如 MyLog::haha('内容')
本文链接:
/archives/1703571896446
版权声明:
本站所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自
雕刻时光!
喜欢就支持一下吧