3
declare(strict_types=1);
6
* This file is part of CodeIgniter 4 framework.
8
* (c) CodeIgniter Foundation <admin@codeigniter.com>
10
* For the full copyright and license information, please view
11
* the LICENSE file that was distributed with this source code.
14
namespace CodeIgniter\Log\Handlers;
20
* Log error messages to file system
22
* @see \CodeIgniter\Log\Handlers\FileHandlerTest
24
class FileHandler extends BaseHandler
34
* Extension to use for log files
38
protected $fileExtension;
41
* Permissions for new log files
45
protected $filePermissions;
50
public function __construct(array $config = [])
52
parent::__construct($config);
54
$this->path = empty($config['path']) ? WRITEPATH . 'logs/' : $config['path'];
56
$this->fileExtension = empty($config['fileExtension']) ? 'log' : $config['fileExtension'];
57
$this->fileExtension = ltrim($this->fileExtension, '.');
59
$this->filePermissions = $config['filePermissions'] ?? 0644;
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
68
* @param string $level
69
* @param string $message
73
public function handle($level, $message): bool
75
$filepath = $this->path . 'log-' . date('Y-m-d') . '.' . $this->fileExtension;
79
if (! is_file($filepath)) {
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";
88
if (! $fp = @fopen($filepath, 'ab')) {
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);
99
$date = date($this->dateFormat);
102
$msg .= strtoupper($level) . ' - ' . $date . ' --> ' . $message . "\n";
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
113
// @codeCoverageIgnoreEnd
120
if (isset($newfile) && $newfile === true) {
121
chmod($filepath, $this->filePermissions);
124
return is_int($result);