search
HomePHP FrameworkLaravelHow to customize the analysis of log behavior in Laravel5.5

The content of this article is to share with you the analysis of how to customize the log behavior in Laravel5.5. The content is very detailed and has certain reference value. I hope it can help friends in need.

In Laravel 5.6 version, log behavior can be easily customized, while in versions below 5.5, the degree of freedom to customize log behavior is not very high, but if the project has needs, it cannot be forced because of this. Upgrade the project to 5.6. Moreover, as a stable project, upgrading the framework to a large version may have many pitfalls. For these reasons, I tried to transform the logs of Laravel 5.5 to suit my needs.

Most of Laravel's logging behavior is in Illuminate\Log\LogServiceProvider. We can take a look at the code snippets:

/**
 * Configure the Monolog handlers for the application.
 *
 * @param \Illuminate\Log\Writer $log
 * @return void
 */
protected function configureDailyHandler(Writer $log)
{
 $log->useDailyFiles(
  $this->app->storagePath().'/logs/laravel.log', $this->maxFiles(),
  $this->logLevel()
 );
}

This is the log storage method I use most often in projects. , you can see that the log storage path is almost hard-coded and cannot be easily changed through external parameters.

At first I thought of rewriting this Provider and registering it in the providers array of app.php, but this behavior is not feasible because by looking at the source code, LogServiceProvider is registered when the framework starts. .

There is such a method that controls this registration behavior:

protected function registerBaseServiceProviders()
{
 $this->register(new EventServiceProvider($this));

 $this->register(new LogServiceProvider($this));

 $this->register(new RoutingServiceProvider($this));
}

Now that we know how they take effect, we inherit these two classes and modify them We need to change the behavior to transform, and my method of transformation is as follows. Create a new LogServiceProvider class in app\Providers and inherit Illuminate\Log\LogServiceProvider. The code is as follows:

<?php


namespace App\Providers;

use Illuminate\Log\LogServiceProvider as BaseLogServiceProvider;
use Illuminate\Log\Writer;

class LogServiceProvider extends BaseLogServiceProvider
{
 /**
  * Configure the Monolog handlers for the application.
  *
  * @param \Illuminate\Log\Writer $log
  * @return void
  */
 protected function configureDailyHandler(Writer $log)
 {
  $path = config(&#39;app.log_path&#39;);
  $log->useDailyFiles(
   $path, $this->maxFiles(),
   $this->logLevel()
  );
 }
}

Add configuration in the config/app.php directory:

&#39;log_path&#39; => env(&#39;APP_LOG_PATH&#39;, storage_path(&#39;/logs/laravel.log&#39;)),

app Create a new Foundation directory in the directory, create a new Application class that inherits the Illuminate\Foundation\Application class, and overrides the registerBaseServiceProviders method.

<?php
/**
 * Created by PhpStorm.
 * User: dongyuxiang
 * Date: 2018/7/31
 * Time: 16:53
 */

namespace App\Foundation;

use App\Providers\LogServiceProvider;
use Illuminate\Events\EventServiceProvider;
use Illuminate\Routing\RoutingServiceProvider;
use Illuminate\Foundation\Application as BaseApplication;


class Application extends BaseApplication
{

 /**
  * Register all of the base service providers.
  *
  * @return void
  */
 protected function registerBaseServiceProviders()
 {
  $this->register(new EventServiceProvider($this));

  $this->register(new LogServiceProvider($this));

  $this->register(new RoutingServiceProvider($this));
 }
}

It is said that it is rewritten. In fact, it just changes the use class from the LogServiceProvider we created ourselves.

Then in bootstrap\app.php, replace the new object of the variable $app with the one we inherited and rewritten.

$app = new App\Foundation\Application(
 realpath(__DIR__.&#39;/../&#39;)
);

In this way, I successfully defined the log path casually, and with this experience, I can further optimize the areas where the framework does not meet my needs to meet my requirements, and I have not changed the underlying code of the framework, and I can safely update the framework when there are bug fixes in the framework.

Recommended related articles:

php Detailed explanation of custom error log examples

Yii2 Custom log file writing log

The above is the detailed content of How to customize the analysis of log behavior in Laravel5.5. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Collaborative Document Editing: Streamlining Workflow in Distributed TeamsCollaborative Document Editing: Streamlining Workflow in Distributed TeamsApr 27, 2025 am 12:21 AM

Collaborative document editing is an effective tool for distributed teams to optimize their workflows. It improves communication and project progress through real-time collaboration and feedback loops, and common tools include Google Docs, Microsoft Teams, and Notion. Pay attention to challenges such as version control and learning curve when using it.

How long will the previous Laravel version be supported?How long will the previous Laravel version be supported?Apr 27, 2025 am 12:17 AM

ThepreviousversionofLaravelissupportedwithbugfixesforsixmonthsandsecurityfixesforoneyearafteranewmajorversion'srelease.Understandingthissupporttimelineiscrucialforplanningupgrades,ensuringprojectstability,andleveragingnewfeaturesandsecurityenhancemen

Leveraging Laravel's Features for Both Frontend and Backend DevelopmentLeveraging Laravel's Features for Both Frontend and Backend DevelopmentApr 27, 2025 am 12:16 AM

Laravelcanbeeffectivelyusedforbothfrontendandbackenddevelopment.1)Backend:UtilizeLaravel'sEloquentORMforsimplifieddatabaseinteractions.2)Frontend:LeverageBladetemplatesforcleanHTMLandintegrateVue.jsfordynamicSPAs,ensuringseamlessfrontend-backendinteg

Can Laravel be used for Full Stack Development (Frontend   Backend)?Can Laravel be used for Full Stack Development (Frontend Backend)?Apr 27, 2025 am 12:10 AM

Laravelcanbeusedforfullstackdevelopment.1)BackendmasterywithLaravel'sexpressivesyntaxandfeatureslikeEloquentORMfordatabasemanagement.2)FrontendintegrationusingBladefordynamicHTMLtemplates.3)EnhancingfrontendwithLaravelMixforassetcompilation.4)Fullsta

What tools help with upgrading to the latest Laravel version?What tools help with upgrading to the latest Laravel version?Apr 27, 2025 am 12:02 AM

Answer: The best tools for upgrading Laravel include Laravel's UpgradeGuide, LaravelShift, Rector, Composer, and LaravelPint. 1. Use Laravel's UpgradeGuide as the upgrade roadmap. 2. Use LaravelShift to automate most of the upgrade work, but it requires manual review. 3. Automatically refactor the code through Rector, and you need to understand and possibly customize its rules. 4. Use Composer to manage dependencies and pay attention to possible dependency conflicts. 5. Run LaravelPint to maintain code style consistency, but it does not solve the functional problems.

Beyond the Zoom Call: Creative Strategies for Connecting Distributed TeamsBeyond the Zoom Call: Creative Strategies for Connecting Distributed TeamsApr 26, 2025 am 12:24 AM

ToenhanceengagementandcohesionamongdistributedteamsbeyondZoom,implementthesestrategies:1)Organizevirtualcoffeebreaksforinformalchats,2)UseasynchronoustoolslikeSlackfornon-workdiscussions,3)Introducegamificationwithteamgamesorchallenges,and4)Encourage

What are the breaking changes in the latest Laravel version?What are the breaking changes in the latest Laravel version?Apr 26, 2025 am 12:23 AM

Laravel10introducesseveralbreakingchanges:1)ItrequiresPHP8.1orhigher,2)TheRouteServiceProvidernowusesabootmethodforloadingroutes,3)ThewithTimestamps()methodonEloquentrelationshipsisdeprecated,and4)TheRequestclassnowpreferstherules()methodforvalidatio

The Productivity Paradox: Maintaining Focus and Motivation in Remote SettingsThe Productivity Paradox: Maintaining Focus and Motivation in Remote SettingsApr 26, 2025 am 12:17 AM

Tomaintainfocusandmotivationinremotework,createastructuredenvironment,managedigitaldistractions,fostermotivationthroughsocialinteractionsandgoalsetting,maintainwork-lifebalance,anduseappropriatetechnology.1)Setupadedicatedworkspaceandsticktoaroutine.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use