0

I need to override the default CakePHP Log() function so that it writes to the database instead of a file. I don't care whether or not this is a good idea, I simply want to know how I would go about firstly overriding what happens when I go $this->Log("blah") and secondly how I would reference the Log table element form within the app_controller or other class I am performing the override in.

5
  • You should consider to upgrade your CakePHP version. 2.x is much faster than 1.x. It has also a lot more possibilities, one of them is database logging Commented May 3, 2013 at 11:50
  • Let's just say I have to work with v1.3. Commented May 3, 2013 at 11:53
  • In that case, you should try that powerfull search engine. first result Commented May 3, 2013 at 11:57
  • It doesn't answer my question. I am not one of those people who add a plugin each time I want a new feature. Commented May 3, 2013 at 12:02
  • What is a "Log table element"? Are you talking about view elements or database tables? Commented May 3, 2013 at 13:17

1 Answer 1

2

First, create a table in your database to store the logs:

CREATE TABLE IF NOT EXISTS `logs` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `type` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `message` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;

In the app/model directory create a file called log.php and put this code in it:

<?php

class Log extends AppModel {

    var $name = 'Log';

    function write($type, $message) {
        $this->save(array(
            'Log' => array(
                'type' => $type,
                'message' => $message
            )
        ));
    }

}

That's the logging engine but it's also a model so you can customise it to use a different datasource or table. The only requirement is the write function that accepts those parameters.

Edit app/config/bootstrap.php and add this code at the end of the file:

App::Import('Model','Log');

CakeLog::config('otherFile', array(
    'engine' => 'Log',
    'model' => 'Log',
));

You can now use the log with $this->log($type, $message); or $this->log($message); which defaults to the error type.

There is some info about creating custom logging engines in the CakePHP manual.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. It's much more elegant than the solution I came up with in the end.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.