How to print a debug log?

2019-03-07 11:42发布

I'd like to debug some PHP code, but I guess printing a log to screen or file is fine for me.

How should I print a log in PHP code?

The usual print/printf seems to go to HTML output not the console.

I have Apache server executing the PHP code.

15条回答
相关推荐>>
2楼-- · 2019-03-07 12:09

A lesser known trick is that mod_php maps stderr to the Apache log. And, there is a stream for that, so file_put_contents('php://stderr', print_r($foo, TRUE)) will nicely dump the value of $foo into the Apache error log.

查看更多
The star\"
3楼-- · 2019-03-07 12:09

I use cakephp so I use:

$this->log(YOUR_STRING_GOES_HERE, 'debug');
查看更多
The star\"
4楼-- · 2019-03-07 12:11

Are you debugging on console? There are various options for debugging PHP. The most common function used for quick & dirty debugging is var_dump.

That being said and out of the way, although var_dump is awesome and a lot of people do everything with just that, there are other tools and techniques that can spice it up a bit.

Things to help out if debugging in a webpage, wrap <pre> </pre> tags around your dump statement to give you proper formatting on arrays and objects.

Ie:

<div> some html code ....
      <a href="<?php $tpl->link;?>">some link to test</a>
</div>

      dump $tpl like this:

    <pre><?php var_dump($tpl); ?></pre>

And, last but not least make sure if debugging your error handling is set to display errors. Adding this at the top of your script may be needed if you cannot access server configuration to do so.

error_reporting(E_ALL);
ini_set('display_errors', '1');

Good luck!

查看更多
一夜七次
5楼-- · 2019-03-07 12:12
error_log(print_r($variable, TRUE)); 

might be useful

查看更多
叛逆
6楼-- · 2019-03-07 12:16

You can use error_log to send to your servers error log file (or an optional other file if you'd like)

查看更多
叼着烟拽天下
7楼-- · 2019-03-07 12:17

I have used many of these, but since I usually need to debug when developing, and since I develop on localhost, I have followed the advice of others and now write to the browser's JavaScript debug console (see http://www.codeforest.net/debugging-php-in-browsers-javascript-console).

That means that I can look at the web page which my PHP is generating in my browser & press F12 to quickly show/hide any debug trace.

Since I am constantly looking at the developer tools for debugger, CSS layout, etc, it makes sense to look at my PHP loggon there.

If anyone does decide to us that code, I made one minor change. After

function debug($name, $var = null, $type = LOG) {

I added

$name = 'PHP: ' . $name;

This is because my server side PHP generates HTML conatining JavaScript & I find it useful to distinguish between output from PHP & JS.

(Note: I am currently updating this to allow me to switch on & off different output types: from PHP, from JS, and database access)

查看更多
登录 后发表回答