Write to a log file with PHP
As you certainly know, PHP can be used for command line scripting. In my case, I caught myself writing log PHP function many times so I finally decided to write Logging PHP class. After Logging class initialization, first call of lwrite method will open log file for writing. Log file will be closed implicitly when PHP script ends.
Before you read further, I also wrote a post how to Log PHP errors to the separate file, if you are looking for such information.
How to use Logging class:
// Logging class initialization
$log = new Logging();
// write message to the log file
$log->lwrite('Test message');
Logging class:
/**
* Logging class:
* - contains lopen and lwrite methods
* - lwrite will write message to the log file
* - first call of the lwrite will open log file implicitly
* - message is written with the following format: hh:mm:ss (script name) message
*/
class Logging{
// define log file
private $log_file = '/tmp/logfile.txt';
// define file pointer
private $fp = null;
// write message to the log file
public function lwrite($message){
// if file pointer doesn't exist, then open log file
if (!$this->fp) $this->lopen();
// define script name
$script_name = pathinfo($_SERVER['PHP_SELF'], PATHINFO_FILENAME);
// define current time
$time = date('H:i:s');
// write current time, script name and message to the log file
fwrite($this->fp, "$time ($script_name) $message\n");
}
// open log file
private function lopen(){
// define log file path and name
$lfile = $this->log_file;
// define the current date (it will be appended to the log file name)
$today = date('Y-m-d');
// open log file for writing only; place the file pointer at the end of the file
// if the file does not exist, attempt to create it
$this->fp = fopen($lfile . '_' . $today, 'a') or exit("Can't open $lfile!");
}
}
For PHP prior to version 5.2.0 you will have to replace or change line with built-in PHP function pathinfo() because PATHINFO_FILENAME constant was added in PHP 5.2.0
// for PHP 5.2.0+ $script_name = pathinfo($_SERVER['PHP_SELF'], PATHINFO_FILENAME); // for PHP before version 5.2.0 $script_name = basename($_SERVER['PHP_SELF']); $script_name = substr($script_name, 0, -4); // php extension and dot are not needed
If you want to send a message to the PHP's system logger, please see the error_log PHP command.
Related posts
- Resize images with PHP script
- Reading multiple parameters in PHP
- Week list for the current date in PHP
- Backup Linux server with PHP
- Find files with PHP
looks good, but it could be improved by using the built-in PHP function pathinfo() to get your $script_name
PHP has a really big list of functions and now I know one function more - thank you Steve. After I improved lwrite method with pathinfo, my PHP code is shorter and simpler.
How to write only error in log file?
Thank You.
Vasim,
you can specify error log path in /etc/php.ini like I described in Log PHP errors to the separate file or you can define your own error handling and logging functions.
Here is part from the PHP error handling and logging manual:
"With the logging functions, you can send messages directly to other machines, to an email (or email to pager gateway!), to system logs, etc., so you can selectively log and monitor the most important parts of your applications and websites. The error reporting functions allow you to customize what level and kind of error feedback is given, ranging from simple notices to customized functions returned during errors."
PHP manual also contains nice example of using the error handling capabilities in PHP.
Hope this informations will help you.
Thanks for this trick !
Hi! thanks for shareing this class. Exactely what I was looking for.
can i read a log file created by a web serve?
@viettel - Yes you can read any file with PHP if you have read permissions. Please be aware that access_log can be huge (like 100MB or more) and reading / processing will be resource intensive task.
This is very nice!!
Now I want to put the error lines in red colour should it be possible?
@Abhishek - My intention was to write log PHP output to the ordinary file and to read it with text editor (like vi). But if you want to read log file with browser - you can modify PHP script to wrap lines with <span style="color:red"></span> ... This lines will be red.
hello, i'm still beginner in php. i want my php to use data in log file and filter it on linux platform. For example i want my php to take data in log file in my honeypot. then the raw data will be filter into certain category. can anybody help me because i need to use it into my project.
wow, great job, thank you for publishing this
Thanks for sharing. Though couple questions. Do you run in any concurency issues? Shoul'd you lock the file? (Not sure how it is done with PHP). Also, isn't similar can be achieved simply by using
file_put_contents function?
This is simple function and only one line is written per logging so I assume that concurrency (file locking) wasn't needed in such case. Anyway, PHP has flock function and is possible to extend Logging class to support file locking. And about file_put_contents ... You're probably right, but file_put_contents is available since PHP5 so this will not work on PHP4 engines - on the other hand, who still uses PHP4
Nice script! I've modified your logger class so that I can pass a different log file to use in the constructor. Thanks for sharing!