3

I use symfony 2.5, and I have next service for monolog.

<?php

namespace Megogo\CoreBundle;

use Symfony\Component\HttpFoundation\Session\Session;

class SessionRequestProcessor
{
    /**
     * @var \Symfony\Component\HttpFoundation\Session\Session
     */
    protected $session;

    /**
     * @var
     */
    private $token;

    public function __construct( Session $session)
    {
        $this->session = $session;
    }

    public function processRecord(array $record)
    {

        if (null === $this->token) {
            try {
                $this->token = $this->session->getId();
            } catch (\RuntimeException $e) {
                $this->token = '????????';
            }

        }
        $record['extra']['token'] = $this->token;

        return $record;
    }
} 

service.yml

services:
    monolog.formatter.session_request:
        class: Monolog\Formatter\LineFormatter
        arguments:
            - "[%%datetime%%] [%%extra.token%%] %%channel%%.%%level_name%%: %%message%%\n"

    monolog.processor.session_request:
        class: Megogo\CoreBundle\SessionRequestProcessor
        arguments:  ["@session"]
        tags:
            - { name: monolog.processor, method: processRecord }

I get example from official documentation. Adding a Session/Request Token

I have problem, that $this->session->getId() return empty string. If I add $session->start(); all works. I can get session id. But this is weird, because in other my services all works without this workaround. And when I make app/console cache:clear I have error Failed to start the session: already started by PHP.

denys281
  • 2,004
  • 2
  • 19
  • 38

2 Answers2

2

I've had a similar issue.

I've solved it by adding in a controller

$this->get('session')->start();

In your case you could simply add following line before you try to get session ID

$this->session->start();

Don't worry about calling "start()" when session is already started - it will check and simply skip (re)starting it.

Current (2.6) version of Symfony does not have config property which would force session auto_start

paq85
  • 864
  • 10
  • 13
0

Official docs says:

Symfony sessions are incompatible with php.ini directive session.auto_start = 1 This directive should be turned off in php.ini, in the webserver directives or in .htaccess.

Maybe try this?

Jovan Perovic
  • 19,846
  • 5
  • 44
  • 85