0

I'm trying to make a custom Log using the channels of the new laravel version 5.6, but I'm not able to implement it. I have installed the recent version of monolog. How can I save records in my MongoDB bank using MongoDBHandler's monolog.

I'm trying to add in custom channel but it is not working.

namespace Monolog\Handler;

use Monolog\Logger;
use Monolog\Formatter\NormalizerFormatter;

/**
 * Logs to a MongoDB database.
 *
 * usage example:
 *
 *   $log = new Logger('application');
 *   $mongodb = new MongoDBHandler(new \Mongo("mongodb://localhost:27017"), "logs", "prod");
 *   $log->pushHandler($mongodb);
 *
 * @author Thomas Tourlourat <thomas@tourlourat.com>
 */
class MongoDBHandler extends AbstractProcessingHandler
{
    protected $mongoCollection;

    public function __construct($mongo, $database, $collection, $level = Logger::DEBUG, $bubble = true)
    {
        if (!($mongo instanceof \MongoClient || $mongo instanceof \Mongo || $mongo instanceof \MongoDB\Client)) {
            throw new \InvalidArgumentException('MongoClient, Mongo or MongoDB\Client instance required');
        }

        $this->mongoCollection = $mongo->selectCollection($database, $collection);

        parent::__construct($level, $bubble);
    }

    protected function write(array $record)
    {
        if ($this->mongoCollection instanceof \MongoDB\Collection) {
            $this->mongoCollection->insertOne($record["formatted"]);
        } else {
            $this->mongoCollection->save($record["formatted"]);
        }
    }

    protected function getDefaultFormatter()
    {
        return new NormalizerFormatter();
    }
}
Sebastian D'Agostino
  • 1,575
  • 2
  • 27
  • 44

1 Answers1

0

When you use the "usage example" specified in the comment, you juste need to call then :

$log->addInfo($message, $context); // you can see this method in the Monolog\Logger class

And it will be added in your Mongo !

Marion R
  • 1
  • 1