Created
June 26, 2013 15:12
-
-
Save andrew-kzoo/5868250 to your computer and use it in GitHub Desktop.
PDOHandler to log records to a database https://github.com/Seldaek/monolog/blob/master/doc/extending.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| 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( | |
| 'time' => $record['datetime']->format('Y-m-d H:i:s'), | |
| 'channel' => $record['channel'], | |
| 'level' => $record['level'], | |
| 'level_name' => $record['level_name'], | |
| 'message' => $record['message'], | |
| 'context' => json_encode($record['context']), | |
| 'extra' => json_encode($record['extra']), | |
| 'formatted' => $record['formatted'], | |
| )); | |
| } | |
| private function initialize() | |
| { | |
| $this->pdo->exec(<<<CREATE | |
| CREATE TABLE IF NOT EXISTS | |
| monolog | |
| ( | |
| time DATETIME, | |
| channel VARCHAR(255), | |
| level INTEGER, | |
| level_name VARCHAR(255), | |
| message LONGTEXT, | |
| context LONGTEXT, | |
| extra LONGTEXT, | |
| formatted LONGTEXT | |
| ) | |
| CREATE | |
| ); | |
| $this->statement = $this->pdo->prepare(<<<INSERT | |
| INSERT INTO | |
| monolog | |
| ( | |
| time, | |
| channel, | |
| level, | |
| level_name, | |
| message, | |
| context, | |
| extra, | |
| formatted | |
| ) | |
| VALUES | |
| ( | |
| :time, | |
| :channel, | |
| :level, | |
| :level_name, | |
| :message, | |
| :context, | |
| :extra, | |
| :formatted | |
| ) | |
| INSERT | |
| ); | |
| $this->initialized = true; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment