Last active
August 29, 2015 14:03
-
-
Save Andrewpk/c60ba3385e9050d84829 to your computer and use it in GitHub Desktop.
A PDO monolog handler implementation. Almost done (it needs tests). It also works with Postgres' json data type.
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 | |
namespace AK\Monolog\Handler; | |
use Monolog\Handler\AbstractProcessingHandler; | |
use Monolog\Logger; | |
use Monolog\Formatter\JsonFormatter; | |
class PDOHandler extends AbstractProcessingHandler | |
{ | |
private $dbh; | |
private $table; | |
private $column; | |
private $sth = null; | |
public function __construct(\PDO $dbh, $table = null, $column = null, $level = Logger::DEBUG, $bubble = true) | |
{ | |
if ($table === null || $column === null) { | |
throw new \InvalidArgumentException('$table and $column are required'); | |
} else { | |
$this->dbh = $dbh; | |
$this->table = $table; | |
$this->column = $column; | |
parent::__construct($level, $bubble); | |
} | |
} | |
public function __destruct() | |
{ | |
if ($this->sth !== null) { | |
$this->sth->closeCursor(); | |
} | |
unset($this->sth, $this->dbh, $this->table, $this->column); | |
} | |
protected function write(array $record) | |
{ | |
try { | |
if ($this->sth === null) { | |
$sth = $this->dbh->prepare("INSERT INTO $this->table($this->column) VALUES (?)"); | |
$this->sth = $sth; | |
} | |
$this->sth->bindParam(1, $record['formatted']); | |
$result = $this->sth->execute(); | |
} catch (PDOException $e) { | |
//Throwing Standard Exception in case private data in PDOException | |
//Might want to change this to something more reasonable? | |
throw new Exception("Problem with PDO Connection."); | |
} | |
if (!$result) { | |
throw new Exception("Problem adding log entry to database."); | |
} | |
} | |
protected function getDefaultFormatter() | |
{ | |
return new JsonFormatter(JsonFormatter::BATCH_MODE_JSON, false); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment