是否可以写入字符串或日志到控制台?
我的意思是
就像在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值限制不太重要的日志来关闭它们。
其他回答
这是我的解决方案,这个的好处是你可以传递尽可能多的参数。
function console_log()
{
$js_code = 'console.log(' . json_encode(func_get_args(), JSON_HEX_TAG) .
');';
$js_code = '<script>' . $js_code . '</script>';
echo $js_code;
}
这样称呼它
console_log('DEBUG>>', 'Param 1', 'Param 2');
console_log('Console DEBUG:', $someRealVar1, $someVar, $someArray, $someObj);
现在你应该能够在你的控制台看到输出,愉快的编码:)
我认为它可以被用来
function jsLogs($data, $isExit) {
$html = "";
$coll;
if (is_array($data) || is_object($data)) {
$coll = json_encode($data);
} else {
$coll = $data;
}
$html = "<script id='jsLogs'>console.log('PHP: ${coll}');</script>";
echo($html);
if ($isExit) exit();
}
# For String
jsLogs("Testing string"); #PHP: Testing string
# For Array
jsLogs(array("test1", "test2")); # PHP: ["test1","test2"]
# For Object
jsLogs(array("test1"=>array("subtest1", "subtest2"))); #PHP: {"test1":["subtest1","subtest2"]}
对于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页面。
输出可能是这样的:
我已经放弃了上述所有工具,转而使用调试器和记录器。我怎么称赞都不为过!
只需点击右上角的一个标签,或者点击“点击这里”来展开/隐藏。
注意不同的“类别”。您可以单击任意数组展开/折叠它。
从网页
主要特点: 显示全局变量($ globals, $_POST, $_GET, $_COOKIE等) 显示PHP版本和加载的扩展 替换PHP内置的错误处理程序 记录SQL查询 监视代码和SQL查询的执行时间 检查变量的变化 函数调用跟踪 代码覆盖分析,检查执行了哪些脚本行 转储所有类型的变量 文件检查器与代码高亮显示查看源代码 发送消息到JavaScript控制台(仅限Chrome),用于Ajax脚本
或者使用从PHP调试到控制台的技巧。
首先需要一个PHP辅助函数
function debug_to_console($data) {
$output = $data;
if (is_array($output))
$output = implode(',', $output);
echo "<script>console.log('Debug Objects: " . $output . "' );</script>";
}
然后你可以这样使用它:
debug_to_console("Test");
这将创建如下输出:
Debug Objects: Test