Skip to content

Instantly share code, notes, and snippets.

@znsstudio
Created March 31, 2016 16:19
Show Gist options
  • Save znsstudio/385dad35f8e904419eeade5c0b8be2d2 to your computer and use it in GitHub Desktop.
Save znsstudio/385dad35f8e904419eeade5c0b8be2d2 to your computer and use it in GitHub Desktop.
Gist for simple database logging in Laravel 4, instead of plain text files. You will then be able to get logs from your DB like this : `SELECT * FROM logs;`
<?php
// app/start/global.php
/*
|--------------------------------------------------------------------------
| Application Error Logger
|--------------------------------------------------------------------------
|
| Here we will configure the error logger setup for the application which
| is built on top of the wonderful Monolog library. By default we will
| build a rotating log file setup which creates a new file each day.
|
*/
//$logFile = 'log-'.php_sapi_name().'.txt';
//Log::useDailyFiles(storage_path().'/logs/'.$logFile);
// Log to the database asynchronously
Log::listen(function($level, $message, $context) {
// Save the php sapi and date, because the closure needs to be serialized
$apiName = php_sapi_name();
$date = new DateTime;
Queue::push(function() use ($level, $message, $context, $apiName, $date) {
DB::insert("INSERT INTO logs (php_sapi_name, level, message, context, created_at) VALUES (?, ?, ?, ?, ?)", array(
$apiName,
$level,
$message,
json_encode($context),
$date
));
});
});
<?php
use Illuminate\Database\Migrations\Migration;
class AppMigrationCreateLogTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('logs', function($t)
{
$t->increments('id');
$t->string('php_sapi_name');
$t->string('level');
$t->text('message');
$t->text('context');
$t->timestamp('created_at');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('logs');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment