为什么它会同时到达 laravel.log 和 tweets.log?

Why is it going to both laravel.log and tweets.log?

考虑以下任务:

<?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));
    }
}

然后这样设置:

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

当我查看生产环境甚至本地环境时,我看到 laravel.logtweets.log 文件都有我打印到 tweets.log 的内容。

这是为什么?我如何让它 ONLY 打印到 tweets.log?

pushHandler() 不会替换现有的日志处理程序。相反,它将一个新的日志处理程序添加到现有的预定义处理程序列表中。这就是为什么您现在将消息记录在 2 个日志文件中的原因。

您需要调用 setHandlers() 来覆盖处理程序列表:

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