The Symfony framework provides an incredible amount of debug information in its application log file. In its development environment, Symfony will write a whole host of information into the app/logs/dev.log file on every request. Using the default logging setup, a line from this log looks something like this:

[2015-03-15 20:41:29] request.INFO: Matched route "homepage" (parameters: "_controller": "AppBundle\Controller\DefaultController::indexAction", "_route": "homepage") [] {}

We have the time the line was generated, the log level, the log message itself, and space for some ‘extra’ info. What we don’t have is the IP address of the client making the request, and this is something that is really useful to include in your application logs.

At first, it might seem that Monolog provides a built-in solution for this through its WebProcessor which, ‘adds the current request URI, request method and client IP to a log record’. Sounds like exactly what we need!

Setting up the WebProcessor

Using the built-in Monolog processors with Symfony is relatively straightforward. We just need to create a service for the processor, and tag it with the monolog.processor tag.

To do this, add something like the below to the services section of your app/config/services.yml file:

services:
  monolog.processor.web:
      class: Monolog\Processor\WebProcessor
      tags:
          - { name: monolog.processor }

If we now repeat our request from earlier, we’ll see a line like this in our dev.log:

[2015-03-15 20:58:04] request.INFO: Matched route "homepage" (parameters: "_controller": "AppBundle\Controller\DefaultController::indexAction", "_route": "homepage") [] {"url":"/app/example","ip":"10.0.2.2","http_method":"GET","server":"localhost","referrer":null}

We now have a set of extra info about the request, including the IP address! Yay! But it’s all just bunged onto the end of the line in the extra array, and we don’t really want the rest of this information! Boo!

Lets integrate the IP a little better into the log line.

Adding a log formatter

To include items from the log record’s extra array in the main section of our log lines, we need to configure a Formatter and then apply it to our log handler.

First, add this formatter configuration - again in app/config/services.yaml - it can go directly under the service config we already added for the processor:

monolog.formatter.standard:
    class: Monolog\Formatter\LineFormatter
    arguments:
        format: "%%datetime%% | %%extra.ip%% | %%channel%%.%%level_name%%: %%message%% %%context%%\n"

The format line here defines what we want our log lines to include; we’ve added the extra.ip field (and we could just as well have added any of the other keys from the extra list: url, ip, http_method, server or referrer) and also added a | separator between fields, for easier log parsing with awk or similar.

Now, we need to tell our log handler to use the new formatter. To do this, find the monolog section in app/config/config_dev.yml (and config_prod.yml, if you like) and add the last line shown below.

monolog:
    handlers:
        main:
            type:   stream
            path:   "%kernel.logs_dir%/%kernel.environment%.log"
            level:  debug
            formatter: monolog.formatter.standard

With these two changes in place, our log lines now look like this:

2015-03-15 21:08:38 | 10.0.2.2 | request.INFO: Matched route "homepage" (parameters: "_controller": "AppBundle\Controller\DefaultController::indexAction", "_route": "homepage") []

This is starting to look pretty good! We have the IP address included as part of the log line proper, and we’ve dumped the extraneous information we had earlier.

There’s just one problem: our Symfony app is behind a reverse proxy (think CloudFlare or similar) and the proxy’s IP address is 10.0.2.2. We’re not logging the client’s IP, we’re logging our proxy’s IP! Needless to say, this is less than ideal.

Getting the real client IP address

Thankfully our reverse proxy is well-behaved, and adds the IP address of the client who really made the request to our app to the X-Forwarded-For HTTP header. We’re just going to need to write a log record processor of our own to extract this information from the request and add it to our log records.

This should probably look something like the class shown here (obviously the namespace and such will need adjusting to suit your project):

<?php
// src/AppBundle/Log/ClientIpProcessor
namespace AppBundle\Log;

use Symfony\Component\HttpFoundation\RequestStack;

class ClientIpProcessor
{
    private $requestStack;
    private $cachedClientIp = null;
    
    public function __construct(RequestStack $requestStack)
    {
        $this->requestStack = $requestStack;
    }
    
    public function __invoke(array $record)
    {
        // request_ip will hold our proxy server's IP
        $record['extra']['request_ip'] = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : 'unavailable';
        // client_ip will hold the request's actual origin address
        $record['extra']['client_ip']  = $this->cachedClientIp          ? $this->cachedClientIp   : 'unavailable';
        
        // Return if we already know client's IP
        if ($record['extra']['client_ip'] !== 'unavailable') {
            return $record;
        }
        
        // Ensure we have a request (maybe we're in a console command)
        if (! $request = $this->requestStack->getCurrentRequest()) {
            return $record;
        }
        
        // If we do, get the client's IP, and cache it for later.
        $this->cachedClientIp = $request->getClientIp();
        $record['extra']['client_ip'] = $this->cachedClientIp;
        
        return $record;
    }
}

And with the class in place, we should create a service for it, so Symfony knows to use it as a Monolog processor. The config below should replace our earlier monolog.processor.web service in app/config/services.yml:

monolog.processor.client_ip:
    class: AppBundle\Log\ClientIpProcessor
    arguments: [ @request_stack ]
    tags:
        - { name: monolog.processor }

And since our processor uses new extra array fields to hold the proxy server and client IP addresses, we need to update our log formatter config to look like this:

monolog.formatter.standard:
    class: Monolog\Formatter\LineFormatter
    arguments:
        format: "%%datetime%% | %%extra.request_ip%% | %%extra.client_ip%% | %%channel%%.%%level_name%%: %%message%% %%context%%\n"

If we haven’t already, we also need to tell Symfony to trust our reverse proxy. This is done in the framework section of app/config/config.yml:

framework:
    # Set your proxy's IP address(es) here
    trusted_proxies: 10.0.2.2

Phew! With all of the above in place, lets make another request to our app:

2015-03-15 21:33:57 | 10.0.2.2 | 5.10.144.10 | request.INFO: Matched route "homepage" (parameters: "_controller": "AppBundle\Controller\DefaultController::indexAction", "_route": "homepage") []

We now have everything we want - we’ve got the proxy’s IP address (10.0.2.2) and the IP address of the client who sent the original request (5.10.144.10).

This post has really only scratched the surface of what is possible with the combination of Symfony and Monolog, but I hope it provides some inspiration for the kinds of possibilities they offer.