Symfony

How to manage logs with Symfony and Graylog

Step 1. Docker-compose configuration.

Graylog needs Elasticsearch and MongoDB to store and index data.

Let’s create our docker-compose file, which you can find in our blog post example.

Step 2. Install Monolog on your project.

Monolog bundle integrates Monolog into Symfony, with many handlers like Slack, Elasticsearch, and Graylog.

composer require symfony/monolog-bundle

Install the gelf implementation in PHP

composer require graylog2/gelf-php

As you can see, there are two handlers:

  • “streams” write all logs into a file.
  • “console” allows you to see logs on your terminal when you execute a task with the option -vvv.

Now add the new handler to send all logs in Graylog:

monolog:
  handlers:
    graylog:
      type: service
      id: monolog.gelf_handler
      level: !php/const Monolog\Logger::DEBUG

It would be best if you defined the Symfony service gelf-handler correctly:

services:
    monolog.gelf_handler:
        class: Monolog\Handler\GelfHandler
        arguments:
            - '@gelf.publisher'
            - 'warning'

    gelf.publisher:
        class: Gelf\Publisher
        arguments: ['@gelf.ignore_error_transport']

    gelf.ignore_error_transport:
        class: Gelf\Transport\IgnoreErrorTransportWrapper
        arguments: ['@gelf.transport']

    gelf.transport:
        class: Gelf\Transport\TcpTransport # or Tcp, Amp, Http,...
        arguments:
            - '%env(GRAYLOG_HOST)'
            - '%env(GRAYLOG_PORT)'

Then add these two new env variables in your .env file.

GRAYLOG_HOST=localhost
GRAYLOG_PORT=12201

Step 3. Configure a new input in Graylog.

Go to http://127.0.0.1:9001, then connect you with the credentials: admin/admin.

Then go to System / Inputs, select “GELF TCP,” then click launch input.

Step 4. Test

Go to your website, then go back to your Graylog dashboard. Now you can see all the logs.