[nycphp-talk] Logging and file locking.
Rothe, Robert
rrothe at ana.net
Mon Jul 17 08:22:28 EDT 2006
Here is a very simple example of cooperative locking. Be sure to read
the PHP flock() docs concerning locking files opened with truncation --
which is not the case in this example.
This was written long ago and I recall testing it on both *nix and Win.
It creates a simple text log file with date, time, IP, and a passed
string. As a byproduct, it also auto-rotates daily.
function WriteLog( $s )
{
global $LOG_FILE_PATH;
$fn = $LOG_FILE_PATH.'log-'.date('Ymd');
// Open file (or create it). You should check for errors.
$fp = fopen( $fn, 'a' );
/*
* flock() will block waiting for another proc to release
acquired
* lock. You should probably check error condition here. See
docs
* for how to get EWOULDBLOCK flag.
*/
flock($fp, LOCK_EX );
/*
* See to end, write, and then close. Fclose() releases all
locks.
* Check for errors as appropriate.
*/
fseek( $fp, 0, SEEK_END );
fwrite($fp, date('Y-m-d H:i:s ')); // Write date/time
fwrite($fp, $_SERVER['REMOTE_ADDR'].' '); //Write IP
fwrite($fp, $s."\n"); // Write passed string and newline.
fclose($fp); // Close file which releases lock.
}
-----Original Message-----
From: talk-bounces at lists.nyphp.org [mailto:talk-bounces at lists.nyphp.org]
On Behalf Of David A.Roth
Sent: Sunday, July 16, 2006 9:43 PM
To: talk at lists.nyphp.org
Subject: [nycphp-talk] Logging and file locking.
When you do your own logging of various events to text logfiles created
from PHP, is file locking needed or does Linux handle this for us? I am
designing a new web application which will have multiple processes
appending to the same text logfile, and I'm concerned entries might get
lost.
If the answer is yes you need to do your own file locking, I'd be
interested to know how you handle the problem yourself and a pointer to
resources/discussion would be appreciated.
Thanks!
David Roth
_______________________________________________
New York PHP Community Talk Mailing List
http://lists.nyphp.org/mailman/listinfo/talk
NYPHPCon 2006 Presentations Online
http://www.nyphpcon.com
Show Your Participation in New York PHP
http://www.nyphp.org/show_participation.php
More information about the talk
mailing list