Log Errors in CakePHP
Hello friends, welcome to FindNerd. Today we are going to discuss how to log errors in the database in CakePHP. Let's discuss the default behaviour of CakePHP's error logging.
LOG FILES
The default Cakelog setting writes log to a file /tmp/logs/
directory in case of CakePHP . With the help of log files, you will be able to see the errors.
For Example:
CakeLog::write('error', 'Your error message goes here.');
This error message will be written to the following file /tmp/logs/error.log
Error logging is very easy in CakePHP. There are 2 different ways for writing logs to the log files.
First method: Use the static CakeLog::write() method.
CakeLog::write('debug', 'Error message here.');
Second method: log() method is available which is used as shortcut function. log() extends Object and it can be used in any class. You can call this internally CakeLog::write() .This will be called on Calling log() function.
$this->log("Your error message goes here.", 'debug');
If we use error logging, then it has come with the disadvantages like: Dirty look, large size, reading errors are bit tough, searching is an hectic task. To overcome these disadvantages we can store these error messages in the database instead of the log files. To accomplish this, you can download the plugin : "CakePHP-DatabaseLogger-Plugin" . Let's start by downloading the plugin from the following : DatabaseLogger
(Note: original plugin source : CakePHP-DatabaseLogger-Plugin)
Next step is to extract this zip file and then copy DatabaseLogger folder and paste it in app/Plugin
folder. Now you need to copy the database_logger.php
file and paste it to app/Config
folder. After this run the schema which is located at app/Plugin/DatabaseLogger/Config/Schema/DatabaseLogger.sql
, This SQL file needed to run into the database to create logs table. Add the following code below in app/Config/bootstrap.php
file.
App::import('Log','CakeLog');
CakePlugin::load('DatabaseLogger');
CakeLog::config('default', array(
'engine' => 'DatabaseLogger.DatabaseLog'
));
Also, you need to comment the lines given below which is the default file logging option.
CakeLog::config('debug', array(
'engine' => 'File',
'types' => array('notice', 'info', 'debug'),
'file' => 'debug',
));
HOW TO USE
This can be used anywhere in the app. If you call $this->log() or CakeLog::write the database logger will be used.
For Example:
$this->log(' Error message will be logged in the database','error');
OR
CakeLog::write('error', 'Error message will be logged in the database');
Final step is to navigate to http://localhost/database_logger/logs to view,delete or search your logs.
Thanks for reading.
0 Comment(s)