【发布时间】:2018-05-24 22:02:33
【问题描述】:
令人惊讶的是,codeigniter v2 和 v3 都没有它的文档。我刚刚从教程中自己发现了代码link。该教程并不完美,也无法正常工作,但我倾向于改进它。
我指的是 $this->db->query_times 和 $this->db->queries。我很惊讶地发现这些都有效。
现在您可以在 Codginiter 钩子中使用这些来确定使用 $this->db->queries 执行的查询以及使用 $this-> 执行的时间db->query_times 并在 post 控制器之后实现 hook
$this->db->queries 在 codeigniter v3 中的结果是
Array
(
[0] => SELECT GET_LOCK('0ae383feca87611f9ef779f13ae5d3f3', 300) AS ci_session_lock
[1] => SELECT `data`
FROM `ci_sessions_3`
WHERE `id` = '9sh99dhtp1i51t21g498gerhem4e6gl6'
[2] => SELECT * FROM `tradelog` WHERE status=1
)
$this->db->query_times 在 codeigniter v3 中的结果是
Array
(
[0] => 0.00015497207641602
[1] => 0.0003199577331543
[2] => 0.0003359317779541
)
两个数组具有相同数量的索引,因为第一个数组包含执行的查询,第二个数组包含这些查询的执行时间。
我有一个小问题是确定query_time格式正确转换为秒或分钟。
会这样使用
(如果你对它的使用方式不感兴趣,请忽略它)
我将使用它在开发环境中的 queries.log.txt 文件中记录我的所有查询,方法是在 codeigniter 中的后控制器挂钩后挂钩 LogQueryHook 类。 p>
转到 application/config/config.php 并更改它
$config['enable_hooks'] = FALSE;
到这里
switch (ENVIRONMENT)
{
case 'development':
$config['enable_hooks'] = TRUE;
break;
case 'testing':
case 'production':
default:
$config['enable_hooks'] = FALSE;
break;
}
所以只有在开发中你才会记录所有查询。
现在转到 application/config/hooks.php 以在发布系统后挂钩您的 LogQueryHook 类。只需复制粘贴此代码即可。
$hook['post_system'][] = array(
'class' => 'LogQueryHook',
'function' => 'log_queries',
'filename' => 'LogQueryHook.php',
'filepath' => 'hooks'
);
在应用程序文件夹的钩子文件夹中创建一个文件名“LogQueryHook.php”。 它看起来像这样 application\hooks\LogQueryHook.php 现在粘贴此代码以记录每个查询的执行时间。
class LogQueryHook
{
function log_queries()
{
$CI = &get_instance ();
$times = $CI->db->query_times;
$output = null;
$queries = $CI->db->queries;
$date_now = date('Y-m-d h:i:sa');
/** Spaces are given for proper alignment of text */
if (count ($queries) == 0) {
$output .= $date_now . " no queries\n";
} else {
foreach ($queries as $key => $query) {
$took = round (doubleval ($times[$key]), 3);
// I need to improve this line to record time properly
// and I don't know in which format codeginiter is giving me time either its is seconds or miliseconds.
$output .= $date_now . " ===[took:{$took}]\n";
$query = str_replace (array("\r\n", "\r", "\n", "\\r", "\\n", "\\r\\n"), "\n ", " " . $query);
$output .= $query . "\n\n\n";
}
}
$CI->load->helper ('file');
if (!write_file (APPPATH . "/logs/queries.log.txt", $output, 'a+')) {
log_message ('debug', 'Unable to write query the file');
}
}
}
之后在开发环境中运行任意页面,所有查询都会记录在application\logs\queries.log.txt文件中。
【问题讨论】:
-
你的问题是什么?
-
我有一个小问题,就是确定 query_time 格式以正确转换为秒或分钟。我只是不知道它是以纳秒、微秒或毫秒为单位还是仅仅以秒为单位,因为没有文档。
-
请先阅读问题
-
我不明白。 0.00015497207641602 表示 0.00015497207641602 秒。你想要的输出是什么? ;)
-
是的,我确定看看@github.com/bcit-ci/CodeIgniter/blob/develop/system/database/… 并看看下面的代码sandbox.onlinephpfunctions.com/code/… - 它基本上是相同的机制;)
标签: php codeigniter time codeigniter-2 codeigniter-3