是否可以写入字符串或日志到控制台?
我的意思是
就像在JSP中一样,如果我们打印system.out.println("some")这样的东西,它将出现在控制台,而不是页面上。
是否可以写入字符串或日志到控制台?
我的意思是
就像在JSP中一样,如果我们打印system.out.println("some")这样的东西,它将出现在控制台,而不是页面上。
当前回答
我发现这很有帮助:
function console($data, $priority, $debug)
{
if ($priority <= $debug)
{
$output = '<script>console.log("' . str_repeat(" ", $priority-1) . (is_array($data) ? implode(",", $data) : $data) . '");</script>';
echo $output;
}
}
像这样使用它:
<?php
$debug = 5; // All lower and equal priority logs will be displayed
console('Important', 1 , $debug);
console('Less Important', 2 , $debug);
console('Even Less Important', 5 , $debug);
console('Again Important', 1 , $debug);
?>
在控制台输出:
重要的 不那么重要 更不重要 同样重要的
您可以通过使用$debug值限制不太重要的日志来关闭它们。
其他回答
默认情况下,所有输出都输出到stdout,即HTTP响应或控制台,这取决于脚本是由Apache运行还是在命令行上手动运行。但是您可以使用error_log进行日志记录,并且可以使用fwrite写入各种I/O流。
这两个都有效:
<?php
$five = 5;
$six = 6;
?>
<script>
console.log(<?php echo $five + $six ?>);
</script>
<?php
$five = 5;
$six = 6;
echo("<script>console.log($five + $six);</script>");
?>
我发现这很有帮助:
function console($data, $priority, $debug)
{
if ($priority <= $debug)
{
$output = '<script>console.log("' . str_repeat(" ", $priority-1) . (is_array($data) ? implode(",", $data) : $data) . '");</script>';
echo $output;
}
}
像这样使用它:
<?php
$debug = 5; // All lower and equal priority logs will be displayed
console('Important', 1 , $debug);
console('Less Important', 2 , $debug);
console('Even Less Important', 5 , $debug);
console('Again Important', 1 , $debug);
?>
在控制台输出:
重要的 不那么重要 更不重要 同样重要的
您可以通过使用$debug值限制不太重要的日志来关闭它们。
我认为最好的解决办法是使用 error_log(内容) 这是输出
2022年编辑:
所以我发现了更好的方法,那就是file_put_contents("php://stdout",内容)
它在没有日志信息的情况下进行写入
对于Chrome浏览器,有一个名为Chrome Logger的扩展,允许记录PHP消息。
Firefox DevTools甚至集成了对Chrome Logger协议的支持。
要启用日志记录,您只需要在项目中保存“ChromePhp.php”文件。那么它可以这样使用:
include 'ChromePhp.php';
ChromePhp::log('Hello console!');
ChromePhp::log($_SERVER);
ChromePhp::warn('something went wrong!');
示例取自GitHub页面。
输出可能是这样的: