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
-
- require __DIR__ . '/vendor/autoload.php';
- use Monolog\Logger;
- use Monolog\Handler\StreamHandler;
- use Monolog\Handler\BufferHandler;
- use Monolog\ErrorHandler;
- use Monolog\Processor\MemoryUsageProcessor;
-
-
- $logger = new Logger('error_logger');
- $stream = new StreamHandler(__DIR__.'/error.log', Logger::ERROR);
- $logger->pushHandler(new BufferHandler($stream, 10, Logger::DEBUG, true, true));//用BufferHandler设置同一请求下日志数达到10条再写一次文件
- ErrorHandler::register($logger);
-
- //code...
monolog完全按照面向对象思想写的,它本身有符合fig的psr-3 prs-4规则,所以扩展起来非常方便,下面是作者文档上写的一个日志入数据库的一个例子
[php] view plain copy
- use Monolog\Logger;
- use Monolog\Handler\AbstractProcessingHandler;
-
- class PDOHandler extends AbstractProcessingHandler
- {
- private $initialized = false;
- private $pdo;
- private $statement;
-
- public function __construct(PDO $pdo, $level = Logger::DEBUG, $bubble = true)
- {
- $this->pdo = $pdo;
- parent::__construct($level, $bubble);
- }
-
- protected function write(array $record)
- {
- if (!$this->initialized) {
- $this->initialize();
- }
-
- $this->statement->execute(array(
- 'channel' => $record['channel'],
- 'level' => $record['level'],
- 'message' => $record['formatted'],
- 'time' => $record['datetime']->format('U'),
- ));
- }
-
- private function initialize()
- {
- $this->pdo->exec(
- 'CREATE TABLE IF NOT EXISTS monolog '
- .'(channel VARCHAR(255), level INTEGER, message LONGTEXT, time INTEGER UNSIGNED)'
- );
- $this->statement = $this->pdo->prepare(
- 'INSERT INTO monolog (channel, level, message, time) VALUES (:channel, :level, :message, :time)'
- );
-
- $this->initialized = true;
- }