令人惊讶的是,codeigniter v2和v3都没有它的文档。我刚从这里的教程中发现了代码link。该教程并不完美,也不起作用,但我倾向于改进。
我所指的是 $ this-> db-> query_times 和 $ this-> db->查询。我惊讶地发现这些都在起作用。
现在,您可以在Codginiter钩子中使用这些来确定使用 $ this-> db->查询执行哪个查询以及使用 $ this花费了多少时间 - > db-> query_times 并在post controller
之后实现钩子codeigniter v3中 $ this-> db->查询的结果是
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
)
和codeigniter v3中 $ this-> db-> query_times 的结果是
Array
(
[0] => 0.00015497207641602
[1] => 0.0003199577331543
[2] => 0.0003359317779541
)
两个数组都有相同数量的索引,因为第一个数组包含执行的查询,第二个数组包含执行时间的这些查询。
我有一个小问题,即确定query_time格式以正确转换为秒或分钟。
(如果您对如何使用不感兴趣,请忽略
)我将使用它在开发环境中的 queries.log.txt 文件中记录我的所有查询,方法是在codeigniter中发布控制器挂钩之后挂钩 LogQueryHook 类。
转到 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"在应用程序文件夹中的hooks文件夹中 它看起来像 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 文件中。
答案 0 :(得分:2)
query_time
将返回秒作为输出($time_end - $time_start)
。
这些$time_end
和$time_start
都使用microtime
函数in PHP,参数设置为true。
microtime(TRUE)
:这会返回秒而不是微秒。