基于Laravel 8
<?php
namespace App\Http\Helpers;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Route;
use Monolog\Formatter\LineFormatter;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
class LogHelper
{
private static $filename ='';
// 文件记录类型 1:文件目录/日期/文件名 2:所有日志一个文件夹
private function __construct()
{
}
private function __clone()
{
// TODO: Implement __clone() method.
}
/**
* 设置日志文件名称
* @param $filename
*/
public static function setFilename($filename)
{
self::$filename = $filename;
}
/**
* @param $message
* @param array $data
* @param string $filename
* @param string $isDate 是否按月份分文件夹
*/
private static function _save($message, $data = [],string $filename, $isDate = true)
{
$action = Route::current()->getActionName();
list($class, $method) = explode('@', $action);
if (empty($filename)) $filename = !empty(self::$filename) ? self::$filename : $method;
$log = new Logger('mylog');
if (PHP_SAPI == 'cli') {
// 命令行访问脚本的,加一个cli标识和用户浏览器访问的区分开
$filename .= '_cli';
}
$filename = $filename . '.log';
if ($isDate) {
// 是否要按日显示
$path = storage_path('logs/' . date('Y-m-d'));
} else {
$path = storage_path('logs/');
}
// 有时候运维没给号权限,容易导致写入日志失败
self::mkDirs($path);
$path = $path . '/' . $filename;
if (gettype($data) != 'array') {
$message .= " " . $data;
$data = [];
}
$microtime = microtime();
$message = '[' . substr($microtime, 0, 8) . '] ' . $message;// 记录毫秒时间
// finally, create a formatter
$formatter = new LineFormatter("[%datetime%] %message% %context%\n", "Y-m-d H:i:s");
$stream = new StreamHandler($path, Logger::INFO);
$stream->setFormatter($formatter);
$log->pushHandler($stream);
$log->info($message, $data);
}
/**
* 日志打印
* @param string $message
* @param array $data
* @param string $filename
*/
public static function info(string $message,$data = [],string $filename='')
{
self::_save($message, $data, $filename);
}
/**
* 给日志文件夹权限
* @param $dir
* @param int $mode
* @return bool
*/
private static function mkDirs($dir, int $mode = 0777)
{
if (is_dir($dir) || @mkdir($dir, $mode)) {
return TRUE;
}
if (!self::mkdirs(dirname($dir), $mode)) {
return FALSE;
}
return @mkdir($dir, $mode);
}
/**
* 记录最后一条执行的sql
* @param string $file_name
*
*/
public static function sql(string $file_name='')
{
if (empty($file_name)) $file_name = !empty(self::$filename) ? self::$filename : __FUNCTION__.'_sql';
DB::listen(function ($sql) use ($file_name) {
foreach ($sql->bindings as $i => $binding) {
if ($binding instanceof \DateTime) {
$sql->bindings[$i] = $binding->format('\'Y-m-d H:i:s\'');
} else {
if (is_string($binding)) {
$sql->bindings[$i] = "'$binding'";
}
}
}
$query = str_replace(array('%', '?'), array('%%', '%s'), $sql->sql);
$query = vsprintf($query, $sql->bindings);
LogHelper::info('sql:', $query, $file_name);
});
}
}
// 按日 按文件名
LogHelper::info('A 数组',['a','b'],'order');
// 按文件名
LogHelper::info('A 数组',['a','b'],'order');
// 只有字符串
LogHelper::info('B 字符串');
// 记录下面的执行sql
LogHelper::sql();
// 输出:
// [2021-04-15 11:50:37] [0.627499] sql:select * from `user` where `mobile` = '' limit 1 []