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

Php How to Change Date Format in Json Response Laravel

How to Change Date Format in Json Response Laravel ?

July 9, 2022November 17, 2023

In json response we get different data format and to change date format in Json Response Laravel we need to make bit extra efforts to show correct date format. Laravel provides by default two timestamp created_at and updated_at, and there format are according to database format but sometimes we want…

Read More
Php laravel custom validation

How to make custom validation in Laravel 8 ?

October 19, 2021October 28, 2021

In this tutorial we will learn to implement custom validation rule in Laravel 8. Laravel has too many validation rules but sometime we feel some rules are missing according to our project need. so, in this article we will learn to implement custom reusable validation rule and implement the username…

Read More
Php Laravel group by with example

How to use laravel group by with example ?

January 22, 2022January 22, 2022

MySQL group by is used to group same column value multiple rows into one row so to create the group by query we used groupBy method. laravel groupBy method accepts single and multiple parameter as column name. In this article i will show you to use groupBy in multiple ways,…

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