PHPackages                             salimkamboh/laravel-log-to-db - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. salimkamboh/laravel-log-to-db

ActiveLibrary[Database &amp; ORM](/categories/database)

salimkamboh/laravel-log-to-db
=============================

Custom Laravel Log channel handler that can store log events to SQL or MongoDB databases. Uses Laravel native logging functionality.

v1.0.0(1y ago)05MITPHPPHP ^8.1

Since Mar 3Pushed 8mo agoCompare

[ Source](https://github.com/salimkamboh/laravel-log-to-db)[ Packagist](https://packagist.org/packages/salimkamboh/laravel-log-to-db)[ RSS](/packages/salimkamboh-laravel-log-to-db/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (6)Versions (2)Used By (0)

Laravel Log-to-DB
=================

[](#laravel-log-to-db)

[![GitHub](https://camo.githubusercontent.com/7123c32787e013be5a8a13598ad01f562754637ed6141e89b02e85bf16d3e63e/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f6d6173686170652f6170697374617475732e7376673f7374796c653d666c61742d737175617265)](https://github.com/danielme85/laravel-log-to-db)[![PHP from Packagist](https://camo.githubusercontent.com/539971cc2aaefe08e9006354f8a3c105800fb54a5ab86883dc8257e1d17ac403/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f64616e69656c6d6538352f6c61726176656c2d6c6f672d746f2d64622e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/danielme85/laravel-log-to-db)[![GitHub release](https://camo.githubusercontent.com/d745e029004d99c393358ece57f8442df6148d8bb204c331a9335c4af4ea0212/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f72656c656173652f64616e69656c6d6538352f6c61726176656c2d6c6f672d746f2d64622e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/danielme85/laravel-log-to-db)[![GitHub tag](https://camo.githubusercontent.com/a830aabd87b216b7a292b24879fb3d8840c112a8daa1bf180289738276459cd1/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f7461672f64616e69656c6d6538352f6c61726176656c2d6c6f672d746f2d64622e7376673f7374796c653d666c61742d737175617265)](https://github.com/danielme85/laravel-log-to-db)[![Codecov](https://camo.githubusercontent.com/cfc5922e5a6876f6026502950333de6bc13eeefe0da53da6ab965ef43c2a1747/68747470733a2f2f696d672e736869656c64732e696f2f636f6465636f762f632f6769746875622f64616e69656c6d6538352f6c61726176656c2d6c6f672d746f2d64622e7376673f7374796c653d666c61742d737175617265)](https://codecov.io/gh/danielme85/laravel-log-to-db)[![CodeFactor](https://camo.githubusercontent.com/24a6174a2c9f79aaefa32ebcc68b7a62518460b690627fda0ec5dc45399c8b50/68747470733a2f2f696d672e736869656c64732e696f2f636f6465666163746f722f67726164652f6769746875622f64616e69656c6d6538352f6c61726176656c2d6c6f672d746f2d64623f7374796c653d666c61742d737175617265)](https://www.codefactor.io/repository/github/danielme85/laravel-log-to-db)[![CircleCI](https://camo.githubusercontent.com/8773d95d43cb0a64e043ee12571fbd2f17273e5183eeeb82dfd005a8bfa5d011/68747470733a2f2f646c2e636972636c6563692e636f6d2f7374617475732d62616467652f696d672f67682f64616e69656c6d6538352f6c61726176656c2d6c6f672d746f2d64622f747265652f6d61696e2e7376673f7374796c653d736869656c64)](https://dl.circleci.com/status-badge/redirect/gh/danielme85/laravel-log-to-db/tree/main)

Hi, this is a custom Laravel 5.6+ Log channel handler that can store log events to SQL or MongoDB databases. Uses Laravel native logging functionality trough [Monolog](https://github.com/Seldaek/monolog).

- [Installation](#installation)
- [Configuration](#configuration)
- [Usage](#usage)
- [Fetching Logs](#fetching-logs)
- [Custom Eloquent Model](#custom-eloquent-model)
- [Log Cleanup](#log-cleanup)
- [Processors](#processors)
- [Lumen Installation](#lumen-installation)
- [Local Testing With Docker](#local-testing-with-docker)

> ⚠️ For Laravel version 10 and beyond, please use version 4 or later of this package.
>  For Laravel version 5.6 to 9, please use version 3.x.x.

Installation
------------

[](#installation)

Use the composer require or add to composer.json.

```
composer require danielme85/laravel-log-to-db

```

If you are using SQL database server to store log events you can use the migration included. The MongoDB driver does not require the migration. Copy the migration file for log the database table to your app (you can also do any changes you want or manually copy this file your database/migrations folder).

```
php artisan vendor:publish --tag=migrations --provider="danielme85\LaravelLogToDB\ServiceProvider"

```

Run the Laravel migration artisan command.

```
php artisan migrate

```

*For optional MongoDB support you need to install jenseegers/mongodb addon to Laravel*

```
#Optional mongodb support, not required!

composer require jenssegers/mongodb

```

Configuration
-------------

[](#configuration)

Starting with Laravel 5.6 and later, you will have a new config file: "config/logging.php". You will need to add an array under 'channels' for Log-to-DB here like so:

```
'database' => [
    'driver' => 'custom',
    'via' => danielme85\LaravelLogToDB\LogToDbHandler::class
    ...
    ],
```

These are the minimum required logging.php config settings to get started. Please note that the array index 'database' can be whatever string you like as long as it is unique to this logging config. You can also give the logging channel a name that later is referenced in a column in the DB table, this way you can have multiple logging-to-db channels.

```
'channels' => [
    'stack' => [
        'name' => 'Log Stack',
        'driver' => 'stack',
        'channels' => ['database', 'other-database', 'file'],
    ],
    'database' => [
        'driver' => 'custom',
        'via' => danielme85\LaravelLogToDB\LogToDbHandler::class,
        'name' => 'Basic DB Logging'
    ],
    'other-database' => [
        'driver' => 'custom',
        'via' => danielme85\LaravelLogToDB\LogToDbHandler::class,
        //'model' => App\Model\Log::class, //Your own optional custom model
        'level' => env('APP_LOG_LEVEL', 'debug'),
        'name' => 'My DB Log with a bunch more settings',
        'connection' => 'default',
        'collection' => 'log',
        'detailed' => true,
        'queue' => false,
        'queue_name' => '',
        'queue_connection' => '',
        'max_records' => false,
        'max_hours' => false,
        'processors' => [
              //Monolog\Processor\HostnameProcessor::class
              // ..
         ]
    ],
    ...
]
```

- driver = Required to trigger the log driver.
- via = The Log handler class.
- level = The minimum error level to trigger this Log Channel.
- name = The channel name that will be stored with the Log event. Please note that if you use the stack driver the name value in the stack array is used.
- connection = The DB connection from config/database.php to use (default: 'default').
- collection = The DB table or collection name. (Default: log).
- detailed = Store detailed log on Exceptions like stack-trace (default: true).
- processors = Array of additional processors. These will add additional info into the 'extra' field in the logged data. [More information about processors](#processors)

More info about some of these options:

There are some default settings and more information about configuring the logger in the 'logtodb.php' config file. This could be copied to your project if you would like edit it with the vendor publish command.

```
php artisan vendor:publish --tag=config --provider="danielme85\LaravelLogToDB\ServiceProvider"

```

You can also change these settings in your env file.

```
LOG_DB_CONNECTION='default'
LOG_DB_DETAILED=false
LOG_DB_MAX=100
LOG_DB_QUEUE=false
LOG_DB_QUEUE_NAME='logToDBQueue'
LOG_DB_QUEUE_CONNECTION='default'
LOG_DB_MAX_COUNT=false
LOG_DB_MAX_HOURS=false
LOG_DB_DATETIME_FORMAT='Y-m-d H:i:s:ms'

```

> **PLEASE NOTE**: Starting with v2.2.0, the datetime column will be saved as a string in the format given in 'datetime\_format' in logtodb.php config file, or the LOG\_DB\_DATETIME\_FORMAT value in your .env file.

#### Config priority order

[](#config-priority-order)

There are three places you can change different options when using log-to-db:

1. The config file: config/logtodb.php (after doing vendor:publish).
2. Your .env file will override settings in the logtodb.php config file.
3. The Laravel logging config file: config/logging.php. You need to add a custom array here as mentioned above, in this same array you can specify/override config settings specifically for that log channel.

Config values set in point 1 &amp; 2 would work as default for all new log channels you add in the "channels" array for the Laravel logging configuration (config/logging.php).

#### Log Worker Queue

[](#log-worker-queue)

It might be a good idea to save the log events with a Queue Worker. This way your server does not have to wait for the save process to finish. You would have to configure the Laravel Queue settings and run the Queue listener.

The queue can be enabled/disabled in any of the following places:

- LOG\_DB\_QUEUE = true | in .env
- queue\_db\_saves =&gt; true | in config/logtodb.php
- queue =&gt; true | in the log channel config array -&gt; config/logging.php

Usage
-----

[](#usage)

Since this is a custom log channel for Laravel, all "standard" ways of generating log events etc should work with the Laravel Log Facade. See  for more information.

```
Log::debug("This is an test DEBUG log event");
Log::info("This is an test INFO log event");
Log::notice("This is an test NOTICE log event");
Log::warning("This is an test WARNING log event");
Log::error("This is an test ERROR log event");
Log::critical("This is an test CRITICAL log event");
Log::alert("This is an test ALERT log event");
Log::emergency("This is an test EMERGENCY log event");
```

You can also log to specific log channels: Log::channel('database')debug("This is an test DEBUG log event");

Fetching Logs
-------------

[](#fetching-logs)

The logging by this channel is done trough the Eloquent Model builder. LogToDB::model($channel, $connection, $collection); You can skip all function variables and the default settings from the config/logtodb.php will be used.

```
$model = LogToDB::model();
$model->get(); //All logs for default channel/connection
```

Some more examples of getting logs

```
$logs = LogToDB::model()->get();
$logs = LogToDB::model()->where('level_name', '=', 'INFO')->get();
```

When getting logs for specific channel or DB connection and collection you can either use the channel name matching config/logging.php or connection name from config/databases.php. You can also specify collection/table name if needed as the third function variable when fetching the model.

```
$logsFromDefault = LogDB::model()->get(); //Get the logs from the default log channel and default connection.
$logsFromChannel = LogDB::model('database')->get(); //Get logs from the 'database' log channel.
$logsFromChannel = LogDB::model('customname')->get(); //Get logs from the 'customname' log channel.
$logsFromMysql   = LogToDB::model(null, 'mysql')->get(); //Get all logs from the mysql connection (from Laravel database config)
$logsFromMongoDB = LogToDB::model(null, 'mongodb')->get(); //Get all logs from the mongodb connection (from Laravel database config)
$logsFromMysqlTable  = LogToDB::model(null, 'mysql', 'table')->get(); //Get all logs from the mysql table: 'table'
```

Custom Eloquent Model
---------------------

[](#custom-eloquent-model)

Since Laravel is supposed to use static defined collection/table names, it might be better to use your own model in your app for a more solid approach. You can use your own eloquent model by referencing it in the config, then adding the trait: "LogToDbCreateObject"

##### SQL

[](#sql)

```
namespace App\Models;

use danielme85\LaravelLogToDB\Models\LogToDbCreateObject;
use Illuminate\Database\Eloquent\Model;

class CustomLog extends Model
{
    use LogToDbCreateObject;

    protected $table = 'log';
    protected $connection = 'mysql';

}
```

##### MongoDB

[](#mongodb)

```
namespace App\Models;
use danielme85\LaravelLogToDB\Models\LogToDbCreateObject;
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;

class CustomLogMongo extends Eloquent
{
    use LogToDbCreateObject;

    protected $collection = 'log';
    protected $connection = 'mongodb';

}
```

LOG\_DB\_MODEL='App\\Models\\CustomLog'

> **WARNING**: Fetching the model trough the dynamic Eloquent model (default behavior) have some side-effects as tables and connections are declared dynamically instead of assigned properties in the model class. Certain functions are broken like LogToDB::model-&gt;all(), while LogToDB::model-&gt;where()-&gt;get() will work as normal. Using your own models avoids these problems.

#### Model Closures and Observers

[](#model-closures-and-observers)

You can either add [closures](https://laravel.com/docs/7.x/eloquent#events-using-closures) on your custom application model mentioned above, or add a [model observer](https://laravel.com/docs/7.x/eloquent#observers) for the default LogToDb models.
Create a observer:

```
