Cakephp ORM and Logging Queries

Working with cakephp/orm library, I needed to log all the queries. Cakephp provides a way to do it via cakephp/log.

1
2
3
4
5
6
7
8
use Cake\Log\Log;

Log::config('queries', [
  'className' => 'File',
  'path' => '/my/log/path/',
  'file' => 'app',
  'scopes' => ['queriesLog']
]);

But you are not limited, if you need to configure it to a PSR-3 logger like monolog/monolog

1
2
3
4
5
6
7
8
9
use Cake\Log\Log;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;

Log::config('default', function () {
    $log = new Logger('cli');
    $log->pushHandler(new StreamHandler('php://stdout'));
    return $log;
});

That was pretty simple and it logs to cli.

Thank you José Lorenzo Rodríguez for providing the necessary information.

How about logging the queries to a debugbar?

Install fabfuel/prophiler

1
composer require fabfuel/prophiler

Configuring debugbar

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
use Cake\Log\Log;
use Fabfuel\Prophiler\Profiler;
use Fabfuel\Prophiler\Toolbar;
use Fabfuel\Prophiler\DataCollector\Request;
use Fabfuel\Prophiler\Adapter\Psr\Log\Logger;

$profiler = new Profiler();
$toolbar = new Toolbar($profiler);
// add your data collectors
// $toolbar->addDataCollector(new Request());

Log::config('db', function () use ($profiler) {
  $log = new Logger($profiler);
  return $log;
});

Using a PSR-7 framework like zend-expressive, bitExpert/prophiler-psr7-middleware is your friend.

cakephp, debugbar, logging, orm, psr-3, psr-7

Comments