Skip to content

Instantly share code, notes, and snippets.

@tuupola
Last active June 12, 2017 04:33
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tuupola/03a5bc0cea694b972b58 to your computer and use it in GitHub Desktop.
Save tuupola/03a5bc0cea694b972b58 to your computer and use it in GitHub Desktop.
Monolog logging with Spot2 and Slim
<?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);
}
}
<?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