简体   繁体   English

使用php写入日志文件

[英]Using php to write to a log file

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. 首先,我对php非常非常非常非常不好,所以对这个问题感到抱歉,我有一个应用程序,我想在其中记录一些调试数据,并通过我的项目向我的网站发出webrequest,将信息存储在$ msg中,然后我想要将数据写入站点上的我的logfile.log。 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. 我首先使用fopen fwrite fclose,但听说file_put_contents会更好,尤其是因为我极有可能有多个用户试图一次写入文件。 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. 但是,您可能会猜到代码对我没有任何帮助,但我使用fopen fwrite fclose使它起作用,但是我想将每个用户添加到新行中。

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. 编辑:@杰伊这就是我尝试应用它的方式(在第一行打开php)编辑:由于复制/粘贴错误,从代码中删除了“标签”。

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);

Why not just use error_log() ? 为什么不只使用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_type设置为3 (第二个参数),消息将被写入第三个参数中指定的文件:

$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. 请注意,附加到消息的newlineerror_log()不会为您执行此操作。

Note also that permissions must be set to allow the web server to write to the target file. 另请注意,必须设置权限以允许Web服务器写入目标文件。 This is true whether using error_log() or file_put_contents() 无论使用error_log()还是file_put_contents()

PHP reference is here PHP参考在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM