0
votes

I want to add monolog in mongodb with default handler(MongoDBHandler) in Symfony 4.

my monolog.yaml file in dev folder

monolog:
    handlers:
        mongo:
             type: mongo
             mongo:
                id: monolog.logger.mongo
                host: '%env(MONGODB_URL)%'
                database: '%env(MONGODB_DB)%'
                collection: logs

my services.yaml

services:
    monolog.logger.mongo:
        class: Monolog\Handler\MongoDBHandler
        arguments: ['@doctrine_mongodb']

my doctrine_mongodb.yaml

doctrine_mongodb:
    auto_generate_proxy_classes: '%kernel.debug%'
    auto_generate_hydrator_classes: '%kernel.debug%'
    connections:
        default:
            server: '%env(MONGODB_URL)%'
            options:
                    db: '%env(MONGODB_DB)%'
        log:
                server: '%env(MONGODB_URL)%'
                options:
                    db: '%env(MONGODB_DB)%'
                    connect: true
    default_database: '%env(MONGODB_DB)%'
    document_managers:
        log:
            auto_mapping: false
            logging: false

But doesn't work.

one of the errors:

Cannot autowire service "monolog.logger.mongo": argument "$database" of method "Monolog\Handler\MongoDBHandler::__construct()" is type-hinted "string", you should configure its value explicitly.

While i use database option in monolog config.

Is there any document?

2
define "doesn't work" ? any error message? Did you cleared Symfony cache?Cid
Tanks, Yes i cleared Symfony cache.ShahRokh
Do you have MONGO_DB set in your .env file, or as an environment variable?yivi
Yes, i set MONGO_DB in my .env file.ShahRokh

2 Answers

0
votes

Another way to enable mongodb for monolog is:

monolog:
    handlers:
        mongo:
             type: mongo
             mongo:
                host: '%env(MONGODB_URL)%'
                user: myuser
                pass: mypass
                database: '%env(MONGODB_DB)%'
                collection: logs

, So it mean you need to remove id field and add user and pass instead.

0
votes

If you use doctrine mongodb already, it's possible to re-use it's connection, avoiding more ENV vars to separate the DSN:

monolog:
    handlers:
        mongo:
            type: mongo
            mongo:
                id: "doctrine_mongodb.odm.default_connection"
                database: "%env(MONGODB_DB)%"
                collection: MyLogDocument # Keeping this the same, allows you to simply use a doctrine repository to access the documents in your app if needed
            level: debug