在PHP的Laravel中,如何清除laravel.log?

In PHP's Laravel, how do I clear laravel.log?

我是 Laravel 和 PHP 的新手,我正在尝试清除我的错误日志。我正在使用的当前错误日志是 Laravel 的 laravel.log 文件,它位于 /app/storage/logs 中。

有清除laravel.log文件的简便方法吗?删除它是否安全,它会在需要时重建?

我使用的是最新版本的 Ubuntu。谢谢!

向它回显一个空字符串就可以了,就像这样:

echo "" > storage/logs/laravel.log

most efficienttruncate 大小为零:

truncate -s 0 /app/storage/logs/laravel.log

这对我有用:

echo "" > storage/logs/laravel.log

对于Laravel 5,它将是

truncate -s 0 storage/logs/laravel.log

您还可以这样做:: > storage/logs/laravel.log

只需在要清除日志的地方添加这一行即可。 file_put_contents(storage_path('logs/laravel.log'),'');

对我来说最简单的方法是使用 vim。

$ vim laravel.log

Then type ggdG

Then :wq save and quit.

备注: gg - 将光标移动到第一行

d - 删除

G - 到文件末尾

这是一个可重复使用的 artisan 命令,可以节省您的时间和精力:)

Artisan::command('logs:clear', function() {
    
    exec('rm -f ' . storage_path('logs/*.log'));

    exec('rm -f ' . base_path('*.log'));
    
    $this->comment('Logs have been cleared!');
    
})->describe('Clear log files');

将其放入 routes/console.php 然后 运行 php artisan logs:clear


更新:

  • 在根目录中为 npmcomposer 等日志添加了 base_path('*.log')
  • 已将 -f 添加到 rm 函数以抑制 No such file or directory 消息。

您还可以创建自定义 artisan 命令。

首先,运行命令php artisan make:command Log/ClearLogFile创建自定义命令文件。

然后,在Console/Commands/Log/ClearLogFile.php上打开文件(取决于你的Laravel版本,目前我使用的是5.5版本)

之后需要定义自定义命令代码,看一下

// Define command name
protected $signature = 'log:clear';

// Add description to your command
protected $description = 'Clear Laravel log';

// Create your own custom command
public function handle(){
    exec('echo "" > ' . storage_path('logs/laravel.log'));
    $this->info('Logs have been cleared');
}

然后,你只需要运行就像其他phpartisan命令一样,

php artisan log:clear

感谢@emotality answer

来自您的 Laravel 目录:

rm storage/logs/laravel-*.log

当我是 运行 SQL 查询侦听器时,我通常会在我的控制器方法中添加以下行:

exec("truncate -s 0 " . storage_path('/logs/laravel.log'));

如果您使用不同的 monolog 通道设置,您可能需要调整日志文件的名称。

我发现此解决方案适用于 windows

Artisan::command('logs:clear', function() {
   array_map('unlink', array_filter((array) glob(storage_path('logs/*.log'))));
   $this->comment('Logs have been cleared!');
})->describe('Clear log files');

运行 php artisan logs:clear

使用Laravel More Command Package.

使用php artisan log:clear 命令清除日志的方法非常简单

首先安装Laravel更多命令

composer require theanik/laravel-more-command --dev

然后运行

php artisan log:clear

以上将从 /storage/logs/ 目录中删除所有旧日志数据。

谢谢。