JoeGo
JoeGo

Reputation: 293

Customize logging - CakePHP (1.3)

I would like to extend the cakephp logging facility. Using

$this->log($msg, $level)

you can log a $msg with $level to tmp/logs/$level.log.

How I would like to use logging is:

  1. Separate functions for different levels, e.g. $this->debug($msg) for $this->log($msg, 'debug') and $this->error($msg) for $this->log($msg, 'error') etc. for logging.
  2. Automatically put the name of the class in front of a message, e.g. $this->debug($msg) will lead to "MyClass: $msg" if $this is of type "MyClass".

I know I can extend the functionality by extending AppModel, AppController etc., but as I need the functionality everywhere in my application, I would rather need to extend cakephp's Object - but didn't find a stable mechanism for that (don't want to change it in the cake/ folder). I though about implementing a new class for that functionality, but I'm not sure how to make that available in cakephp.

Could you please give me some hints where/how I can implement these extensions neatly?

Upvotes: 3

Views: 2063

Answers (2)

drfloob
drfloob

Reputation: 3274

In addition to what deizel said (great writeup, by the way, deizel), you don't have to use Cake's logger. You're welcome to use any logging system you'd like. Choosing an existing logging framework that you like would probably be the safest bet. bootstrap.php is a good place to do any require calls or initializations.

Otherwise, if you'd like to do things 'in' Cake, I'd recommend creating a plugin with a trio of logging interfaces: a Component, a Behavior, and a Helper. That way the logging functionality would be available in your models, views, and controllers. As for how to code it, I like the idea making the cake classes thin proxies to your real logging class, and using the magic method __call() in your proxies to parse logging requests and environment, then forward on that information to your logger to handle uniformly.

You'd be able to write things like $this->MyLogger->oops("stubbed my toe") and potentially have an oops.log file with your messages and whatever additional information (calling controller/view/model, time&date, etc.) you'd like included.

Upvotes: 2

deizel.
deizel.

Reputation: 11232

Global convenience methods

Well, you can't really do monkey patching in PHP (5.2 at least), and that is probably a good thing for the the developers that have to maintain your code after you are gone. :)

CakePHP - being an MVC framework with strict conventions - makes it hard for you to break the MVC paradigm by only allowing you the extend the parts you need in isolation (ie. AppModel, AppController, etc.) and keeping the object-orientated foundation untouched in the core (making it hard to add code that "can be used everywhere" for potential misuse).

As for adding functionality that transcends all the MVC separation, the place for this is app/config/bootstrap.php. When you place code here it seems clear that it is not part of the framework (quite rightly so), but allows you to add these sort of essentials before CakePHP even loads. A few options of what to do here might be:

  1. Create a function (eg. some custom functions such as error() that call CakeLog::write() in the way you like.)
  2. Load a class (eg. load your very own logging class called something like.. Log, so you can call Log::error() in places)
  3. See below:

The logger API

Cake does allow for many customisations to be made to things like the logger, but unfortunately the API exposed to us is already defined in the core in this case. The API for logging in CakePHP is as follows, and you can use either approach anywhere you like (well, the former only in classes):

$this->log($msg, $level) // any class extending `Object` inherits this
// or
CakeLog::write($level, $message); // this is actually what is called by the above

The arbitrary $level parameter that you are trying to eliminate is actually quite a powerful feature:

$this->log('Cannot connect to SMTP server', 'email'); // logs to app/logs/email.log
// vs
$this->email('Cannot connect to SMTP server'); // ambiguous - does this send emails?

We just created a brand new log type without writing an extra line of code and it's quite clear what the intention of our code is.

Customising the logger

The core developers had the foresight to add a condition allowing us to completely replace the logger class should we wish to:

function log($msg, $type = LOG_ERROR) {
    if (!class_exists('CakeLog')) { // winning
        require LIBS . 'cake_log.php';
    }
    // ...

As you can see, the core CakeLog class only gets instantiated if no such class exists, giving you the opportunity to insert something of your own creation (or an exact copy with a few tweaks - though you would want to sync changes with core - manually - when upgrading):

// app/config/bootstrap.php
App::import('Lib', 'CakeLog'); // copy cake/libs/cake_log.php to app/lib/cake_log.php

The above would give you full control over the implementation of the CakeLog class in your application, so you could do something like dynamically adding the calling class name to your log messages. However, a more direct way of doing that (and other types of logging - such as to a database) would be to create a custom log stream:

CakeLog::config('file', array(
    'engine' => 'FileLog', // copy cake/libs/log/file_log.php to app/libs/log/file_log.php
));

TL;DR - Although you can load your own code before CakePHP bootstraps or for use in isolation in each of the MVC layers provided, you shouldn't tamper with the object hierarchy provided by the core. This makes it hard to add class methods that are inherited globally.

My advice: use the API given to you and concentrate on adding more features instead of syntactical subtleties. :)

Upvotes: 2

Related Questions