Completed
Push — master ( 67caf0...bdc372 )
by Dmitry
13:07 queued 04:28
created

FileTarget   A

Complexity

Total Complexity 26

Size/Duplication

Total Lines 180
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 83.82%

Importance

Changes 0
Metric Value
wmc 26
lcom 1
cbo 5
dl 0
loc 180
ccs 57
cts 68
cp 0.8382
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A init() 0 15 4
D export() 0 45 10
B rotateFiles() 0 20 7
A clearLogFile() 0 7 2
A rotateByCopy() 0 7 2
A rotateByRename() 0 4 1
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\log;
9
10
use Yii;
11
use yii\base\InvalidConfigException;
12
use yii\helpers\FileHelper;
13
14
/**
15
 * FileTarget records log messages in a file.
16
 *
17
 * The log file is specified via [[logFile]]. If the size of the log file exceeds
18
 * [[maxFileSize]] (in kilo-bytes), a rotation will be performed, which renames
19
 * the current log file by suffixing the file name with '.1'. All existing log
20
 * files are moved backwards by one place, i.e., '.2' to '.3', '.1' to '.2', and so on.
21
 * The property [[maxLogFiles]] specifies how many history files to keep.
22
 *
23
 * @author Qiang Xue <[email protected]>
24
 * @since 2.0
25
 */
26
class FileTarget extends Target
27
{
28
    /**
29
     * @var string log file path or [path alias](guide:concept-aliases). If not set, it will use the "@runtime/logs/app.log" file.
30
     * The directory containing the log files will be automatically created if not existing.
31
     */
32
    public $logFile;
33
    /**
34
     * @var bool whether log files should be rotated when they reach a certain [[maxFileSize|maximum size]].
35
     * Log rotation is enabled by default. This property allows you to disable it, when you have configured
36
     * an external tools for log rotation on your server.
37
     * @since 2.0.3
38
     */
39
    public $enableRotation = true;
40
    /**
41
     * @var int maximum log file size, in kilo-bytes. Defaults to 10240, meaning 10MB.
42
     */
43
    public $maxFileSize = 10240; // in KB
44
    /**
45
     * @var int number of log files used for rotation. Defaults to 5.
46
     */
47
    public $maxLogFiles = 5;
48
    /**
49
     * @var int the permission to be set for newly created log files.
50
     * This value will be used by PHP chmod() function. No umask will be applied.
51
     * If not set, the permission will be determined by the current environment.
52
     */
53
    public $fileMode;
54
    /**
55
     * @var int the permission to be set for newly created directories.
56
     * This value will be used by PHP chmod() function. No umask will be applied.
57
     * Defaults to 0775, meaning the directory is read-writable by owner and group,
58
     * but read-only for other users.
59
     */
60
    public $dirMode = 0775;
61
    /**
62
     * @var bool Whether to rotate log files by copy and truncate in contrast to rotation by
63
     * renaming files. Defaults to `true` to be more compatible with log tailers and is windows
64
     * systems which do not play well with rename on open files. Rotation by renaming however is
65
     * a bit faster.
66
     *
67
     * The problem with windows systems where the [rename()](http://www.php.net/manual/en/function.rename.php)
68
     * function does not work with files that are opened by some process is described in a
69
     * [comment by Martin Pelletier](http://www.php.net/manual/en/function.rename.php#102274) in
70
     * the PHP documentation. By setting rotateByCopy to `true` you can work
71
     * around this problem.
72
     */
73
    public $rotateByCopy = true;
74
75
    /**
76
     * Initializes the route.
77
     * This method is invoked after the route is created by the route manager.
78
     */
79 3
    public function init()
80
    {
81 3
        parent::init();
82 3
        if ($this->logFile === null) {
83
            $this->logFile = Yii::$app->getRuntimePath() . '/logs/app.log';
84
        } else {
85 3
            $this->logFile = Yii::getAlias($this->logFile);
0 ignored issues
show
Documentation Bug introduced by
It seems like \Yii::getAlias($this->logFile) can also be of type boolean. However, the property $logFile is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
86
        }
87 3
        if ($this->maxLogFiles < 1) {
88
            $this->maxLogFiles = 1;
89
        }
90 3
        if ($this->maxFileSize < 1) {
91
            $this->maxFileSize = 1;
92
        }
93 3
    }
94
95
    /**
96
     * Writes log messages to a file.
97
     * Starting from version 2.0.14, this method throws LogRuntimeException in case the log can not be exported.
98
     * @throws InvalidConfigException if unable to open the log file for writing
99
     * @throws LogRuntimeException if unable to write complete log to file
100
     */
101 2
    public function export()
102
    {
103 2
        $logPath = dirname($this->logFile);
104 2
        FileHelper::createDirectory($logPath, $this->dirMode, true);
105
106 2
        $text = implode("\n", array_map([$this, 'formatMessage'], $this->messages)) . "\n";
107 2
        if (($fp = @fopen($this->logFile, 'a')) === false) {
108
            throw new InvalidConfigException("Unable to append to log file: {$this->logFile}");
109
        }
110 2
        @flock($fp, LOCK_EX);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
111 2
        if ($this->enableRotation) {
112
            // clear stat cache to ensure getting the real current file size and not a cached one
113
            // this may result in rotating twice when cached file size is used on subsequent calls
114 2
            clearstatcache();
115
        }
116 2
        if ($this->enableRotation && @filesize($this->logFile) > $this->maxFileSize * 1024) {
117 2
            $this->rotateFiles();
118 2
            @flock($fp, LOCK_UN);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
119 2
            @fclose($fp);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
120 2
            $writeResult = @file_put_contents($this->logFile, $text, FILE_APPEND | LOCK_EX);
121 2
            if ($writeResult === false) {
122
                $error = error_get_last();
123
                throw new LogRuntimeException("Unable to export log through file!: {$error['message']}");
124
            }
125 2
            $textSize = strlen($text);
126 2
            if ($writeResult < $textSize) {
127 2
                throw new LogRuntimeException("Unable to export whole log through file! Wrote $writeResult out of $textSize bytes.");
128
            }
129
        } else {
130 2
            $writeResult = @fwrite($fp, $text);
131 2
            if ($writeResult === false) {
132
                $error = error_get_last();
133
                throw new LogRuntimeException("Unable to export log through file!: {$error['message']}");
134
            }
135 2
            $textSize = strlen($text);
136 2
            if ($writeResult < $textSize) {
137
                throw new LogRuntimeException("Unable to export whole log through file! Wrote $writeResult out of $textSize bytes.");
138
            }
139 2
            @flock($fp, LOCK_UN);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
140 2
            @fclose($fp);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
141
        }
142 2
        if ($this->fileMode !== null) {
143
            @chmod($this->logFile, $this->fileMode);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
144
        }
145 2
    }
146
147
    /**
148
     * Rotates log files.
149
     */
150 2
    protected function rotateFiles()
151
    {
152 2
        $file = $this->logFile;
153 2
        for ($i = $this->maxLogFiles; $i >= 0; --$i) {
154
            // $i == 0 is the original log file
155 2
            $rotateFile = $file . ($i === 0 ? '' : '.' . $i);
156 2
            if (is_file($rotateFile)) {
157
                // suppress errors because it's possible multiple processes enter into this section
158 2
                if ($i === $this->maxLogFiles) {
159 2
                    @unlink($rotateFile);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
160 2
                    continue;
161
                }
162 2
                $newFile = $this->logFile . '.' . ($i + 1);
163 2
                $this->rotateByCopy ? $this->rotateByCopy($rotateFile, $newFile) : $this->rotateByRename($rotateFile, $newFile);
164 2
                if ($i === 0) {
165 2
                    $this->clearLogFile($rotateFile);
166
                }
167
            }
168
        }
169 2
    }
170
171
    /***
172
     * Clear log file without closing any other process open handles
173
     * @param string $rotateFile
174
     */
175 2
    private function clearLogFile($rotateFile)
176
    {
177 2
        if ($filePointer = @fopen($rotateFile, 'a')) {
178 2
            @ftruncate($filePointer, 0);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
179 2
            @fclose($filePointer);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
180
        }
181 2
    }
182
183
    /***
184
     * Copy rotated file into new file
185
     * @param string $rotateFile
186
     * @param string $newFile
187
     */
188 1
    private function rotateByCopy($rotateFile, $newFile)
189
    {
190 1
        @copy($rotateFile, $newFile);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
191 1
        if ($this->fileMode !== null) {
192
            @chmod($newFile, $this->fileMode);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
193
        }
194 1
    }
195
196
    /**
197
     * Renames rotated file into new file
198
     * @param string $rotateFile
199
     * @param string $newFile
200
     */
201 1
    private function rotateByRename($rotateFile, $newFile)
202
    {
203 1
        @rename($rotateFile, $newFile);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
204 1
    }
205
}
206