Search code examples
phplaravellaravel-5.1monolog

Disable Log::info in production using Laravel


I assumed that by default the Log::info calls wouldn't log in production, but they are still coming in.

Im setting production using my .env file

APP_ENV=production
APP_DEBUG=false

Ive tried these commands as well, but no luck

composer dump-autoload
php artisan cache:clear
php artisan optimize

Am i missing something?


Solution

  • Well, I think that it's too late to search for all the Log::info() and do the proposed answer by @jon__o

    if (App::environment('local', 'staging')) {
        Log::info($error);
    }
    

    But you can still do something. You can override the default Laravel logger instance with your own implementation.

    Go to your ApplicationServiceProvider and override the log instance with a custom one:

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        $this->registerLogger();
    }
    
    /**
     * Register the logger instance in the container.
     *
     * @return MyCustomWriter
     */
    protected function registerLogger()
    {
        $this->app->instance('log', $log = new MyCustomWriter(
            new Monolog($this->app->environment()), $app['events'])
        );
    
        $log->dontLogInfoOnEnvironmnets(['production', 'staging', 'other']);
        return $log;
    }
    

    Now you can create your custom writer by just extending the Laravel's Writer and overriding the info() method.

    class MyCustomWriter extends \Illuminate\Log\Writer
    {
    
        protected $dontInfoOn = [];
    
        /**
         * Log an informational message to the logs.
         *
         * @param  string  $message
         * @param  array  $context
         * @return void
         */
        public function info($message, array $context = [])
        {
            // Since we are providing the app environment to the Monolog instance in out ApplicationServiceProvider
            // we can get the environment from the Monolog getName() method
            if(!in_array($this->monolog->getName(), $this->dontInfoOn)) {
                return parent::info($message, $context);
            }
        }
    
        /**
         * Don't log info() on the supplied environments .
         *
         * @param  array  $environments
         * @return void
         */
        public function dontLogInfoOnEnvironmnets(array $environments)
        {
            $this->dontInfoOn = $environments;
        }
    }
    

    This way, you can still keep you Log::info on testing environments without checking every time.