Search code examples
logginglaravelmonologservice-provider

How to log message while registering a ServiceProvide in Laravel?


So I have a Laravel service provider and I would like to create a DEBUG log entry when it is applied:

<?php

use Illuminate\Support\ServiceProvider;

class MyServiceProvider extends ServiceProvider
{
    public function register() {
        Log::debug('message'); //fails, Log facade alias isn't available yet
        $this->app['log']->debug('message'); //fails too
    }
}

How can this be done?


Solution

  • In laravel, service providers is defined in app/config/app.php

    It will fail if MyServiceProvider present early before LogServiceProvider, because LogServiceProvider has not registered yet. on the opposite side, If MyServiceProvider show later, It's exactly the answer you want.

    For more details, ProviderRepository have responsibility for register the application service providers.

    <?php
    return array(
        'providers' => array(
            'Illuminate\Foundation\Providers\ArtisanServiceProvider',
            'Illuminate\Auth\AuthServiceProvider',
            'Illuminate\Cache\CacheServiceProvider',
            'Illuminate\Session\CommandsServiceProvider',
            'Illuminate\Foundation\Providers\ConsoleSupportServiceProvider',
            'Illuminate\Routing\ControllerServiceProvider',
            'Illuminate\Cookie\CookieServiceProvider',
            'Illuminate\Database\DatabaseServiceProvider',
            'Illuminate\Encryption\EncryptionServiceProvider',
            'Illuminate\Filesystem\FilesystemServiceProvider',
            'Illuminate\Hashing\HashServiceProvider',
            'Illuminate\Html\HtmlServiceProvider',
            'Illuminate\Log\LogServiceProvider', // Log facade is registered here.
            'Illuminate\Mail\MailServiceProvider',
            'Illuminate\Database\MigrationServiceProvider',
            'Illuminate\Pagination\PaginationServiceProvider',
            'Illuminate\Queue\QueueServiceProvider',
            'Illuminate\Redis\RedisServiceProvider',
            'Illuminate\Remote\RemoteServiceProvider',
            'Illuminate\Auth\Reminders\ReminderServiceProvider',
            'Illuminate\Database\SeedServiceProvider',
            'Illuminate\Session\SessionServiceProvider',
            'Illuminate\Translation\TranslationServiceProvider',
            'Illuminate\Validation\ValidationServiceProvider',
            'Illuminate\View\ViewServiceProvider',
            'Illuminate\Workbench\WorkbenchServiceProvider',
            'MyServiceProvider', // You have to put this after LogServiceProvider.
        )
    );