Extending Laravel core logging

后端 未结 2 650
闹比i
闹比i 2021-02-03 16:03

I\'m back with more Laravel problems as I\'m having a problem understanding things.

Again, I\'m attempting to create a package to do my own logging. After doing some ext

2条回答
  •  逝去的感伤
    2021-02-03 16:25

    Why are you using the Boot method in the service provider?

    Replacing Laravel's log

    You may have meant to use the register method instead of the boot method in that service provider?

    It looks like your implementation of this will override the default logger, rather than create an additional log. Is that your intention? In that case, note that you have used the boot method to register an instance of "log", but then the register method is re-doing that work. (perhaps replacing it back with the default? I'm not sure what behavior would result).

    An additional log

    If you want to add an additional log, you can do that without having to extend Laravel's service provider.

    Within a new file and your own namespace, create a LogServiceProvider:

    app['events']);
    
            $logFile = 'my-custom-log.txt';
    
            $logger->useDailyFiles(storage_path().'/logs/'.$logFile);
    
            $this->app->instance('fideloper.log', $logger);
    
            $this->app->bind('Fideloper\Log\Writer', function($app)
            {
                return $app->make('fideloper.log');
            });
        }
    
        /**
         * Get the services provided by the provider.
         *
         * @return array
         */
        public function provides()
        {
            return array('fideloper.log');
        }
    
    }
    

    Then create a new log writer (similar to how you've done):

    Note that I didn't add any extra functionality to my extended writer class, but I could.

    A con of this setup is that I haven't created or over-written the Log facade to use my new logger. Any call to Log::whatever() will still go to Laravel's default. I create a new Fideloper\Log\Writer object and it works because of Laravel's ability to provide class dependencies automatically.

    $log = App::make('fideloper.log');
    
    // Or get auto-created by laravel by making it a dependency
    //   in a controller, for example:
    log = $log;
    
            //Later
            $this->log->error('SOME CUSTOM ERROR');
        }
    
    }
    

提交回复
热议问题