PHP 日志记录 - 不会添加新行


PHP Logging - won't add new line

我有一个名为logToFile的函数,当我调用它时,它会记录到文件中,但不添加新行。

这是我的代码:

function logToFile($msg) {
    $filename = "log.txt";
    $fd = fopen($filename, "a");
    $str = "[" . date("Y/m/d h:i:s", mktime()) . "] " . $msg;
    fwrite($fd, $str . "'n");
    fclose($fd);
}

我试过:

$msg . "'n"
$msg . "'r'n"

它们都输出以下内容:

[2013/11/03 06:32:06]Test[2013/11/03 06:34:58]Test2[2013/11/03 06:37:10]Test3

这些'n'r只能由浏览器看到。因此,如果您想查看它,请停止使用记事本对其进行操作,并在浏览器中打开该日志.txt文件。为此,请尝试以下代码:

function logToFile($msg) {
    $filename = "log.txt";
    $fd = fopen($filename, "a");
    $str = "[" . date("Y/m/d h:i:s") . "] " . $msg . "'n";
    fwrite($fd, $str . "'n");
    fclose($fd);
}

但是,另一种方法是使用 html 文件而不是 txt 文件。你可以
在那里使用。所以:

  function logToFile($msg) {
        $filename = "log.html";
        $fd = fopen($filename, "a");
        $str = "[" . date("Y/m/d h:i:s") . "] " . $msg . "<br>";
        fwrite($fd, $str . "'n");
        fclose($fd);
    }

您还可以设置其样式:

$str = "<span style='background-color: red;'>[" . date("Y/m/d h:i:s") . "] " . $msg . "</span><br>";

尝试:

fwrite($fd, $str . PHP_EOL);

这将为运行 PHP 的平台编写正确类型的行尾字符串。在Unix上它会写'n,在Windows上它应该写'r'n

除了缺少换行符(这很可能归结为记事本的"功能"),您还可以在 PHP 中使用 error_log 函数。使用它们,您不必担心打开和关闭文件句柄的开销,因为它都为您处理:

/**
 * logMessage
 * @param string $message
 * @param string $filename
 * @param resource $logHandle
 */
function logMessage($message=null, $filename=null, $logHandle=null)
{
    if (!is_null($filename))
    {
        $logMsg=date('Y/m/d H:i:s').": {$message}'n";
        error_log($logMsg, 3, $filename);
    }
    if (is_object($logHandle))
    {
        try
        {
            $errorPS=$logHandle->prepare("insert into ".LOG_TABLE." (insertDateTime,logText) values (now(),:message)");
            $errorPS->bindParam(':message', $message, PDO::PARAM_STR);
            $errorPS->execute();
        } catch (PDOException $e)
        {
            logError($e->getMessage(), ERROR_LOG);
        }
    }
}
/**
 * logError
 * @param string $message
 * @param string $filename
 * @param resource $logHandle
 */
function logError($message=null, $filename=null, $logHandle=null)
{
    if (!is_null($message))
    {
        logMessage("***ERROR*** {$message}", $filename, $logHandle);
    }
}

上述函数是我为自定义日志记录到文件(或者数据库表)而编写的函数

希望这有帮助