php实现记录
PHP实现日志记录的方法
使用PHP内置函数error_log记录日志
error_log函数可以将日志信息写入到指定位置,支持文件、系统日志或邮件发送。语法如下:
error_log("Error message", 3, "/path/to/error.log");
配置PHP错误日志路径 在php.ini文件中设置以下参数:
log_errors = On
error_log = /path/to/php_errors.log
使用Monolog日志库
安装Monolog 通过Composer安装Monolog:
composer require monolog/monolog
基本使用示例
require 'vendor/autoload.php';
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
$log = new Logger('name');
$log->pushHandler(new StreamHandler('path/to/your.log', Logger::WARNING));
$log->warning('This is a warning');
自定义日志类实现
创建日志类
class CustomLogger {
private $logFile;
public function __construct($filePath) {
$this->logFile = $filePath;
}
public function log($message, $level = 'INFO') {
$timestamp = date('Y-m-d H:i:s');
$logEntry = "[$timestamp][$level] $message" . PHP_EOL;
file_put_contents($this->logFile, $logEntry, FILE_APPEND);
}
}
使用示例
$logger = new CustomLogger('/path/to/logfile.log');
$logger->log('This is an informational message');
$logger->log('Something went wrong', 'ERROR');
数据库日志记录
创建日志表
CREATE TABLE system_logs (
id INT AUTO_INCREMENT PRIMARY KEY,
level VARCHAR(20),
message TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
ip_address VARCHAR(45)
);
PHP实现数据库日志
function logToDatabase($message, $level = 'INFO') {
$db = new PDO('mysql:host=localhost;dbname=yourdb', 'user', 'pass');
$stmt = $db->prepare("INSERT INTO system_logs (level, message, ip_address)
VALUES (?, ?, ?)");
$stmt->execute([$level, $message, $_SERVER['REMOTE_ADDR']]);
}
日志轮转和归档
实现日志文件轮转
function rotateLog($filePath, $maxSize = 1048576) {
if (file_exists($filePath) && filesize($filePath) >= $maxSize) {
$backupFile = $filePath . '.' . date('YmdHis');
rename($filePath, $backupFile);
}
}
定时清理旧日志
function cleanOldLogs($dir, $daysToKeep = 30) {
$files = glob($dir . '/*.log*');
$now = time();
foreach ($files as $file) {
if (is_file($file) && ($now - filemtime($file)) > ($daysToKeep * 86400)) {
unlink($file);
}
}
}






