Skip to content

Instantly share code, notes, and snippets.

@ipalaus
Last active February 14, 2023 13:10
Show Gist options
  • Save ipalaus/5568323 to your computer and use it in GitHub Desktop.
Save ipalaus/5568323 to your computer and use it in GitHub Desktop.
Eloquent handler for Monolog.
<?php namespace BigBrother\Support\Facades;
use Illuminate\Support\Facades\Facade;
class BigLog extends Facade {
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor() { return 'biglog'; }
}
<?php namespace BigBrother\Log\Handler;
use Monolog\Logger;
use Monolog\Formatter\JsonFormatter;
use Monolog\Handler\AbstractProcessingHandler;
class EloquentHandler extends AbstractProcessingHandler {
protected $model;
public function __construct($class, $level = Logger::DEBUG, $bubble = true)
{
$this->model = $class;
parent::__construct($level, $bubble);
}
/**
* {@inheritDoc}
*/
protected function write(array $record)
{
$model = $this->createModel();
$model->level = $record['level'];
$model->level_name = $record['level_name'];
$model->message = $record['message'];
$model->save();
}
/**
* Create a new instance of the model.
*
* @return \Illuminate\Database\Eloquent\Model
*/
protected function createModel()
{
$class = '\\'.ltrim($this->model, '\\');
return new $class;
}
}
<?php
BigLog::useEloquent('Activity');
BigLog::info(new Exception('Lorem ipsum'));
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateActivity extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('activity', function(Blueprint $table)
{
$table->increments('id');
$table->integer('level');
$table->string('level_name');
$table->text('message');
$table->timestamps();
$table->index('level');
$table->index('level_name');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('activity');
}
}
<?php namespace BigBrother\Log;
use Closure;
use Illuminate\Events\Dispatcher;
use Illuminate\Log\Writer as IlluminateLogWriter;
use Monolog\Handler\StreamHandler;
use Monolog\Logger as MonologLogger;
use Monolog\Handler\RotatingFileHandler;
class Writer extends IlluminateLogWriter {
public function useEloquent($class, $level = 'debug')
{
$level = $this->parseLevel($level);
$this->monolog->pushHandler(new Handler\EloquentHandler($class, $level));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment