In PHP, we can create a log file and write to it, whenever needed. The following is the php file ‘logfile.php’.
<?php
class logfile{
function write($the_string )
{
if( $fh = @fopen( “/logfile.txt”, “a+” ) )
{
fputs( $fh, $the_string, strlen($the_string) );
fclose( $fh );
return( true );
}
else
{
return( false );
}
}
}
?>
In the above example, the class ‘logfile’ has a method ‘write’. This method will write the messages to the log file ‘logfile.txt’. Note that this file should exists before writing to it.
The below file uses ‘logfile.php’ to write the messages to the log file.
require ‘logfile.php’;
$lf = new logfile();
$lf->write(“Writing log file”);
echo “Data written to file”;
$lf->write(“Appending to log file”);
February 1, 2008 at 8:21 pm
Vidhya, This is really good. But how can we use the log4php libraries for logging in php. SugarCRM uses this for logging.
~Sanjay
February 5, 2008 at 8:47 am
Hi Sanjay,
You can find the usage of log4php library in this link
http://incubator.apache.org/log4php/qsg.html
Steps involved in writing content to log file
1: You need to extract the log4php library and copy the folder src/log4php to your own directory
2: In the base folder create the php file and log4php.properties file
Content of log4php.properties file:
log4php.appender.A2=LoggerAppenderRollingFile
log4php.appender.A2.layout=LoggerLayoutTTCC
log4php.appender.A2.File=./testlog.log
log4php.rootLogger=fatal, A2
log4php.rootLogger=error, A2
log4php.rootLogger=warn, A2
log4php.rootLogger=info, A2
log4php.rootLogger=debug, A2
February 6, 2008 at 7:05 pm
I will see the site.
Anyway thanks.
Sanjay
May 8, 2009 at 7:40 am
Thanks for the code. I added timestamp and crlf for easier viewing:
/**
* Write to log file
*
* @return true on success
*/
public function putLog($msg)
{
if ($fh = @fopen($_SERVER[‘DOCUMENT_ROOT’].”/dhl/log.txt”, ‘a+’)) {
$msg = “[“.date(‘d-m-Y H:i:s’).”] “.$msg.”\r”; //backslash r backslach n
fputs($fh, $msg, strlen($msg));
fclose($fh);
return true;
}
else {
return false;
}
}
August 3, 2009 at 1:14 pm
Hello Vidya,
This is a nice work. Congratulation . Expect more From you..
Bye anes
December 19, 2009 at 5:19 pm
Nice Blog Vidhya,
Indeed helpful for PHP beginners like me.
Is there any way to re-direct system generated php error messages to the same log file?
January 5, 2010 at 10:13 am
Hi,
Thanks.. I dont know the straight way of doing it. I think you can open the error_log file in which you can find all the system generated errors and write the contents of error_log to this file. Any other suggestion is highly appreciated.