Hi everyone,
I am literally pulling my hair out trying to figure out for the life of me how to write simple print statements to a custom log file. I have spent hours on this and just can't do it.
If anyone can give me a heads up it would be appreciated.
I have set all the correct settings in the php.ini file to output errors to a customer log file. The file being under my home directory path in a linux install.
I have created the file but no printed statements ever make it into the file.
All I want to do is print some statements into a text file. No fancy error reporting. Just some plain printing of this or that message I make up into a text file. How hard can this be?
Any input or suggestions would be appreciated.
Thanks.
Carlos
Going nuts trying to write errors to custom log file!
Moderator: General Moderators
- Chris Corbyn
- Breakbeat Nuttzer
- Posts: 13098
- Joined: Wed Mar 24, 2004 7:57 am
- Location: Melbourne, Australia
Re: Going nuts trying to write errors to custom log file!
The core steps are:
1. Open the file with fopen() using "a" as the mode (append)
2. Write to the file with fwrite()
3. Close the file
Realistically these core steps need more checking though since two requests at the same time may try to write simultaneously (race condition). So extra steps are:
4. Make sure each of the operations returns true (i.e. they succeed)
5. Use flock to gain an exclusive lock on the file so you know you're the only process writing to it
Now you can just sprinkle your code with log_message() calls.
1. Open the file with fopen() using "a" as the mode (append)
2. Write to the file with fwrite()
3. Close the file
Realistically these core steps need more checking though since two requests at the same time may try to write simultaneously (race condition). So extra steps are:
4. Make sure each of the operations returns true (i.e. they succeed)
5. Use flock to gain an exclusive lock on the file so you know you're the only process writing to it
Code: Select all
<?php
function log_message($message, $path) {
//Open the file in append mode
if (!$fp = fopen($path, 'a')) {
trigger_error('Failed opening file for writing: ' . $path, E_USER_NOTICE);
return;
}
//Get a write lock on it (so race conditions don't occur)
if (flock($fp, LOCK_EX)) {
//Write your message
if (!fwrite($fp, $message)) {
trigger_error('Failed writing to file: ' . $path, E_USER_NOTICE);
}
} else {
trigger_error('Failed to gain exclusive lock for writing: ' . $path, E_USER_NOTICE);
}
//Close the file
fclose($fp);
}
Code: Select all
<?php
log_message("Line one\n", '/tmp/logfile.log');
log_message("Next line\n", '/tmp/logfile.log');