Skip to content

Instantly share code, notes, and snippets.

An easy way to log session data and queries with Monolog and Hooks in codeigniter. Some of the code is taken from Profiler class in the core of CI. The hook must be post_controller or post_system
class LoggerHook
{
private $CI;
function __construct()
{
$this->CI =& get_instance();
}
public function log()
{
$logger = new Logger('my_logger');
$logger->pushHandler(new MongoDBHandler(new \MongoClient(), 'test', 'test'));
if (isset($this->CI->session)) {
$session_data = $this->CI->session->all_userdata();
} else {
$session_data = 'No session defined';
}
$dbs = array();
// Let's determine which databases are currently connected to
foreach (get_object_vars($this->CI) as $CI_object)
{
if (is_object($CI_object) && is_subclass_of(get_class($CI_object), 'CI_DB') )
{
$dbs[] = $CI_object;
}
}
$queries = array();
if (count($dbs) > 0){
foreach ($dbs as $db){
$driver_name = get_class($db);
if (count($db->queries) > 0){
foreach ($db->queries as $key => $val) {
$time = number_format($db->query_times[$key], 4);
$queries[$driver_name][] = array('time' => $time , 'query' => $val);
}
}
}
} else {
$queries = 'There is no queries to log';
}
$logger->addInfo(
'Session and queries',
array(
'session' => $session_data,
'database' => $queries'url' => $this->CI->uri->uri_string()
)
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment