Home > Blockchain >  how to config for delete log file in yii2
how to config for delete log file in yii2

Time:10-08

i'm running a Yii2 application. After a few days, the logs have taken a lot of volume from us.

how to set config for delete log file every day ?

log file : runtime -> logs

the config  ;

        'log' => [
            'traceLevel' => 3,
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                ],
            ],
        ],

CodePudding user response:

You can create separate action in Controller.

Put code in any controller

public function actionCache()
{
    $r = Yii::$app->cache->flush();

    $cache = [
        '@frontend' => [
            'web' . DIRECTORY_SEPARATOR . 'assets',
            'runtime',
        ],
        '@backend' => [
            'web' . DIRECTORY_SEPARATOR . 'assets',
            'runtime',
        ],
        '@console' => [
            'runtime',
        ],
    ];


    foreach ($cache as $key => $c) {
        $path = Yii::getAlias($key) . DIRECTORY_SEPARATOR;
        foreach ($c as $dir_name) {
            $dir = $path . $dir_name;
            if ($handle = opendir($dir)) {
                while (false !== ($file = readdir($handle))) {
                    if ($file != "." && $file != ".." && $file != ".gitignore") {
                        self::deleteDirectory($dir . DIRECTORY_SEPARATOR . $file);
                    }
                }
                closedir($handle);
            }

        }
    }

    echo "<div align='center'><b>Cache successfully Deleted.</b><br><br><a href=\"" . Url::to(['site/index']) . "\">GO TO HOME</a></div>";
    die;
}

create one more static function in same controller

public static function  deleteDirectory($dir)
{

    if (!file_exists($dir)) {
        return true;
    }
    if (!is_dir($dir)) {
        return unlink($dir);
    }
    foreach (scandir($dir) as $item) {
        if ($item == '.' || $item == '..') {
            continue;
        }
        if (!self::deleteDirectory($dir . DIRECTORY_SEPARATOR . $item)) {
            return false;
        }
    }
    return rmdir($dir);
}

CodePudding user response:

Yii should rotate logs by default (you can change it using $enableRotation) and remove older logs automatically. You can adjust amount of logs using $maxFileSize and $maxLogFiles settings, by default it should be around 50-60 MB.

   'log' => [
        'traceLevel' => 3,
        'targets' => [
            [
                'class' => 'yii\log\FileTarget',
                'levels' => ['error', 'warning'],
                'maxFileSize' => 1024,
            ],
        ],
    ],
  • Related