Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks
How to create logs file in laravel

How to create logs file in laravel 8 / 9 ?

Aman Jain, May 12, 2022May 12, 2022

In this article i will show you to use and create logs file in laravel. Logging is an important aspect when you want to debug your application or you want to monitor the user activities on the application. Laravel itself provides a robust library to create logging on daily basis, stack, slack, single file etc.

Laravel have different logs level to emergency, alert, critical, error, warning, notice, info, and debug.

Laravel uses channels to log the logs for example single channel store logs in single file in storage logs folders and slacks send logs information to slack provider.

Configuration file of laravel logs

You can configure the laravel logs configuration in config/logging.php file. here is the look of logging.php

<?php

use Monolog\Handler\NullHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Handler\SyslogUdpHandler;

return [

    /*
    |--------------------------------------------------------------------------
    | Default Log Channel
    |--------------------------------------------------------------------------
    |
    | This option defines the default log channel that gets used when writing
    | messages to the logs. The name specified in this option should match
    | one of the channels defined in the "channels" configuration array.
    |
    */

    'default' => env('LOG_CHANNEL', 'stack'),

    /*
    |--------------------------------------------------------------------------
    | Log Channels
    |--------------------------------------------------------------------------
    |
    | Here you may configure the log channels for your application. Out of
    | the box, Laravel uses the Monolog PHP logging library. This gives
    | you a variety of powerful log handlers / formatters to utilize.
    |
    | Available Drivers: "single", "daily", "slack", "syslog",
    |                    "errorlog", "monolog",
    |                    "custom", "stack"
    |
    */

    'channels' => [
        'stack' => [
            'driver' => 'stack',
            'channels' => ['single'],
            'ignore_exceptions' => false,
        ],

        'single' => [
            'driver' => 'single',
            'path' => storage_path('logs/laravel.log'),
            'level' => env('LOG_LEVEL', 'debug'),
        ],

        'daily' => [
            'driver' => 'daily',
            'path' => storage_path('logs/laravel.log'),
            'level' => env('LOG_LEVEL', 'debug'),
            'days' => 14,
        ],

        'slack' => [
            'driver' => 'slack',
            'url' => env('LOG_SLACK_WEBHOOK_URL'),
            'username' => 'Laravel Log',
            'emoji' => ':boom:',
            'level' => env('LOG_LEVEL', 'critical'),
        ],

        'papertrail' => [
            'driver' => 'monolog',
            'level' => env('LOG_LEVEL', 'debug'),
            'handler' => SyslogUdpHandler::class,
            'handler_with' => [
                'host' => env('PAPERTRAIL_URL'),
                'port' => env('PAPERTRAIL_PORT'),
            ],
        ],

        'stderr' => [
            'driver' => 'monolog',
            'level' => env('LOG_LEVEL', 'debug'),
            'handler' => StreamHandler::class,
            'formatter' => env('LOG_STDERR_FORMATTER'),
            'with' => [
                'stream' => 'php://stderr',
            ],
        ],

        'syslog' => [
            'driver' => 'syslog',
            'level' => env('LOG_LEVEL', 'debug'),
        ],

        'errorlog' => [
            'driver' => 'errorlog',
            'level' => env('LOG_LEVEL', 'debug'),
        ],

        'null' => [
            'driver' => 'monolog',
            'handler' => NullHandler::class,
        ],

        'emergency' => [
            'path' => storage_path('logs/laravel.log'),
        ],
    ],

];

If you look above file default log channel is 'default' => env('LOG_CHANNEL', 'stack') stack and in stack channel we can configure multiple providers to log the information as below

 'channels' => [
        'stack' => [
            'driver' => 'stack',
            'channels' => ['single'],
            'ignore_exceptions' => false,
        ],

        'single' => [
            'driver' => 'single',
            'path' => storage_path('logs/laravel.log'),
            'level' => env('LOG_LEVEL', 'debug'),
        ],

Logging the logs

To log the information we use use Illuminate\Support\Facades\Log class as below

use Illuminate\Support\Facades\Log;
 
Log::emergency($message);
Log::alert($message);
Log::critical($message);
Log::error($message);
Log::warning($message);
Log::notice($message);
Log::info($message);
Log::debug($message);

Example to use:

use Illuminate\Support\Facades\Log;
Log::info("Simple Log",["info"=>"This is simple log by readerstacks"]);

So, each method accepts two parameters first as string and another one as array as above. Make sure second parameter is array otherwise it will throw exception.

Let’s understand create logs file in laravel 8 / 9 with example

Step 1: Create a laravel project

First step is to create the Laravel 8 project using composer command or you can also read the How to install laravel 8 ? and Laravel artisan command to generate controllers, Model, Components and Migrations

composer create-project laravel/laravel example-app

Step 4 : Create a controller

Create the controller and add the necessary imports and class. You can create by Laravel artisan or manually.

php artisan make:controller ArticleController

Now, add the controller logic for pagination and Ajax

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Article;
use Illuminate\Support\Facades\Log;

class ArticleController extends Controller
{
    public function index(Request $request)
    {
        $articles = Article::paginate(5);
        Log::info("Articles data" , ["data"=>$articles]);
        $type="ALERT";
        Log::alert("Articles alert ".$type." Error") ;
        return $articles;
    }
}

Step 3 : Create Route

Now, create a route and log the information

<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ArticleController;


Route::get('/log-info',[ArticleController::class, 'index']);

Create separate file for every day or date wise

If you want to create a separate file for each day then you can use daily configuration in config file of log as below

 'channels' => [
        'stack' => [
            'driver' => 'stack',
            'channels' => ['daily'],
            'ignore_exceptions' => false,
        ]

         

Location of logs file in laravel

you will be able to find the location at storage/logs/laravel.log in case of single file and if its daily then storage/logs/date.logs

Create Request Id for each request using Middleware

You can attach a request id with each using middleware, learn about middleware in larave from here

<?php
 
namespace App\Http\Middleware;
 
use Closure;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
 
class AssignRequestIdToRequest
{
     
    public function handle($request, Closure $next)
    {
        $requestId = (string) Str::uuid();
 
        Log::withContext([
            'request-id' => $requestId
        ]);
 
        return $next($request)->header('Request-Id', $requestId);
    }
}

Write logs to specific log channel or multiple at runtime

You can write to multiple logs channel or specific to any channel by overriding the configuration as below

Log::stack(['single', 'slack'])->info('Something happened!');

Also Read : How to Send Mail with Attachment(PDF, docs,image) in Laravel ?

Related

Php Laravel Laravel 9 laravellogsphp

Post navigation

Previous post
Next post

Related Posts

How to print database query in laravel 8 ?

January 1, 2022February 22, 2024

Sometime to debug the MySQL query in laravel eloquent we need to print the raw MySQL query. In laravel we have multiple methods to print database query in laravel 8 and we can also print the query before executing it. Laravel eloquent method to print the query The first approach…

Read More
Javascript Laravel Ajax Autocomplete Using Select2

Laravel Customized Autocomplete Options Using Select2

July 18, 2022July 18, 2022

In this article we will learn to use Laravel Customized Autocomplete Options Using Select2. Select2 is useful when we want live search of bulk data or to convert the existing select boz with multi features like search, multi select and options customizations. Autocomplete search is mostly work of javascript and…

Read More
Php How to create multiple size thumbs from image in laravel

How to create multiple size thumbs from image in laravel 9 ?

May 14, 2022February 22, 2024

Resizing images can be a best performance booster for any application since this will load the proper size images. In this article i will show you to create multiple size thumbs from image in laravel using intervention package. Big size of image can reduce the performance of the application therefor…

Read More

Aman Jain
Aman Jain

With years of hands-on experience in the realm of web and mobile development, they have honed their skills in various technologies, including Laravel, PHP CodeIgniter, mobile app development, web app development, Flutter, React, JavaScript, Angular, Devops and so much more. Their proficiency extends to building robust REST APIs, AWS Code scaling, and optimization, ensuring that your applications run seamlessly on the cloud.

Categories

  • Angular
  • CSS
  • Dart
  • Devops
  • Flutter
  • HTML
  • Javascript
  • jQuery
  • Laravel
  • Laravel 10
  • Laravel 11
  • Laravel 9
  • Mysql
  • Php
  • Softwares
  • Ubuntu
  • Uncategorized

Archives

  • June 2025
  • May 2025
  • April 2025
  • October 2024
  • July 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • July 2023
  • March 2023
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Recent Posts

  • The Resilience of Nature: How Forests Recover After Fires
  • Understanding Laravel Cookie Consent for GDPR Compliance
  • Understanding High Vulnerabilities: A Critical Overview of the Week of May 12, 2025
  • Installing a LAMP Stack on Ubuntu: A Comprehensive Guide
  • Understanding High Vulnerabilities: A Deep Dive into Recent Security Concerns
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version