laravel 5.6中的自定义日志开发

时间:2018-06-15 01:32:05

标签: mongodb laravel-5.6 monolog

我正在尝试使用新laravel版本5.6的频道制作自定义日志,但我无法实现它。我已经安装了最新版本的monolog。如何使用MongoDBHandler的monolog在MongoDB库中保存记录。

我正在尝试添加自定义渠道,但它无效。

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();
    }
}

1 个答案:

答案 0 :(得分:0)

使用注释中指定的“用法示例”时,只需调用然后:

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

它将被添加到您的Mongo中!