Home > PHP, Snippets of Code > Log rotation with file locking support

Log rotation with file locking support

PHP programmingSame code from previous entry but adding file locking support and making it simple by using file_put_contents PHP function. Writing function is called using two flags FILE_APPEND, LOCK_EX. Bitwise OR operator (inclusive or) expressed by “|” symbol is used to attach several flags into 1 byte field. LOCK_EX is supposed to guarantee transaction safety. Nevertheless there are claims against that, here. I have added the PHP function
clearstatcache() before measuring the size of current log file, in order to get instant proper measures. Otherwise rotation wouldn’t occur unless the PHP script would end and restart again.


// Appends lines to file locked and makes sure the file doesn't grow too much
function append_line_to_limited_text_file($text, $filename) {
	if (!file_exists($filename)) { touch($filename); chmod($filename, 0666); }
	if (filesize($filename) > 2*1024*1024) {
		$filename2 = "$filename.old";
		if (file_exists($filename2)) unlink($filename2);
		rename($filename, $filename2);
		touch($filename); chmod($filename, 0666);
	file_put_contents($filename, $text, FILE_APPEND | LOCK_EX);
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: