1: <?php
2: /**
3: * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
4: * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
5: *
6: * Licensed under The MIT License
7: * For full copyright and license information, please see the LICENSE.txt
8: * Redistributions of files must retain the above copyright notice.
9: *
10: * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
11: * @link https://cakefoundation.org CakePHP(tm) Project
12: * @since 1.3.0
13: * @license https://opensource.org/licenses/mit-license.php MIT License
14: */
15: namespace Cake\Log\Engine;
16:
17: use Cake\Core\Configure;
18: use Cake\Utility\Text;
19:
20: /**
21: * File Storage stream for Logging. Writes logs to different files
22: * based on the level of log it is.
23: */
24: class FileLog extends BaseLog
25: {
26:
27: /**
28: * Default config for this class
29: *
30: * - `levels` string or array, levels the engine is interested in
31: * - `scopes` string or array, scopes the engine is interested in
32: * - `file` Log file name
33: * - `path` The path to save logs on.
34: * - `size` Used to implement basic log file rotation. If log file size
35: * reaches specified size the existing file is renamed by appending timestamp
36: * to filename and new log file is created. Can be integer bytes value or
37: * human readable string values like '10MB', '100KB' etc.
38: * - `rotate` Log files are rotated specified times before being removed.
39: * If value is 0, old versions are removed rather then rotated.
40: * - `mask` A mask is applied when log files are created. Left empty no chmod
41: * is made.
42: *
43: * @var array
44: */
45: protected $_defaultConfig = [
46: 'path' => null,
47: 'file' => null,
48: 'types' => null,
49: 'levels' => [],
50: 'scopes' => [],
51: 'rotate' => 10,
52: 'size' => 10485760, // 10MB
53: 'mask' => null,
54: ];
55:
56: /**
57: * Path to save log files on.
58: *
59: * @var string|null
60: */
61: protected $_path;
62:
63: /**
64: * The name of the file to save logs into.
65: *
66: * @var string|null
67: */
68: protected $_file;
69:
70: /**
71: * Max file size, used for log file rotation.
72: *
73: * @var int|null
74: */
75: protected $_size;
76:
77: /**
78: * Sets protected properties based on config provided
79: *
80: * @param array $config Configuration array
81: */
82: public function __construct(array $config = [])
83: {
84: parent::__construct($config);
85:
86: if (!empty($this->_config['path'])) {
87: $this->_path = $this->_config['path'];
88: }
89: if ($this->_path !== null &&
90: Configure::read('debug') &&
91: !is_dir($this->_path)
92: ) {
93: mkdir($this->_path, 0775, true);
94: }
95:
96: if (!empty($this->_config['file'])) {
97: $this->_file = $this->_config['file'];
98: if (substr($this->_file, -4) !== '.log') {
99: $this->_file .= '.log';
100: }
101: }
102:
103: if (!empty($this->_config['size'])) {
104: if (is_numeric($this->_config['size'])) {
105: $this->_size = (int)$this->_config['size'];
106: } else {
107: $this->_size = Text::parseFileSize($this->_config['size']);
108: }
109: }
110: }
111:
112: /**
113: * Implements writing to log files.
114: *
115: * @param string $level The severity level of the message being written.
116: * See Cake\Log\Log::$_levels for list of possible levels.
117: * @param string $message The message you want to log.
118: * @param array $context Additional information about the logged message
119: * @return bool success of write.
120: */
121: public function log($level, $message, array $context = [])
122: {
123: $message = $this->_format($message, $context);
124: $output = date('Y-m-d H:i:s') . ' ' . ucfirst($level) . ': ' . $message . "\n";
125: $filename = $this->_getFilename($level);
126: if ($this->_size) {
127: $this->_rotateFile($filename);
128: }
129:
130: $pathname = $this->_path . $filename;
131: $mask = $this->_config['mask'];
132: if (!$mask) {
133: return file_put_contents($pathname, $output, FILE_APPEND);
134: }
135:
136: $exists = file_exists($pathname);
137: $result = file_put_contents($pathname, $output, FILE_APPEND);
138: static $selfError = false;
139:
140: if (!$selfError && !$exists && !chmod($pathname, (int)$mask)) {
141: $selfError = true;
142: trigger_error(vsprintf(
143: 'Could not apply permission mask "%s" on log file "%s"',
144: [$mask, $pathname]
145: ), E_USER_WARNING);
146: $selfError = false;
147: }
148:
149: return $result;
150: }
151:
152: /**
153: * Get filename
154: *
155: * @param string $level The level of log.
156: * @return string File name
157: */
158: protected function _getFilename($level)
159: {
160: $debugTypes = ['notice', 'info', 'debug'];
161:
162: if ($this->_file) {
163: $filename = $this->_file;
164: } elseif ($level === 'error' || $level === 'warning') {
165: $filename = 'error.log';
166: } elseif (in_array($level, $debugTypes)) {
167: $filename = 'debug.log';
168: } else {
169: $filename = $level . '.log';
170: }
171:
172: return $filename;
173: }
174:
175: /**
176: * Rotate log file if size specified in config is reached.
177: * Also if `rotate` count is reached oldest file is removed.
178: *
179: * @param string $filename Log file name
180: * @return bool|null True if rotated successfully or false in case of error.
181: * Null if file doesn't need to be rotated.
182: */
183: protected function _rotateFile($filename)
184: {
185: $filePath = $this->_path . $filename;
186: clearstatcache(true, $filePath);
187:
188: if (!file_exists($filePath) ||
189: filesize($filePath) < $this->_size
190: ) {
191: return null;
192: }
193:
194: $rotate = $this->_config['rotate'];
195: if ($rotate === 0) {
196: $result = unlink($filePath);
197: } else {
198: $result = rename($filePath, $filePath . '.' . time());
199: }
200:
201: $files = glob($filePath . '.*');
202: if ($files) {
203: $filesToDelete = count($files) - $rotate;
204: while ($filesToDelete > 0) {
205: unlink(array_shift($files));
206: $filesToDelete--;
207: }
208: }
209:
210: return $result;
211: }
212: }
213: