initphp / logger
PSR-3 日志库
1.0.1
2023-12-15 17:30 UTC
Requires
- php: >=5.6
- psr/log: 1.1.4
README
符合PSR-3标准的Logger类
特性
- 使用PDO将日志记录到数据库。
- 将日志记录打印到文件。
- 支持多个驱动器的日志功能。
要求
- PHP 5.6或更高版本
- PSR-3接口包
- PDO扩展(仅限
PDOLogger
)
安装
composer require initphp/logger
使用
FileLogger
require_once "vendor/autoload.php"; use \InitPHP\Logger\Logger; use \InitPHP\Logger\FileLogger; $logFile = __DIR__ . '/logfile.log'; $logger = new Logger(new FileLogger(['path' => $logFile]));
PdoLogger
require_once "vendor/autoload.php"; use \InitPHP\Logger\Logger; use \InitPHP\Logger\PDOLogger; $table = 'logs'; $pdo = new \PDO('mysql:dbname=project;host=localhost', 'root', ''); $logger = new Logger(new PDOLogger(['pdo' => $pdo, 'table' => $table])); $logger->error('User {user} caused an error.', array('user' => 'muhametsafak')); // INSERT INTO logs (level, message, date) VALUES ('ERROR', 'User muhametsafak caused an error.', '2022-03-11 13:05:45')
您可以使用以下SQL语句创建一个示例MySQL表。
CREATE TABLE `logs` ( `level` ENUM('EMERGENCY','ALERT','CRITICAL','ERROR','WARNING','NOTICE','INFO','DEBUG') NOT NULL, `message` TEXT NOT NULL, `date` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ) ENGINE = InnoDB CHARSET=utf8mb4 COLLATE utf8mb4_general_ci;
多日志记录器
require_once "vendor/autoload.php"; use \InitPHP\Logger\Logger; use \InitPHP\Logger\PDOLogger; use \InitPHP\Logger\FileLogger; $logFile = __DIR__ . '/logfile.log'; $table = 'logs'; $pdo = new \PDO('mysql:dbname=project;host=localhost', 'root', ''); $logger = new Logger(new FileLogger(['path' => $logFile]), new PDOLogger(['pdo' => $pdo, 'table' => $table]));
方法
public function emergency(string $msg, array $context = array()): void; public function alert(string $msg, array $context = array()): void; public function critical(string $msg, array $context = array()): void; public function error(string $msg, array $context = array()): void; public function warning(string $msg, array $context = array()): void; public function notice(string $msg, array $context = array()): void; public function info(string $msg, array $context = array()): void; public function debug(string $msg, array $context = array()): void; public function log(string $level, string $msg, array $context = array()): void;
上述所有方法的使用方式相同,除了log()
方法。您可以使用log()
方法为自定义错误级别。
示例1
$logger->emergency("Something went wrong");
它将输出如下内容到日志文件。
2021-09-29T13:34:47+02:00 [EMERGENCY] Something went wrong
示例2
$logger->error("User {username} caused an error.", ["username" => "john"]);
它将输出如下内容到日志文件。
2021-09-29T13:34:47+02:00 [ERROR] User john caused an error.
这就完了。
获取帮助
如果您有任何问题、担忧、错误报告等,请在该存储库的问题跟踪器中提交问题。
致谢
许可
版权所有 © 2022 MIT许可