Ad

Why Is It Going To Both Laravel.log And Tweets.log?

Consider the following task:

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Foundation\Inspiring;
use App\Etis\Domain\Services\TwitterService;
use \Twitter;
use Log;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;

class FetchTweets extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'fetch_tweets';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'fetches the latest ten tweets';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {

        $logInstance = Log::getMonolog();
        $logInstance->pushHandler(new StreamHandler(storage_path('logs/tweets.log'), Logger::INFO));

        $tweets = Twitter::getUserTimeline([
            'screen_name' => env('TWITTER_USER_NAME'),
            'count'       => env('TWITTER_TWEET_AMOUNT'),
            'format'      => 'json'
        ]);

        $logInstance->addInfo('Tweets', [$tweets]);

        $twitterService = new TwitterService();
        $twitterService->processTweets(json_decode($tweets, true));
    }
}

Which is then set up as such:

    $schedule->command('fetch_tweets')
        ->everyMinute()
        ->withoutOverlapping()
        ->appendOutputTo('storage/logs/tweets.log');

When I look, on production and even in local, I see that both the laravel.log and the tweets.log file have the contents that I printing out to tweets.log.

Why is this? How do I make it ONLY print out to tweets.log?

Ad

Answer

pushHandler() does not replace existing log handler. Instead, it adds a new log handler to the existing, predefined list of handlers. That's the reason why you're now getting your message logged in 2 log files now.

You need to call setHandlers() to overwrite the list of handlers:

$handler = new StreamHandler(storage_path('logs/tweets.log'), Logger::INFO);
$logInstance = Log::getMonolog();
$logInstance->setHandlers(array($handler));
Ad
source: stackoverflow.com
Ad