使用php写入日志文件

使用php写入日志文件

本文介绍了使用php写入日志文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我对php非常非常非常非常不好,所以对不起这个问题我有一个要在其中记录一些调试数据的应用程序通过我的项目,我向我的网站发出了一个Web请求,将信息存储在$ msg然后我想将数据写入站点上的我的logfile.log中.我首先使用fopen fwrite fclose,但听说file_put_contents会更好特别是因为我极有可能会有几个用户试图一次写入文件.这是代码:

First of I am very very very very bad with php so sorry for this questionI have an application in which i would like to log some debug dataand 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 betterespecially 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);

但是您可能会猜到代码对我没有任何帮助我让它与fopen fwrite fclose一起工作但我想将每个用户添加到新行.

But as you might guess the code does nothing for mei got it working with fopen fwrite fclosebut 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.

致谢.

杰伊这就是我尝试应用它的方式(在第一行中打开php)由于复制/粘贴错误,已从代码中删除了标签".

@JayThis is how i tried applying it (opening php on the first line) 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);

推荐答案

为什么不只使用error_log()?在message_type设置为3(第二个参数)的情况下,消息将被写入第三个参数中指定的文件:

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

请注意,邮件中附加的newlineerror_log()不能为您完成的操作.

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

还请注意,必须设置权限以允许Web服务器写入目标文件.无论使用error_log()还是file_put_contents()

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参考位于此处

这篇关于使用php写入日志文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 04:08