Search code examples
phplaravelloggingslack

Disable Laravel Slack Logging When Configured URL Is Null


Here's the configuration for my Slack logging channel:

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

When LOG_SLACK_WEBHOOK_URL is not set in the .env, I would like the channel to not be used. How do I accomplish that?

Currently if I leave LOG_SLACK_WEBHOOK_URL unset, I get this exception:

TypeError: Monolog\Handler\SlackWebhookHandler::__construct(): Argument #1 ($webhookUrl) must be of type string, null given, called in...


Solution

  • Typically, to use multiple logging channels (single file, daily file, slack notifications, etc.) in a Laravel Application, you use the stack driver:

    In config/logging.php:

    <?php
    
    return [
      'default' => env('LOG_CHANNEL', 'stack'),
      // ...
      'stack' => [
        'driver' => 'stack',
        'channels' => ['single'],
        'ignore_exceptions' => false
      ],
    ];
    

    By default, only a single channel is provided. If you want to use multiple channels based on a condition, you can use an in-line ternary:

    'channels' => ['single', env('LOG_SLACK_WEBHOOK_URL') ? 'slack' : null],
    // OR
    'channels' => env('LOG_SLACK_WEBHOOK_URL') ? ['single', 'slack'] : ['single'],
    

    In this situation, the slack channel will only be included if the LOG_SLACK_WEBHOOK_URL is set in your .env file, otherwise only the single channel (single laravel.log file) will be used.