-
Notifications
You must be signed in to change notification settings - Fork 1
/
FileLogger.php
365 lines (300 loc) · 9.51 KB
/
FileLogger.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
<?php
/**
* Created by PhpStorm.
* User: koco
* Date: 3/29/18
* Time: 12:39 PM
*/
namespace apollo11\fileLogger;
class FileLogger
{
//log file creation types
const FILE_CREATE_TYPE_BY_TIME = 1;
const FILE_CREATE_TYPE_BY_SIZE = 2;
//latest log count to save
// bool/integer
public $saveLatestFileNumber = 100;
//Force create directory if directory does not exist
//Throws error if directory path was given by mistake
public $forceCreateDirectory = false;
//color option for log text
public $enableColors = false;
//log file creation type property
public $fileCreateType = self::FILE_CREATE_TYPE_BY_TIME;
//Log file recreation units
public $fileReCreateMinutes = 0;
public $fileReCreateHours = 0;
public $fileReCreateDays = 1; // New file will be created every day
public $fileReCreateMonths = 0;
public $fileReCreateYears = 0;
//Log file recreation size
public $fileReCreateSize = 1 * 1024 * 1024; //1MB
// Log file attributes
public $logFilePath;
public $logFileName = 'example.log';
public $logFileDateFormat = "Ymd";
public $logFileTemplate = "{date}_{fileName}";
// Log text attributes
public $logTextDateFormat = "Y-m-d H:i:s";
public $logTextTemplate = '[ {date} ] - [ {type} ] - {message}' . PHP_EOL;
/**
* CliLogger constructor.
* @param $config
*/
public function __construct($config)
{
if (!empty($config)) {
$this->configure($this, $config);
}
$this->logFilePath = rtrim($this->logFilePath, '/');
}
/**
* Log message
*
* Log message with color parameters in log file
*
* @param $message
* @param string $fColor
* @param null $bColor
* @param string $type
* @return string
* @throws \Exception
*/
public function log($message, $fColor = FileColor::F_WHITE, $bColor = null, $type = 'LOG')
{
return $this->writeLog($this->processLogTextTemplate($message, $type), $fColor, $bColor);
}
/**
* Log error
*
* @param $message
* @param string $type
* @return string
* @throws \Exception
*/
public function error($message, $type = 'ERROR')
{
return $this->writeLog($this->processLogTextTemplate($message, $type), FileColor::F_RED);
}
/**
* Log info
*
* @param $message
* @param string $type
* @return string
* @throws \Exception
*/
public function info($message, $type = 'INFO')
{
return $this->writeLog($this->processLogTextTemplate($message, $type), FileColor::F_LIGHT_BLUE);
}
/**
* Log success
*
* @param $message
* @param string $type
* @return string
* @throws \Exception
*/
public function success($message, $type = 'SUCCESS')
{
return $this->writeLog($this->processLogTextTemplate($message, $type), FileColor::F_LIGHT_GREEN);
}
/**
* Log write
*
* Write log message with given type and text color parameters in log file
*
* @param $message
* @param $fColor
* @param null $bColor
* @return string
* @throws \Exception
*/
private function writeLog($message, $fColor, $bColor = null)
{
if (!file_exists($this->logFilePath)) {
if ($this->forceCreateDirectory) {
$this->rmkdir($this->logFilePath);
} else {
throw new \Exception(self::class . '::$logFilePath is invalid');
}
}
if ($this->enableColors === true) {
$message = FileColor::getColoredString($message, $fColor, $bColor);
}
$expiredLogFile = $this->checkFileCreation();
file_put_contents($this->logFilePath . '/' . $this->processFileTemplate($expiredLogFile), $message, FILE_APPEND);
if ($this->saveLatestFileNumber) {
/*check old logs and delete them*/
$this->deleteOldLogs();
}
return $message;
}
/**
* Constructor configuration
*
* Returns configuration object for constructor
*
* @param $object
* @param $properties
* @return mixed
*/
private function configure($object, $properties)
{
foreach ($properties as $name => $value) {
$object->$name = $value;
}
return $object;
}
/**
* Log file template
*
* Returns template for log file with chosen configuration
*
* @param $expiredLogFile
* @return bool|mixed|string
*/
private function processFileTemplate($expiredLogFile)
{
$parts = [
'{date}' => date($this->logFileDateFormat),
'{fileName}' => $this->logFileName
];
$fileName = strtr($this->logFileTemplate, $parts);
$latestFile = $this->getLatestLogFile();
if ($latestFile && $expiredLogFile === false) {
$fileName = $latestFile;
}
if ($expiredLogFile) {
$pathInfo = pathinfo($fileName);
if ($this->fileCreateType === self::FILE_CREATE_TYPE_BY_SIZE) {
if ($fileName === $expiredLogFile) {
$fileName = $expiredLogFile = $pathInfo['filename'] . '_' . time() . '.' . $pathInfo['extension'];
} else {
$expiredLogFile = false;
}
} else {
$expiredLogFile = false;
}
}
return $expiredLogFile ?: $fileName;
}
/**
* Log text template
*
* Returns template for log text with chosen configuration
* @param $message
* @param string $type
* @return string
*/
private function processLogTextTemplate($message, $type = 'LOG')
{
$parts = [
'{date}' => date($this->logTextDateFormat),
'{type}' => str_pad($type, 7, ' ', STR_PAD_RIGHT),
'{message}' => $message,
];
return strtr($this->logTextTemplate, $parts);
}
function deleteOldLogs()
{
if (is_dir($this->logFilePath)) {
$logFilePath = $this->logFilePath;
$logFileName = $this->logFileName;
$files = glob("$logFilePath/*.$logFileName");
$allFilesArray = [];
foreach ($files as $key => $file) {
$allFilesArray[$key]['time'] = filemtime($this->logFilePath . '/' . $file);
$allFilesArray[$key]['name'] = $file;
}
usort($allFilesArray, function ($a, $b) {
return $b['time'] - $a['time'];
});
if (count($allFilesArray) > $this->saveLatestFileNumber) {
for ($i = 0; $i < $this->saveLatestFileNumber; $i++) {
if ($allFilesArray[$i]['time'] >= date($this->logFileDateFormat)) {
unset($allFilesArray[$i]);
}
}
foreach ($allFilesArray as $deteFileNames) {
$file = $this->logFilePath . '/' . $deteFileNames['name'];
if (file_exists($file)) {
unlink($file);
echo 'Deleted file: Time:' . $deteFileNames['time'] . " Name: " . $deteFileNames['name'] . "<br>";
}
}
}
}
}
/**
* File creation check
*
* Function checks if log file was created according FILE_CREATE_TYPE option
*
* Returns log file name or boolean(false)
*
* @return bool|mixed
*/
private function checkFileCreation()
{
$logFileName = $this->getLatestLogFile();
$logFilePath = $this->logFilePath . '/' . $logFileName;
if ($this->fileCreateType === self::FILE_CREATE_TYPE_BY_SIZE) {
if (file_exists($logFilePath) && filesize($logFilePath) >= $this->filReCreateSize) {
return $logFileName;
}
} elseif ($this->fileCreateType === self::FILE_CREATE_TYPE_BY_TIME) {
$lasElementInDir = count(scandir($this->logFilePath));
$lastModifiedLogFileDate = strtotime(explode('_', scandir($this->logFilePath)[$lasElementInDir - 1])[0] . '+' . $this->fileReCreateDays . ' day');
if (file_exists($logFilePath) && strtotime(date($this->logFileDateFormat)) >= $lastModifiedLogFileDate) {
return $logFileName;
}
}
return false;
}
/**
* Get latest log
*
* Return latest log file from log directory
*
* @return bool|mixed
*/
private function getLatestLogFile()
{
$files = [];
if ($handle = opendir($this->logFilePath)) {
$filesArray = glob($this->logFilePath."/*{$this->logFileName}");
foreach ($filesArray as $file) {
if ($file != "." && $file != ".." && $file != ".gitignore") {
$files[filemtime($file)] = $file;
}
}
closedir($handle);
// sort
sort($files);
return basename(end($files));
}
return false;
}
/**
* @param $path
*/
private function rmkdir($path)
{
$path = str_replace("\\", "/", $path);
$path = explode("/", $path);
$rebuild = '';
foreach ($path AS $p) {
if (strstr($p, ":") != false) {
$rebuild = $p;
continue;
}
$rebuild .= "/$p";
if (!is_dir($rebuild)) mkdir($rebuild);
}
if ($rebuild) {
return true;
}
}
}