I have what is probably an over-engineering question. I have some PHP code that logs messages to a file. We've been having a problem with the file having the wrong perms from time to time. While we're troubleshooting that, I am writing a work-around for that in the logging function, changing the unix perms and owners on the log file.
So my code looks like this:
function log($message) {
if ( FALSE === file_put_contents(log_path(), $message) ) {
chown(log_path(), 'apache');
chgrp(log_path(), 'www-data');
chown(log_path(), 0770);
// now I'm repeating this line
if ( FALSE === file_put_contents(log_path(), $message) ) {
// log error to database
db_log($message);
}
}
}
In the interest of DRY, can I somehow change the code to avoid repeating the line if ( FALSE === file_put_contents(log_path(), $message) ) {
? Of course, I can't use recursion, because that would go on forever.
if
condition requires the threech
lines in order to work properly, then your code is already DRY.log($message)
within the function, it would continuously try to log, then fail, log, then fail, etc. I could put a static variable, or add an argument as a termination condition, but I never want it to recurse more than once anyway. Have I saved anything, then, over just repeating the line? I suppose again I come back to the thought that I am probably over-thinking things.function log($message) { syslog(LOG_INFO, $message); }
is a far better answer, and it puts the hard part inrsyslog
et al., where it belongs.