WordPress: wp_filesystem->put_contents only writes last call
我遇到了WordPress问题,只想简单地将日志消息写入文本文件。我知道
我正在使用
我有以下方法:
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"); |
输出始终是
为什么会这样?
查看WPCodex的源代码,它在幕后使用
有没有办法解决这个问题?
我发现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文档描述了此方法及其模式。