This article was published on 30 Jul 2016, this means the content may be
out of date or no longer relevant. You should verify that the technical information in this article is still current before relying upon it for your own purposes.
By default Laravel stores all error messages in logs files in storage/logs directory. But sometimes it is not
very convenient to analyze these log files or to aggregate them. In this article, I’m going to use mysql and
Eloquent to store errors in a database.
First of all, we need a table, so lets create a model and an empty migration:
This command will create a model App\Log with an appropriate migration for it.
Next, we need to configure Monolog. Laravel uses this library for logging. To use custom logging we need to override the
Illuminate\Foundation\Bootstrap\ConfigureLogging class. Bur before we need to create a custom Mongolog EloquentHandler
to store logs in a database and a custom RequestProcessor preprocessor to add some more information from the request
to our logs.
Now let’s create the ConfigureLogging class and put it into the app/Vendors/Illuminate/Foundation/Bootstrap folder. In
the bootstrap() method we will set our EloquentHandler and RequestProcessor:
Lastly, we need to update our Kernel class. We override the $boostrappers property of the parent HttpKernel class and
add a new ConfigureLogging class to the array:
Next, we can change our exception Handler, to specify what kind of exceptions we don’t want to log to database:
We can use another storage for logs. MongoDB is a document-orientated database, and I think it the best solution for storing logs, because we
are not limited to the schema.
First of all, we need to install mongodb php driver:
I’m going to use both databases in my project: MySQL as a basic storage and MongoDB for logs and statistics.
To use MongoDB we need to update the config/database.php file and add mongodb driver there:
Then, we need to add a new service provider to the config/app.php file:
The last part is simply to extend our Log model from Jenssegers\Mongodb\Eloquent\Model. And because we use two database connections, we need to
specify the connection. I’ve also specified the collection name:
That’s all, now all logs will be stored in the logs collection in our app database.
@ 2021. All rights reserved.
If you've got any feedback, comments or just want to chat you can get in
touch via Twitter or email.