77 lines
2.0 KiB
PHP
77 lines
2.0 KiB
PHP
<?php
|
|
/**
|
|
* Author: cfn <cfn@leapy.cn>
|
|
*/
|
|
|
|
namespace App\Utils;
|
|
|
|
use Hyperf\Context\ApplicationContext;
|
|
use Hyperf\Logger\Logger;
|
|
use Hyperf\Logger\LoggerFactory;
|
|
use Monolog\Formatter\LineFormatter;
|
|
use Monolog\Handler\StreamHandler;
|
|
use Monolog\Level;
|
|
|
|
class Log
|
|
{
|
|
public static function getInstance(string $name = 'app')
|
|
{
|
|
return ApplicationContext::getContainer()->get(LoggerFactory::class)->get($name);
|
|
}
|
|
|
|
public static function __callStatic($name, $arguments)
|
|
{
|
|
self::getInstance()->$name(...$arguments);
|
|
}
|
|
|
|
public static function record($message, string $filename = "info")
|
|
{
|
|
self::_save($message, $filename);
|
|
}
|
|
|
|
private static function _save($message, string $filename = 'log')
|
|
{
|
|
$log = new Logger('app');
|
|
|
|
$filename = $filename . '.log';
|
|
|
|
$path = 'runtime/logs/' . date('Y') . "/" . date("m");
|
|
|
|
// 有时候运维没给号权限,容易导致写入日志失败
|
|
self::mkDirs($path);
|
|
$path = $path . '/' . date("d") . "_". $filename;
|
|
|
|
if (gettype($message) == 'array') {
|
|
$message = json_encode($message, true);
|
|
}
|
|
|
|
$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, Level::Info);
|
|
$stream->setFormatter($formatter);
|
|
|
|
$log->pushHandler($stream);
|
|
$log->info($message);
|
|
}
|
|
|
|
/**
|
|
* 给日志文件夹权限
|
|
* @param string $dir
|
|
* @param int $mode
|
|
* @return bool
|
|
*/
|
|
private static function mkDirs(string $dir, int $mode = 0777): bool
|
|
{
|
|
if (is_dir($dir) || @mkdir($dir, $mode)) {
|
|
return TRUE;
|
|
}
|
|
if (!self::mkdirs(dirname($dir), $mode)) {
|
|
return FALSE;
|
|
}
|
|
return @mkdir($dir, $mode);
|
|
}
|
|
} |