实现可配置的日志系统需要先定义一个配置文件,用于存储日志系统的相关配置信息,比如日志存储路径、日志级别等。可以使用PHP的数组来定义配置文件,以便于后续的读取和修改。
$config = array(
'log_level' => 'DEBUG', // 日志级别
'log_path' => '/var/log/php.log', // 日志存储路径
'log_rotate' => true, // 是否开启日志滚动
'log_max_size' => 1024 // 单个日志文件最大大小,单位为KB
);
接下来需要定义一个日志类,用于实现日志的写入和相关操作。日志类的构造函数可以接收一个配置文件作为参数,以便于在实例化日志类时进行配置。
class Logger {
private $config;
public function __construct($config) {
$this->config = $config;
}
public function debug($message) {
$this->writeLog('DEBUG', $message);
}
public function info($message) {
$this->writeLog('INFO', $message);
}
public function error($message) {
$this->writeLog('ERROR', $message);
}
private function writeLog($level, $message) {
// 写入日志的具体实现
}
}
日志类中的writeLog方法是具体实现日志写入的方法。在该方法中,我们可以根据配置文件中的日志级别,来决定是否写入该条日志。如果需要写入日志,则可以根据配置文件中的日志存储路径,将日志写入到指定的文件中。如果开启了日志滚动,则需要判断当前日志文件的大小是否已经超过了配置文件中的最大大小,如果超过了则需要切换到下一个日志文件。
private function writeLog($level, $message) {
if ($this->getLogLevelValue($level) >= $this->getLogLevelValue($this->config['log_level'])) {
$log = sprintf("[%s] %s: %s\n", date('Y-m-d H:i:s'), $level, $message);
$logFile = $this->config['log_path'];
if ($this->config['log_rotate']) {
// 检查日志文件大小是否已经超过了最大值
if (filesize($logFile) > $this->config['log_max_size'] * 1024) {
$logFile = $this->rotateLogFile($logFile);
}
}
error_log($log, 3, $logFile);
}
}
private function getLogLevelValue($level) {
switch (strtoupper($level)) {
case 'ERROR':
return 3;
case 'WARN':
return 2;
case 'INFO':
return 1;
case 'DEBUG':
return 0;
default:
return 999;
}
}
private function rotateLogFile($logFile) {
$pathInfo = pathinfo($logFile);
$dir = $pathInfo['dirname'];
$fileName = $pathInfo['filename'];
$extension = $pathInfo['extension'];
$newLogFile = $dir . '/' . $fileName . '_' . date('YmdHis') . '.' . $extension;
rename($logFile, $newLogFile);
return $logFile;
}
在使用时,我们可以先实例化一个日志类,并将配置文件作为参数传入。然后,就可以调用日志类中的debug、info、error等方法来写入不同级别的日志了。
$logger = new Logger($config);
$logger->debug('This is a debug message');
$logger->info('This is an info message');
$logger->error('This is an error message');