Tuesday, February 23, 2016

Save logs to Database and access them from web UI with LexikMonologBrowserBundle

Monolog: Monolog is a logging library for PHP used by Symfony.

Cookbook:  http://symfony.com/doc/current/cookbook/logging/monolog.html

LexikMonologBrowserBundle: 
https://github.com/lexik/LexikMonologBrowserBundle




This Symfony2 bundle provides a Doctrine DBAL handler for Monolog and a web UI to display log entries.

I am using an existing Doctrine configuration in config.yml:

#config.yml

    default:
                    driver:   "%database_driver%"
                    host:     "%database_host%"
                    port:     "%database_port%"
                    dbname:   "%database_name%"
                    user:     "%database_user_prod%"
                    password: "%database_password_prod%"
                    charset:  UTF8
                    logging:   false
                    profiling: false


If you do not have the last two lines, you should add them to avoid circular reference error.
And also  add lexik_monolog_browser config to use the existing Doctrine connection:

    lexik_monolog_browser:
        doctrine:
            connection_name:  default
            table_name: monolog_entries


Generatate the table in the database:

    >php app/console lexik:monolog-browser:schema-create
   

Add the below to config_dev.yml and/or config_prod.yml in order for Monolog to use our handler to save into database.

    # app/config/config_prod.yml # or any env
    monolog:
        handlers:
            main:
                type:         fingers_crossed # or buffer
                level:        error
                handler:      lexik_monolog_browser
            app:
                type:         buffer
                action_level: info
                channels:     app
                handler:      lexik_monolog_browser
            deprecation:
                type:         buffer
                action_level: warning
                channels:     deprecation
                handler:      lexik_monolog_browser
            lexik_monolog_browser:
                type:         service
                id:           lexik_monolog_browser.handler.doctrine_dbal


Import routes to app/config/routing.yml:

    # app/config/routing.yml
    lexik_monolog_browser:
        resource: "@LexikMonologBrowserBundle/Resources/config/routing.xml"
        prefix:   /admin/monolog




More:

It would be good to save in logs also the current user. For this you can add in your controller:

       //log current user in Monolog
        $logger = $this->get('logger');
        $logger->info('Current user is : ' . $this->getUser()->getUsername());

No comments:

Post a Comment