0

我有一个调用的函数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
4

3 回答 3

0

Aside from the missing new-lines (which is most likely down to Notepad's "features"), you could use the error_log function in PHP. Using them you don't have to worry about the overhead of opening and closing file handles as it's all taken care of for you:

/**
 * 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);
    }
}

The above functions are ones that I wrote for custom logging to a file (and, alternatively, a database table)

Hope this helps

于 2014-01-02T17:24:47.980 回答
0

这些\n并且\r只能由浏览器看到。因此,如果您想查看它,请停止使用记事本打开它,并在浏览器中打开该 log.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>";
于 2013-12-11T17:38:23.877 回答
0

尝试:

fwrite($fd, $str . PHP_EOL);

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

于 2013-11-03T17:57:41.837 回答