Using php to write to a log file

五迷三道 提交于 2020-11-29 02:55:18

问题


First of I am very very very very bad with php so sorry for this question I have an application in which i would like to log some debug data and through my project i make a webrequest to my site storing the information in $msg i then want to write the data to my logfile.log on the site. i first used fopen fwrite fclose, but heard that file_put_contents would be better especially as i very likely will have several users trying to write to the file at once. Here's the code:

$msg = $_GET['w'];
$logfile= 'logfile.log';
echo file_put_contents($logfile,$msg, FILE_APPEND | LOCK_EX);

But as you might guess the code does nothing for me i got it working with fopen fwrite fclose but i wanted to add each user to a new line.

If any smart brain out there would help me I would appreciate it a ton.

Regards.

EDIT: @Jay This is how i tried applying it (opening php on the first line) EDIT: removed 'tag' from code due to a copy/paste error.

error_reporting(E_ALL); ini_set('display_errors', 1)
$msg = $_GET['w'];
$logfile= 'logfile.log';
echo file_put_contents($logfile,$msg, FILE_APPEND | LOCK_EX);

回答1:


Why not just use error_log()? With the message_type set to 3 (second parameter) the message will be written the the file specified in the third parameter:

$message = $_GET['w'];
$logfile = 'logfile.log';

// Debug: A line for verifying I have the message
echo "Writing message '$message' to logfile<br>";

error_log($message."\n", 3, $logfile);

// Debug: read back the log file to verify thatthe line has been written
readfile($logfile);

Note the newline appended to the message as error_log() doesn't do this for you.

Note also that permissions must be set to allow the web server to write to the target file. This is true whether using error_log() or file_put_contents()

PHP reference is here



来源:https://stackoverflow.com/questions/27952940/using-php-to-write-to-a-log-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!