Dibi logování sql dotazů do databáze
Upozornění: Tohle vlákno je hodně staré a informace nemusí být platné pro současné Nette.
- Chuchy
- Člen | 77
Ahoj,
rád bych logoval veškeré sql dotazy provedené uživatelem za request,
používám nette 2.0 a dibi knihovnu, mohl by mě někdo trochu navést?
Díky
Tak nakonec jsem to vyřešil takto:
libs\Logger\Logger.php
<?php
namespace Logger;
use DibiEvent;
use DibiConnection;
use Nette\Utils\Strings;
class Logger
{
private $sql = array();
private $user;
private $ip;
private $connections = array();
function __construct($container, array $database)
{
$_this = $this;
foreach ($database as $db)
{
$connection = $container->getservice($db)->connection;
$this->connections[$db] = $connection;
$connection->onEvent[] = function(DibiEvent $event) use ($_this) {
if(!empty($event->sql))
{
$_this->addSql($event->sql);
}
};
}
$this->ip = getenv('REMOTE_ADDR');
$this->user = $container->getservice('user')->id;
}
public function addSql($sql)
{
$this->sql[] = $sql;
}
public function save($db, $table)
{
$sql = $this->sql;
if(!empty($sql))
{
$serializeSql = serialize($sql);
$save = array('date_st%sql' => 'NOW()',
'login' => $this->user,
'ip' => $this->ip,
'sql_serialize' => $serializeSql);
$this->connections[$db]->query("INSERT INTO " . $table, $save);
}
}
}
bootstrap.php
$database = array('db1', 'db2');
foreach ($database as $db)
{
$configurator->onCompile[] = function ($c, $compiler) use ($db) {
$compiler->addExtension($db, new \DibiNetteExtension);
};
}
$logger = new \Logger\Logger($container, $database);
$container->application->onShutdown[] = function() use ($logger) {
$logger->save('db2', 'sql_logs');
};
Editoval Chuchy (25. 6. 2014 13:05)
- mkoubik
- Člen | 728
Principiálně nějak takhle:
$logger = new \SplObjectStorage();
$dibi->onEvent[] = function(DibiEvent $event) {
$logger->attach($event);
};
$application->onShutdown[] = function(Application $app, $e = null) {
foreach ($logger as $event) {
$dibi->insert('queries', array(
'sql' => $event->sql,
'time' => $event->time,
));
}
};