Laravel Logging All You Need to Be Able To

If you are developing a modern app Logging must be on the top of the priorities.
Logging provides a way to visualize your app at both stages of development and in production. This allows for transparency and view. When properly structured, logging modern applications can become easier to manage as we are able to proactively identify points where performance issues and failures are occurring within our application.
The Laravel framework is equipped with an extremely robust log system that can deal with all hurdles involved in configuring the right logging framework out of the box. The new logging system that was introduced in Laravel 6.5 is effective, and we will explore it in this piece.
This article will go over the fundamentals of Laravel logging and why you should use Laravel logging in your next project. This article will explore central logging as well as structured logging in detail. Additionally, we'll learn how to implement Laravel Logging by creating an Todo application.
You'll get more out of this piece if are able to put these things in your repertoire:
- A good understanding of web development
- Building apps with Laravel
What is Laravel Logging?
Laravel logs are all about the way Laravel handles logging, or automatic issue reporting, using a viral PHP log system known as Monolog. But, because of Laravel's approach of using well-known libraries to implement different framework features, Laravel employs Monolog for the entirety of its logging requirements.
Monolog is an extremely adaptable and widely used PHP logging library that you can configure to send your log files to files, databases, sockets and various other services on the web. Monolog provides a familiar interface for writing logs from basic text files, to more sophisticated third-party log management tools. Laravel typically sets up Monolog using a standard Logging configuration file.
For more information about Monolog and its features read the official documentation, as that is outside the scope of this post.
Before we dive into configuring and implementing Laravel Logging using Monolog let's explore more reasons to use Laravel Logging and the various types.
What is the reason to use Laravel Logging?
The reason why logs are necessary?
The Twelve-Factor Application document addresses logging as one of the critical concerns of a modern application, since it is a key to the performance of an application and its monitoring.
Logging structured is an essential tool for applications in production, helping to identify defects and solving problems that arise in production. In addition, you can keep track of and record all your log messages in real-time using specialized logging tools to analyze and report live.
This is why you must make organized logs a priority for your next modern application project.
We will look at the summary of the different logging styles that are available.
Basics of Laravel Logging
Learning the basics of logging will help you learn how Laravel handles logs and help you optimize your log-keeping practices.
We will look at two key ideas in logging in order to learn how best to apply our log-keeping procedures.
Laravel Structured Logging
In the field of software development, structured logging is implementing a predetermined and consistent message format that is used for logs of applications. This format allows the messages to be used as data that can be tracked, altered and visualized better as compared to the standard text format.
Implement a systematic log-keeping strategy in modern application development because log files are essential assets for developers when an error occurs to your application in production.
Since Laravel makes use of Monolog developers are able to swiftly set up structured logs, by setting the logger to accept specific types of information, storing the log files in various formats and transmitting the log files to different third-party log management systems for display.
Laravel Centralized Logging
A central logging system is in which logs are passed into Centralized Log Management (CLM) applications from multiple sources to allow for quick consolidation and easy visualization. But, CLM is a specially designed logger solution that collects log messages from different sources and consolidates the data for easy processing and visualization.
Aside from data collection, CLM is also expected to support the analysis of log data , as well as an easy presentation of data after analysis.
Structured Logging vs Basic Logging
It is important to understand the distinction between structured and basic (unstructured) logs and the reasons you should use structured logging in the development of your Laravel project.
Basic Logging
For basic logging, log files are saved in a raw format with limited data to query and find specific logs.
There are three big reasons not to use basic logging:
- Log management systems that are centralized can use the information without support.
- The solution must be customized for reading and parsing the data of a basic software for logging.
- It can be challenging for administrators to comprehend basic logging data since it is not structured and is raw.
Structured Logging
Structured logging saves developers time using third-party open-source log analysis tools that can support the standard log structure in order to read, view, and analyse logs.
Logs are useful when they contain the correct data listed below, which is what structured logging aims to accomplish. We can use the data that is part of structured logging to build dashboards, graphs and charts, or any other beneficial visualization that helps us determine the health of an application.
These are the basic types of what is possible to include in structured log messages. Furthermore, you have the option to modify the information completely to suit your needs.
Here are some instances of data that you could gather using structured logging:
- The port is used to perform the function
- When and on what date the event happened
- The customer username or ID
- An explanation of the incident (log message)
- The protocol used to execute the task.
- The location of the triggered event (indicate the API or the running app)
- The unique event ID
- The action type that was triggers (log level)
The logs need to contain enough information that you can easily see the answer or the cause of the log events. Be aware that you should not store all types of information, for example, passwords and sensitive data within logs.
Are you interested in knowing what we did to increase our traffic over 1000 percent?
Join the 20,000+ who receive our weekly newsletter that contains insider WordPress tips!
After we've seen the basics of what Laravel Logging is all about, let's go towards implementing Laravel logs by creating an application with logging as a first-class citizen.
The Best Way To Implement Laravel Logging with Todo App
We'll apply the lessons we've learned by creating a new Laravel project, and then implementing Laravel logging.
Installing Laravel
First, we're going to start a new Laravel instance using the below command. It is possible to look through the official Laravel documentation for more.
Start your console, and then navigate to where you store your PHP projects before performing these commands. Be sure you that you have Composer properly installed and configured.
composer create-project laravel/laravel laravel-logging-app
cd laravel-logging-app // Change directory to current Laravel installation
php artisan serve // Start Laravel development serverConfiguring and Seeding the Database
Next, we will establish our database, develop a brand-new model called a Todo model, and seed 200 fake data to be tested.
Launch your database application and make a fresh database. We'll do the same with the name laravel_logging_app_db and then fill up our .env file with the database credentials:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_logging_app_db
DB_USERNAME=//DB USERNAME HERE
DB_PASSWORD=//DB PASSWORD HEREThen, we'll execute the following command to create the migration as well as the todo model at the same time:
php artisan make:model Todo -mcOpen the newly created migration found database/migrations/xxx-create-todos-xxx.php and paste in the following codes:
id();
$table->string('title');
$table->text('description')->nullable();
$table->boolean('is_completed')->default(false);
$table->timestamps();
);
/**
* Reverse the migrations. *
* @return void
*/
public function down()
Schema::dropIfExists('todos');
Your todos can be seeded using fake data, by learning how to seed your databases within Laravel by using Faker.
Overview of Monolog
Through Laravel Monolog it is possible to transmit structured logs to different channels such as emails, Slack, files, inboxes, sockets, databases and a variety of web-based services. In Laravel it is possible to set up logs from a single setting file, which is in config/logging.php.
The configuration file comes with the predefined log driver to select from, and the default driver is an a stack which uses the single channel to record to the laravel.log file found in the logs/storage folder. We will demonstrate the logging structure using few of Laravel log drivers.
Laravel offers an handful of methods to interact with Logs, as demonstrated generally in the TodosController.php controller file in a short time.
Writing Log Messages in the Controller
Start the newly made TodosController.php controller file located in the within the app/Http/Controllers folder and paste in these codes:
Auth::user()->id]);
return view('dashboard')->with(['todos' => $todos]);
public function byUserId(Request $request)
$todos = Todo::where('user_id', Auth::user()->id)->get();
Log::info('User is accessing all his todos', ['user' => Auth::user()->id]);
return view('dashboard')->with(['todos' => $todos]);
public function show(Request $request, $id)
$todo = Todo::find($id);
Log::info('User is accessing a single todo', ['user' => Auth::user()->id, 'todo' => $todo->id]);
return view('show')->with(['todo' => $todo]);
public function update(Request $request, $id)
# Validations before updating
$todo = Todo::where('user_id', Auth::user()->id)->where('id', $id)->first();
Log::warning('Todo found for updating by user', ['user' => Auth::user()->id, 'todo' => $todo]);
if ($todo)
$todo->title = $request->title;
$todo->desc = $request->desc;
$todo->status = $request->status == 'on' ? 1 : 0;
if ($todo->save())
Log::info('Todo updated by user successfully', ['user' => Auth::user()->id, 'todo' => $todo->id]);
return view('show', ['todo' => $todo]);
Log::warning('Todo could not be updated caused by invalid todo data', ['user' => Auth::user()->id, 'todo' => $todo->id, 'data' => $request->except('password')]);
return; // 422
Log::error('Todo not found by user', ['user' => Auth::user()->id, 'todo' => $id]);
return; // 401
public function store(Request $request)
Log::warning('User is trying to create a single todo', ['user' => Auth::user()->id, 'data' => $request->except('password')]);
# Validations before updating
$todo = new Todo;
$todo->title = $request->title;
$todo->desc = $request->desc;
$todo->user_id = Auth::user()->id;
if ($todo->save())
Log::info('User create a single todo successfully', ['user' => Auth::user()->id, 'todo' => $todo->id]);
return view('show', ['todo' => $todo]);
Log::warning('Todo could not be created caused by invalid todo data', ['user' => Auth::user()->id, 'data' => $request->except('password')]);
return; // 422
public function delete(Request $request, $id)
Log::warning('User is trying to delete a single todo', ['user' => Auth::user()->id, 'todo' => $id]);
$todo = Todo::where('user_id', Auth::user()->id)->where('id', $id)->first();
if ($todo)
Log::info('User deleted a single todo successfully', ['user' => Auth::user()->id, 'todo' => $id]);
$todo->delete();
return view('index');
Log::error('Todo not found by user for deleting', ['user' => Auth::user()->id, 'todo' => $id]);
return; // 404
In each method within TodoController, in each of the methods within TodoController, we have added the Log facade that has a particular log level that defines the type of error we wish to communicate. Here is an example how to use the
Log facades in the store method.
public function store(Request $request)
Log::warning('User is trying to create a single todo', ['user' => Auth::user()->id, 'data' => $request->except('password')]);
# Validations before updating
$todo = new Todo;
$todo->title = $request->title;
$todo->desc = $request->desc;
$todo->user_id = Auth::user()->id;
if ($todo->save())
Log::info('User create a single todo successfully', ['user' => Auth::user()->id, 'todo' => $todo->id]);
return view('show', ['todo' => $todo]);
Log::warning('Todo could not be created caused by invalid todo data', ['user' => Auth::user()->id, 'data' => $request->except('password')]);
return; // 422
Formatting Log Messages
Suppose you're not comfortable using what's the standard LineFormatter used by Laravel and does a great job of providing readable and helpful message.
If you do you are able to easily create a custom formatter object that is suited to the needs of your application and then use it in the entirety of the program.
The official Monolog documentation gives a complete listing of formats available and allows you to easily design your own.
In Laravel, you can easily set any of the drivers to use your custom formatter by making it available as shown below in the configuration file located at config/logging.php:
'daily' => [
'driver' => 'daily',
'path' => storage_path('logs/laravel.log'),
'level' => env('LOG_LEVEL', 'debug'),
'days' => 14,
'formatter' => MonologFormatterHtmlFormatter::class,
'formatter_with' => [
'dateFormat' => 'Y-m-d',
]
],The example above adds a custom MonologFormatterHtmlFormatter to the daily driver using the formatter and formatter_with key in the daily channel configuration to change the format of dates.
Sending Logs to Different Channels
Through Monolog, Laravel is able to send logs to different channels and multiple channels simultaneously.
Let's demonstrate how to send logs to our Slack channel following these simple steps. Switch the default log channel to Slack. Then, add the the Slack Webhook URL to the.env file. .env file.
LOG_CHANNEL=slack
LOG_SLACK_WEBBHOOK_URL= Slack_webhook_url_hereThen, you can test your application's configuration by recording an application message using your Log interface, which is similar to that in the following image:
Log::debug("The API instance is caught on fire due to:" ['user' =greater than 1one)You can open your Slack channel to look the message that was printed on the preferred channel that you chose when generating the Webhook URL.
Summary
Logging is just as crucial just like the other aspects of your application or even more important. It's the reason it's mentioned in the Twelve-Factor App manifesto to be one of the most critical concerns of any modern application.
Through effective logging it is easy to read, view, and see the flaws and errors that happen in your production-ready application. For this reason it is essential to implement structured logging into your app before the commencement of the development.
In this piece we've examined Laravel logs and the reasons you should consider using it for your next project. We've covered both structured logging and centralized the logging process in greater detail. Additionally, we were taught how to implement Laravel logging by building the Todo application.
How do you plan to integrate logging into the next application you use? Please let us know via the comments.
Save time, costs and maximize site performance with:
- 24/7 help and support from WordPress hosting experts 24/7.
- Cloudflare Enterprise integration.
- The global reach of the audience is enhanced by 34 data centers worldwide.
- Optimization with the integrated Application Performance Monitoring.