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.
-
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 loggingnoslone– noslone2013-05-03 11:50:28 +00:00Commented May 3, 2013 at 11:50
-
Let's just say I have to work with v1.3.Captain Kenpachi– Captain Kenpachi2013-05-03 11:53:52 +00:00Commented May 3, 2013 at 11:53
-
In that case, you should try that powerfull search engine. first resultnoslone– noslone2013-05-03 11:57:01 +00:00Commented 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.Captain Kenpachi– Captain Kenpachi2013-05-03 12:02:49 +00:00Commented May 3, 2013 at 12:02
-
What is a "Log table element"? Are you talking about view elements or database tables?ndm– ndm2013-05-03 13:17:29 +00:00Commented May 3, 2013 at 13:17
1 Answer
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.