Added long running query tag

- Now if queries run for longer than 0.5 s, a tag will be appended to the log [LONG RUNNING QUERY]
- If app.db_log_only_long is set to true in the .env file, the db log will only show long running queries.
This commit is contained in:
objecttothis
2023-11-30 14:52:32 +04:00
committed by jekkos
parent e90029dea6
commit 3da79fc47c
2 changed files with 32 additions and 7 deletions

View File

@@ -28,6 +28,13 @@ class App extends BaseConfig
*/
public $db_log_enabled = false;
/**
* DB Query Log only long running queries
*
* @var bool
*/
public $db_log_only_long = false;
/**
* Defines whether to require/reroute to HTTPS
*

View File

@@ -12,22 +12,40 @@ class Db_log
// check if database logging is enabled (see config/config.php)
if($config->db_log_enabled)
{
$db = Database::connect();
$filepath = WRITEPATH . 'logs/Query-log-' . date('Y-m-d') . '.log';
$handle = fopen($filepath, "a+");
$message = $this->generate_message($config);
$sql = $db->getLastQuery();
$execution_time = $this->convert_time($sql->getDuration());
$sql .= " \n Affected rows: " . $db->affectedRows()
. " \n Execution Time: " . $execution_time['time'] . ' ' . $execution_time['unit'];
fwrite($handle, $sql . "\n\n");
if(strlen($message) > 0)
{
fwrite($handle, $message . "\n\n");
}
// Close the file
fclose($handle);
}
}
private function generate_message($config): string
{
$db = Database::connect();
$last_query = $db->getLastQuery();
$affected_rows = $db->affectedRows();
$execution_time = $this->convert_time($last_query->getDuration());
$message = $last_query->getQuery()
. " \n Affected rows: $affected_rows"
. " \n Execution Time: " . $execution_time['time'] . ' ' . $execution_time['unit'];
$long_query = ($execution_time['unit'] === 's') && ($execution_time['time'] > 0.5);
if($long_query)
{
$message .= ' [LONG RUNNING QUERY]';
}
return $config->db_log_only_long && !$long_query ? '' : $message;
}
private function convert_time(float $time): array
{
$unit = 's';