How to print a debug log?

前端 未结 15 1689
北海茫月
北海茫月 2020-12-12 10:07

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 u

相关标签:
15条回答
  • 2020-12-12 10:22
    error_log(print_r($variable, TRUE)); 
    

    might be useful

    0 讨论(0)
  • 2020-12-12 10:22

    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!

    0 讨论(0)
  • 2020-12-12 10:25

    If you are on Linux:

    file_put_contents('your_log_file', 'your_content');
    

    or

    error_log ('your_content', 3, 'your_log_file');
    

    and then in console

    tail -f your_log_file
    

    This will show continuously the last line put in the file.

    0 讨论(0)
  • 2020-12-12 10:26

    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.

    0 讨论(0)
  • 2020-12-12 10:27

    You can use

    <?php
    {
        AddLog("anypage.php","reason",ERR_ERROR);
    }
    ?>
    

    or if you want to print that statement in an log you can use

    AddLog("anypage.php","string: ".$string,ERR_DEBUG_LOW);
    
    0 讨论(0)
  • 2020-12-12 10:28

    You need to change your frame of mind. You are writing PHP, not whatever else it is that you are used to write. Debugging in PHP is not done in a console environment.

    In PHP, you have 3 categories of debugging solutions:

    1. Output to a webpage (see dBug library for a nicer view of things).
    2. Write to a log file
    3. In session debugging with xDebug

    Learn to use those instead of trying to make PHP behave like whatever other language you are used to.

    0 讨论(0)
提交回复
热议问题