【发布时间】:2018-11-17 05:19:14
【问题描述】:
我有一个 WordPress 问题,想简单地将日志消息写入文本文件。我知道error_log 存在,但希望为不同的消息提供一个更加隔离的日志文件。
我正在使用wp_filesystem->put_contents,它确实写入文件并成功,但它只输出最后一次调用的数据。
我有以下方法:
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.");
}
}
我称之为:
log_message("\nTest 1");
log_message("\nTest 2");
log_message("\nTest 3");
输出总是只有Test 3,而其他调用被忽略,它们的输出出现在 debug.log 以及所有成功消息中。
为什么会这样?
查看WPCodex的源代码,它在幕后使用fwrite。该文件在此代码中关闭,我不能使用任何“刷新”技术。
有没有办法解决这个问题?
【问题讨论】:
-
根据this post , wp_filesystem 非常有限。您可能希望使用 PHP 的 fwrite 和文件句柄的 append 命令附加到文件。
-
哦,有道理。我假设函数“file_put_contents”只是用于附加到文件......它将清除文件,并将内容放在那里。该函数用于计算/获取数据流,然后保存,不用于文件保存。
标签: php wordpress file fwrite file-put-contents