Last active
June 12, 2017 04:33
-
-
Save tuupola/03a5bc0cea694b972b58 to your computer and use it in GitHub Desktop.
Monolog logging with Spot2 and Slim
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 | |
/* This is old, use https://github.com/tuupola/dbal-psr3-logger instead. */ | |
namespace Doctrine\DBAL\Logging; | |
class MonologSQLLogger implements SQLLogger { | |
public $logger; | |
public $sql = ""; | |
public $start = null; | |
public function __construct($logger = null) { | |
$this->logger = $logger; | |
} | |
public function startQuery($sql, array $params = null, array $types = null) { | |
$this->start = microtime(true); | |
$this->sql = preg_replace_callback("/\?/", function($matches) use (&$params, &$types) { | |
$param = array_shift($params); | |
if (null === $param) { | |
return "NULL"; | |
} else { | |
return "'" . $param . "'"; | |
} | |
}, $sql); | |
} | |
public function stopQuery() { | |
$elapsed = microtime(true) - $this->start; | |
$this->sql .= " -- {$elapsed}"; | |
$this->logger->debug($this->sql); | |
} | |
} |
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 | |
/* Set timezone before instanting logs. */ | |
date_default_timezone_set("Europe/Helsinki"); | |
require_once __DIR__ . "/../vendor/autoload.php"; | |
/* Setup Monolog */ | |
use Monolog\Logger; | |
use Monolog\Handler\RotatingFileHandler; | |
$log = new Logger("slim"); | |
$formatter = new Monolog\Formatter\LineFormatter("[%datetime%] [%level_name%]: %message%\n"); | |
$rotating = new RotatingFileHandler(__DIR__ . "/../logs/slim.log", 0, Logger::DEBUG); | |
$rotating->setFormatter($formatter); | |
$log->pushHandler($rotating); | |
/* Setup Spot */ | |
$config = new \Spot\Config(); | |
$adapter = $config->addConnection("mysql", [ | |
"dbname" => "example", | |
"user" => "root", | |
"password" => "t00r", | |
"host" => "mysql.example.com", | |
"driver" => "pdo_mysql", | |
"charset" => "utf8" | |
]); | |
$spot = new \Spot\Locator($config); | |
/* Log SQL queries. Make sure logger is configured. */ | |
$logger = new Doctrine\DBAL\Logging\MonologSQLLogger($log); | |
$adapter->getConfiguration()->setSQLLogger($logger); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment