文件
2026-08-16 17:03:10 +08:00

71 行
2.5 KiB
PHP

<?php
if (!defined('IN_APP')) exit('Forbidden');
class Logger
{
private static $dir;
private static $enabled = true;
private static $minLevel = 0;
const DEBUG = 0;
const INFO = 1;
const WARN = 2;
const ERROR = 3;
public static function init($dir, $enabled = true, $minLevel = 0)
{
self::$dir = rtrim($dir, '/\\');
self::$enabled = $enabled;
self::$minLevel = $minLevel;
if (!is_dir(self::$dir)) {
@mkdir(self::$dir, 0755, true);
}
}
public static function debug($message, array $context = [])
{
self::write(self::DEBUG, $message, $context);
}
public static function info($message, array $context = [])
{
self::write(self::INFO, $message, $context);
}
public static function warn($message, array $context = [])
{
self::write(self::WARN, $message, $context);
}
public static function error($message, array $context = [])
{
self::write(self::ERROR, $message, $context);
}
private static function write($level, $message, array $context)
{
if (!self::$enabled || $level < self::$minLevel) return;
$levelNames = [self::DEBUG => 'DEBUG', self::INFO => 'INFO', self::WARN => 'WARN', self::ERROR => 'ERROR'];
$date = date('Y-m-d');
$time = date('Y-m-d H:i:s');
$levelName = $levelNames[$level] ?? 'LOG';
$ctxStr = '';
if (!empty($context)) {
$parts = [];
foreach ($context as $k => $v) {
if (is_array($v) || is_object($v)) {
$v = json_encode($v, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
$parts[] = $k . '=' . $v;
}
$ctxStr = ' [' . implode(', ', $parts) . ']';
}
$trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3);
$caller = '';
if (isset($trace[2])) {
$file = basename($trace[2]['file'] ?? '');
$line = $trace[2]['line'] ?? '';
$caller = " [{$file}:{$line}]";
}
$logLine = "[{$time}] [{$levelName}]{$caller} {$message}{$ctxStr}" . PHP_EOL;
$file = self::$dir . DIRECTORY_SEPARATOR . $date . '.log';
@file_put_contents($file, $logLine, FILE_APPEND | LOCK_EX);
if (file_exists($file) && filesize($file) > 10 * 1024 * 1024) {
$rotated = self::$dir . DIRECTORY_SEPARATOR . $date . '.log.1';
@rename($file, $rotated);
}
}
}