本文目录导读:

在Laravel中,有几种方式可以处理任务调度的输出重定向:
使用 ->output() 方法
// app/Console/Kernel.php
protected function schedule(Schedule $schedule)
{
// 输出到文件(覆盖模式)
$schedule->command('email:send')
->daily()
->output(storage_path('logs/email-send.log'));
// 输出到文件(追加模式)
$schedule->command('email:send')
->daily()
->appendOutputTo(storage_path('logs/email-send.log'));
}
输出到多个目标
$schedule->command('report:generate')
->daily()
->output(storage_path('logs/report.log'))
->emailOutputTo('admin@example.com');
使用 exec() 方法
// 使用系统命令执行并重定向
$schedule->exec('php artisan task:run > /dev/null 2>&1')
->daily();
// 追加到日志
$schedule->exec('php artisan task:run >> ' . storage_path('logs/task.log') . ' 2>&1')
->daily();
自定义输出处理
// 使用闭包处理输出
$schedule->command('task:run')
->daily()
->output(function ($output, $command) {
// 处理输出内容
Log::info('Task completed: ' . $output);
// 或者发送到其他系统
// Notification::route('mail', 'admin@example.com')
// ->notify(new TaskCompleted($output));
});
处理多个命令的输出
$schedule->command('task:run')
->daily()
->output(storage_path('logs/task.log'))
->emailOutputTo(['admin@example.com', 'manager@example.com'], '任务执行报告')
->evenInMaintenanceMode();
日志文件管理
use Illuminate\Support\Facades\Storage;
protected function schedule(Schedule $schedule)
{
// 定期清理旧日志
$schedule->call(function () {
$logs = glob(storage_path('logs/*.log'));
$now = now()->subDays(7);
foreach ($logs as $log) {
if (filemtime($log) < $now->timestamp) {
unlink($log);
}
}
})->weekly();
}
完整示例
protected function schedule(Schedule $schedule)
{
// 1. 基础用法
$schedule->command('report:generate')
->dailyAt('02:00')
->timezone('Asia/Shanghai')
->output(storage_path('logs/report-' . now()->format('Y-m-d') . '.log'));
// 2. 同时输出到文件和邮件
$schedule->command('data:sync')
->hourly()
->appendOutputTo(storage_path('logs/data-sync.log'))
->emailOutputTo('admin@example.com');
// 3. 忽略输出(如果不需要)
$schedule->command('cache:clear')
->daily()
->output('/dev/null')
->withoutOverlapping();
// 4. 错误处理和输出
$schedule->command('import:data')
->daily()
->output(storage_path('logs/import.log'))
->onFailure(function () {
// 失败时的处理
Log::error('Import failed');
})
->onSuccess(function () {
// 成功时的处理
Log::info('Import completed successfully');
});
}
输出文件按日期分割
protected function schedule(Schedule $schedule)
{
$dailyLog = storage_path('logs/task-' . now()->format('Y-m-d') . '.log');
$schedule->command('task:run')
->daily()
->appendOutputTo($dailyLog);
}
注意事项
- 权限问题:确保日志目录可写
- 文件大小:定期清理过大的日志文件
- 性能:对于频繁执行的任务,考虑使用追加模式而不是覆盖模式
- 错误处理:配置
onFailure()和onSuccess()回调来处理执行结果
这些方法可以灵活组合使用,根据你的具体需求选择合适的输出重定向方式。