考虑以下任务:
<?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.log
和tweets.log
文件都有我打印到tweets.log
的内容。
这是为什么?如何将 ONLY 打印到tweets.log?
答案 0 :(得分:1)
pushHandler()不会替换现有的日志处理程序。相反,它会向现有的预定义处理程序列表添加一个新的日志处理程序。这就是为什么现在让你的消息记录在2个日志文件中的原因。
您需要调用 setHandlers()来覆盖处理程序列表:
$handler = new StreamHandler(storage_path('logs/tweets.log'), Logger::INFO);
$logInstance = Log::getMonolog();
$logInstance->setHandlers(array($handler));