ci4

Форк
0
/
FileHandler.php 
126 строк · 3.3 Кб
1
<?php
2

3
declare(strict_types=1);
4

5
/**
6
 * This file is part of CodeIgniter 4 framework.
7
 *
8
 * (c) CodeIgniter Foundation <admin@codeigniter.com>
9
 *
10
 * For the full copyright and license information, please view
11
 * the LICENSE file that was distributed with this source code.
12
 */
13

14
namespace CodeIgniter\Log\Handlers;
15

16
use DateTime;
17
use Exception;
18

19
/**
20
 * Log error messages to file system
21
 *
22
 * @see \CodeIgniter\Log\Handlers\FileHandlerTest
23
 */
24
class FileHandler extends BaseHandler
25
{
26
    /**
27
     * Folder to hold logs
28
     *
29
     * @var string
30
     */
31
    protected $path;
32

33
    /**
34
     * Extension to use for log files
35
     *
36
     * @var string
37
     */
38
    protected $fileExtension;
39

40
    /**
41
     * Permissions for new log files
42
     *
43
     * @var int
44
     */
45
    protected $filePermissions;
46

47
    /**
48
     * Constructor
49
     */
50
    public function __construct(array $config = [])
51
    {
52
        parent::__construct($config);
53

54
        $this->path = empty($config['path']) ? WRITEPATH . 'logs/' : $config['path'];
55

56
        $this->fileExtension = empty($config['fileExtension']) ? 'log' : $config['fileExtension'];
57
        $this->fileExtension = ltrim($this->fileExtension, '.');
58

59
        $this->filePermissions = $config['filePermissions'] ?? 0644;
60
    }
61

62
    /**
63
     * Handles logging the message.
64
     * If the handler returns false, then execution of handlers
65
     * will stop. Any handlers that have not run, yet, will not
66
     * be run.
67
     *
68
     * @param string $level
69
     * @param string $message
70
     *
71
     * @throws Exception
72
     */
73
    public function handle($level, $message): bool
74
    {
75
        $filepath = $this->path . 'log-' . date('Y-m-d') . '.' . $this->fileExtension;
76

77
        $msg = '';
78

79
        if (! is_file($filepath)) {
80
            $newfile = true;
81

82
            // Only add protection to php files
83
            if ($this->fileExtension === 'php') {
84
                $msg .= "<?php defined('SYSTEMPATH') || exit('No direct script access allowed'); ?>\n\n";
85
            }
86
        }
87

88
        if (! $fp = @fopen($filepath, 'ab')) {
89
            return false;
90
        }
91

92
        // Instantiating DateTime with microseconds appended to initial date is needed for proper support of this format
93
        if (str_contains($this->dateFormat, 'u')) {
94
            $microtimeFull  = microtime(true);
95
            $microtimeShort = sprintf('%06d', ($microtimeFull - floor($microtimeFull)) * 1_000_000);
96
            $date           = new DateTime(date('Y-m-d H:i:s.' . $microtimeShort, (int) $microtimeFull));
97
            $date           = $date->format($this->dateFormat);
98
        } else {
99
            $date = date($this->dateFormat);
100
        }
101

102
        $msg .= strtoupper($level) . ' - ' . $date . ' --> ' . $message . "\n";
103

104
        flock($fp, LOCK_EX);
105

106
        $result = null;
107

108
        for ($written = 0, $length = strlen($msg); $written < $length; $written += $result) {
109
            if (($result = fwrite($fp, substr($msg, $written))) === false) {
110
                // if we get this far, we'll never see this during travis-ci
111
                // @codeCoverageIgnoreStart
112
                break;
113
                // @codeCoverageIgnoreEnd
114
            }
115
        }
116

117
        flock($fp, LOCK_UN);
118
        fclose($fp);
119

120
        if (isset($newfile) && $newfile === true) {
121
            chmod($filepath, $this->filePermissions);
122
        }
123

124
        return is_int($result);
125
    }
126
}
127

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.