Cara menggunakan php log to stdout

As a programming language, PHP is a developer favorite. An essential PHP programming best practice is how to log to console in PHP. Today, we’ll lay out how you do that.

PHP is one of the most popular server-side scripting languages for building web applications because it’s easy to use. But no matter what you build, logging errors is key to ensuring a short code-test-learn feedback cycle.

PHP is uniquely designed to be good for building web applications. However, PHP was developed before modern browsers, so it lacks an easy way to log errors to the browser console. Using JavaScript, logging to console is as simple as this:

console.log("Message here");

In this article, we’ll show you how to log to console within PHP, and why logging in PHP can be a good thing. Furthermore, we’ll tackle how it’s just as easy as logging to console using JavaScript. You can have the best of both worlds: enjoy the power of PHP and log to console within PHP.

Tip: Find application errors and performance problems instantly with Stackify Retrace

Troubleshooting and optimizing your code is easy with integrated errors, logs and code level performance insights.

Cara menggunakan php log to stdout
Cara menggunakan php log to stdout

What is the browser console?

First of all, we need to understand what the browser console is.

The browser console is a way for the browser to log information associated with a specific web page. The information logged includes network requests, JavaScript, CSS, security errors and warnings, as well as errors, warnings and informational messages explicitly logged by JavaScript code running in the page context.

For demonstrations, we’ll use the desktop version of Google Chrome, but you can also perform similar steps in desktop versions of Firefox, Safari and Internet Explorer. 

To start, open Google Chrome and go to any web page, right-click and choose Inspect to bring up Chrome’s Developer Tools.

Cara menggunakan php log to stdout
Fig. 1: How to trigger Developer Tools in Chrome
Cara menggunakan php log to stdout
Fig. 2: Developer Tools in Chrome after clicking Inspect

The browser console will be one of the tabs in the Developer Tools. And you can test it out by writing the same JavaScript console.log command.

Cara menggunakan php log to stdout
Fig. 3: How to log to console using JavaScript

Why logging to console is a good thing

There are two primary reasons you want to log to the browser console.

The first is simplicity. As a PHP developer, you want to work with two applications at most, your favorite code editor or IDE and your browser. Since you’ll normally toggle between the two as you write code in the editor and test it on the browser, the most natural place to display log statements is inside the browser.

The second reason is to keep the logging as least intrusive as possible. Now, you can log using PHP’s native functions such as var_dump. However, when you use var_dump, you need to decide where you want to write the output to.

You could write output to the browser web page, but this will likely distort the display. Another possible destination for output may be a file in your server. For this option, we recommend an open-source logging library like Monolog instead of var_dump. If you prefer to output view variables without distorting the web page, logging to the browser console is better

Another thing to note is that PHP developers are increasingly gravitating toward frameworks such as Laravel and Symfony. These frameworks usually use popular PHP logging libraries such as Monolog. PHP logging libraries work best when outputting a detailed breakdown of the error stack trace for server-side errors such as database connection into files.

We have a tutorial covering monolog logging for such situations, where you can learn how to send the logs to Retrace.Sometimes you just want something lightweight to display inside the browser for front-end debugging. For such situations, logging to console would be ideal. Furthermore, you can combine this technique with the standard PHP logging methods for a more complete development setup.

How to log directly to console using PHP code

There are two main ways you can log directly to the console using (mostly) PHP code – the json_encode function and PHP libraries.

Using json_encode function

Let’s say you want to console log a PHP variable $view_variable in your view layer. Recall that console.log is a JavaScript function. The key principle is that we can make use of JSON to pass the PHP variable to the JavaScript function. You create a PHP function like this:

<?php
function console_log($output, $with_script_tags = true) {
$js_code = 'console.log(' . json_encode($output, JSON_HEX_TAG) .
');';
if ($with_script_tags) {
$js_code = '<script>' . $js_code . '</script>';
}
echo $js_code;
}

You can call this function at the exact place you want to run the console_log that we just created above. An example of its usage would look like this:

<?php $view_variable = 'a string here'; ?>
<!-- some HTML content here -->
<div>
<!-- even more HTML content here -->
</div>
<?= console_log($view_variable); ?>

And the generated HTML markup would be this:

<!-- some HTML content here -->
<div>
<!-- even more HTML content here -->
</div>
<script>console_log('a string');</script>

Remember to include the definition of the customized console_log PHP function to call it as many times as needed. If you prefer to transform the JSON string into other forms, you can reference the list of constants that json_encode uses. The useful constants that you’re more likely to use are JSON_FORCE_OBJECT and JSON_PRETTY_PRINT.

Logging in the middle of your JavaScript code

Sometimes you don’t want to install PHP libraries unless you’re absolutely sure you have to. You might prefer to console log the PHP variables in the middle of your JavaScript code found in your PHP view files. You can use the same technique this way:

<script>
// other JavaScript code before ...

var js_variable_as_placeholder = <?= json_encode($view_variable,
JSON_HEX_TAG); ?>;
console.log(js_variable_as_placeholder);

// other JavaScript code and after ...
</script>

Using PHP libraries to console log

If you prefer to use open-source libraries that have solved this issue, there are two options we recommend – PHPDebugConsole (installation instructions and code here) and PHPConsole (installation instructions and code here).

A comparison between PHPDebugConsole and PHPConsole

A quick comparison between the two libraries yields the following analysis.

A quick comparison between the two libraries yields the following analysis.

PHPConsole appears to be more established with 1.3k stars on its GitHub repo. At the time of writing, PHPConsole’s last update was September 2019 and has fewer commits (126). A Chrome Extension is recommended for PHPConsole that seems to be authored by the same people behind PHPConsole. Finally, the PHPConsole demo website was no longer working, last I checked.

Meanwhile, PHPDebugConsole has 51 stars on its GitHub repo, a more frequent update history and 797 commits with the last three commits all happening in November 2021. Documentation recommends several browser extensions that PHPDebugConsole can work with and includes demo examples.

Taking all the above into consideration, we recommend choosing PHPDebugConsole if you want to use a PHP library to console log. Overall, we suggest the following decision matrix:

  • If you want to keep it simple, use PHP json_encode function
  • If you want to use more extensive features such as console.info, use PHPDebugConsole with PHPConsole as your backup
An example from PHPDebugConsole

Here’s an example taken from PHPDebugConsole’s excellent demo website:

<?php
require '/path/to/Debug.php';

$debug = new \bdk\Debug(array(
    'collect' => true, // turn logging on
    'output' => true, // if left false (default), the output() method will return an empty string
));

/**
 * Example Class
 * Demonstrates PHP reflection and PHPDocBlock
 */
class Example
{
    private $offLimits = 'I\'m a private property';

    public function __toString() {
        return 'It\'s Magic';
    }

    /**
     * Foo is a private method that does stuff
     *
     * @param string $bar the string you want to foo
     *
     * @return string the fooed string
     */
    private function foo($bar) {
    }
}

$debug->info('PHPDebugConsole is great!');
$debug->warn('No browser plugin necessary');
$debug->log('features/options', array(
    'PHP port of the javascript web console API',
    'outputOpts' => array(
        'HTML (as seen here)',
        'ChromeLogger',
        'FirePHP',
        'Plain-text / file',
        '<script>',
        '"plugin" (send log realtime via websockets, etc)',
    ),
    'password protected',
    'errors (even fatal) are captured / logged / displayed',
    'send error notices via email (throttled as to not to send out a flood of emails)',
    'send debug log via email',
));

When this runs, it looks like the web page content below. If you do want it to be output to the browser’s console, you need to install extensions.

Cara menggunakan php log to stdout
Fig. 4: Example output for PHPDebugConsole

Conclusion

We live in a highly interesting and exciting time for web programming. The console log used to be something that could only work with JavaScript. In this article, you’ve learned what the console log is and why it’s useful for web development. You’ve also learned how to write your own PHP code to log PHP variables in your browser console. If you need more extensive features such as console.info, there are PHP libraries like PHPDebugConsole that can help you with that.

To make it a complete, end-to-end logging infrastructure for your PHP web application, we highly recommend using monolog. It’s useful to cover more back-end-related debugging purposes. Tie it all together by using an application performance monitoring tool such as Retrace to track your application performance, search through your logs easily and identify top web requests and their impact on your stack. We guarantee you’ll have a solid logging setup that’s better than the majority of PHP web applications out there.

You may also want to try Stackify’s free code profiler, Prefix, to write better code on your workstation. Prefix works with .NET, Java, PHP, Node.js, Ruby and Python.