欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

awesome PHP之monolog

程序员文章站 2022-04-20 18:31:02
...
monolog是php下比较全又容易扩展的记录日志组件。目前有包括Symfony 、Laravel、 CakePHP等诸多知名php框架都内置了monolog。可以通过github clone https://github.com/Seldaek/monolog.git 或者 composer安装 require monolog/monolog '~1.7'。monolog代码结果如下:

ErrorHandler.php(设置程序的error hander 、exception hander 给mogolog接管)
Formatter/ (内置的日志显示格式)
Handler/ (各种日志处理类,如写文件、发邮件、写socket、写队列等)
Logger.php (log 处理接口)
Processor/ (内置的处理日志类)
Registry.php --


一个例子用在线上错误日志记录上,可以替换默认错误日志的处理方式

[php] view plain copy

  1. require __DIR__ . '/vendor/autoload.php';
  2. use Monolog\Logger;
  3. use Monolog\Handler\StreamHandler;
  4. use Monolog\Handler\BufferHandler;
  5. use Monolog\ErrorHandler;
  6. use Monolog\Processor\MemoryUsageProcessor;
  7. $logger = new Logger('error_logger');
  8. $stream = new StreamHandler(__DIR__.'/error.log', Logger::ERROR);
  9. $logger->pushHandler(new BufferHandler($stream, 10, Logger::DEBUG, true, true));//用BufferHandler设置同一请求下日志数达到10条再写一次文件
  10. ErrorHandler::register($logger);
  11. //code...

monolog完全按照面向对象思想写的,它本身有符合fig的psr-3 prs-4规则,所以扩展起来非常方便,下面是作者文档上写的一个日志入数据库的一个例子

[php] view plain copy

  1. use Monolog\Logger;
  2. use Monolog\Handler\AbstractProcessingHandler;
  3. class PDOHandler extends AbstractProcessingHandler
  4. {
  5. private $initialized = false;
  6. private $pdo;
  7. private $statement;
  8. public function __construct(PDO $pdo, $level = Logger::DEBUG, $bubble = true)
  9. {
  10. $this->pdo = $pdo;
  11. parent::__construct($level, $bubble);
  12. }
  13. protected function write(array $record)
  14. {
  15. if (!$this->initialized) {
  16. $this->initialize();
  17. }
  18. $this->statement->execute(array(
  19. 'channel' => $record['channel'],
  20. 'level' => $record['level'],
  21. 'message' => $record['formatted'],
  22. 'time' => $record['datetime']->format('U'),
  23. ));
  24. }
  25. private function initialize()
  26. {
  27. $this->pdo->exec(
  28. 'CREATE TABLE IF NOT EXISTS monolog '
  29. .'(channel VARCHAR(255), level INTEGER, message LONGTEXT, time INTEGER UNSIGNED)'
  30. );
  31. $this->statement = $this->pdo->prepare(
  32. 'INSERT INTO monolog (channel, level, message, time) VALUES (:channel, :level, :message, :time)'
  33. );
  34. $this->initialized = true;
  35. }