问题
I am running Centos/Apache with PHP 5.5.14, and am using syslog to write to a log file as follows:
syslog(LOG_INFO,'Some message');
The logs are being written to /var/log/messages
and look like Aug 10 15:48:16 devserver httpd: Some message
, however, the log file is also cluttered with a bunch of logs that look like Aug 10 15:48:21 devserver kernel: usb 1-1.2: USB disconnect, device number 83
.
How do make PHP sent logs to its own dedicated log file?
回答1:
Before calling the function syslog, you should call openlog and specify the “syslog tag”. With this framework, the messages are tagged and you can use the system logger (rsyslog, syslog-ng, etc.) to send these messages to a specific log file, send them to a specific log server, send an email for emergency messages, etc.
This blog post “Using syslog for your php applications” gives more details on how to setup the whole thing.
回答2:
Syslog dumps data into a singular log file. A lot of system services, even the kernel as you pointed out, dumps to syslog, and by extension, the same log file.
If you want to take advantage of your own personal log file, you'll need to use filesystem IO functions.
Example:
<?php
function writeLog($message) {
$handle = fopen('/var/log/project1/myproject1.log', 'a');
$line = '[' . date('Y-m-d H:i:s T') . '] ' . $message . "\n";
fwrite($handle, $line);
fclose($handle);
}
You should take care to make sure you don't fopen()
and then subsequently fclose()
a lot, since that will severely slow down your code. You should only fopen()
when you need to write/read, and then leave the file handle open until your PHP code exits (or let PHP do garbage collection for you).
You'll also need to make sure your web server has sufficient privileges to write to the /var/log/project1/
directory, or at the very least, append/write access to the filename specified. This includes making sure SELinux is happy if you have it enabled.
As a bonus, you could throw your custom log file into logrotate daemon's config and have your logs automatically rotated, compressed, archived, and whatnot.
来源:https://stackoverflow.com/questions/25233789/sending-php-syslog-to-a-specific-linux-log-file