关于php:WordPress:wp_filesystem-> put_contents仅写入最后一次调用

WordPress: wp_filesystem->put_contents only writes last call

我遇到了WordPress问题,只想简单地将日志消息写入文本文件。我知道error_log存在,但希望对于不同的消息有一个更隔离的日志文件。

我正在使用wp_filesystem->put_contents,它确实写入文件并成功,但是它仅输出上次呼叫的数据。

我有以下方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public static function log_message($msg) {
  error_log($msg);
  require_once(ABSPATH . 'wp-admin/includes/file.php');
  global $wp_filesystem;
  if ( ! is_a( $wp_filesystem, 'WP_Filesystem_Base') ){
      $creds = request_filesystem_credentials( site_url() );
      wp_filesystem($creds);
  }

  $bt = debug_backtrace();
  $caller = array_shift($bt);
  $logStr = date("Y-m-d hh:ii A",time())." -".$caller['file'].":".$caller['line']." -".$msg;
  $filePathStr = SRC_DIR.DIRECTORY_SEPARATOR.$logFileName;

  $success = $wp_filesystem->put_contents(
      $filePathStr,
      $logStr,
      FS_CHMOD_FILE // predefined mode settings for WP files
  );

  if(!$success) {
      error_log("Writing to file "".$filePathStr."" failed.");
  } else {
      error_log("Writing to file "".$filePathStr."" succeeded.");
  }
}

我用以下方式称呼它:

1
2
3
4
5
6
log_message("\
Test 1"
);
log_message("\
Test 2"
);
log_message("\
Test 3"
);

输出始终是Test 3,而其他调用仍被忽略,它们的输出将出现在debug.log以及所有成功消息中。

为什么会这样?

查看WPCodex的源代码,它在幕后使用fwrite。该文件在此代码中关闭,并且我不能使用任何"刷新"技术。

有没有办法解决这个问题?


我发现WP_Filesystem的源使用file_put_contents(顾名思义),并且我认为这是用于追加文件数据。

这是不正确的。

此功能是获取数据,然后将其写入文件,以擦除先前的数据。
主要用于创建资源,下载文件等。

如果要附加到文件,则需要使用'fwrite'。

这篇文章对此进行了描述。

这是附加到文件的示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
$filepath = '\\path\\to\\file\';
$filename = '
out.log';
$fullpath = $filepath.$filename;

if(file_exists($fullpath)) {
  $file = fopen($filepath.$filename,"a");//a for append -- could use a+ to create the file if it doesn'
t exist
  $data ="test message";
  fwrite($file,"\
"
. $data);
  fclose($file);
} else {
  error_log("The file \'".$fullpath."\' does not exist.");
}

fopen文档描述了此方法及其模式。