aboutsummaryrefslogtreecommitdiffstats
path: root/include/Logger.class.php
blob: 6b4172faaeb4d797695651d5a1e09cd093cb35c6 (plain)
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
<?php
// +-----------------------------------------------------------------------+
// | Piwigo - a PHP based photo gallery                                    |
// +-----------------------------------------------------------------------+
// | Copyright(C) 2008-2016 Piwigo Team          http://piwigo.org |
// | Copyright(C) 2003-2008 PhpWebGallery Team  http://phpwebgallery.net |
// | Copyright(C) 2002-2003 Pierrick LE GALL   http://le-gall.net/pierrick |
// +-----------------------------------------------------------------------+
// | This program is free software; you can redistribute it and/or modify  |
// | it under the terms of the GNU General Public License as published by  |
// | the Free Software Foundation                                          |
// |                                                                       |
// | This program is distributed in the hope that it will be useful, but   |
// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
// | General Public License for more details.                              |
// |                                                                       |
// | You should have received a copy of the GNU General Public License     |
// | along with this program; if not, write to the Free Software           |
// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
// | USA.                                                                  |
// +-----------------------------------------------------------------------+

/**
 * Modified version of KLogger 0.2.0
 *
 * @author  Kenny Katzgrau <katzgrau@gmail.com>
 *
 * @package logger
 */

class Logger
{
  /**
   * Error severity, from low to high. From BSD syslog RFC, section 4.1.1
   * @link http://www.faqs.org/rfcs/rfc3164.html
   */
  const EMERGENCY = 0;  // Emergency: system is unusable
  const ALERT     = 1;  // Alert: action must be taken immediately
  const CRITICAL  = 2;  // Critical: critical conditions
  const ERROR     = 3;  // Error: error conditions
  const WARNING   = 4;  // Warning: warning conditions
  const NOTICE    = 5;  // Notice: normal but significant condition
  const INFO      = 6;  // Informational: informational messages
  const DEBUG     = 7;  // Debug: debug messages

  /**
   * Custom "disable" level.
   */
  const OFF       = -1; // Log nothing at all

  /**
   * Internal status codes.
   */
  const STATUS_LOG_OPEN  = 1;
  const STATUS_OPEN_FAILED = 2;
  const STATUS_LOG_CLOSED  = 3;

  /**
   * Disable archive purge.
   */
  const ARCHIVE_NO_PURGE = -1;

  /**
   * Standard messages produced by the class.
   * @var array
   */
  private static $_messages = array(
    'writefail'   => 'The file could not be written to. Check that appropriate permissions have been set.',
    'opensuccess' => 'The log file was opened successfully.',
    'openfail'  => 'The file could not be opened. Check permissions.',
  );

  /**
   * Instance options.
   * @var array
   */
  private $options = array(
    'directory' => null, // Log files directory
    'filename' => null, // Path to the log file
    'globPattern' => 'log_*.txt', // Pattern to select all log files with glob()
    'severity' => self::DEBUG, // Current minimum logging threshold
    'dateFormat' => 'Y-m-d G:i:s', // Date format
    'archiveDays' => self::ARCHIVE_NO_PURGE, // Number of files to keep
    );

  /**
   * Current status of the logger.
   * @var integer
   */
  private $_logStatus = self::STATUS_LOG_CLOSED;
  /**
   * File handle for this instance's log file.
   * @var resource
   */
  private $_fileHandle = null;


  /**
   * Class constructor.
   *
   * @param array $options
   * @return void
   */
  public function __construct($options)
  {
    $this->options = array_merge($this->options, $options);
    
    if (is_string($this->options['severity']))
    {
      $this->options['severity'] = self::codeToLevel($this->options['severity']);
    }

    if ($this->options['severity'] === self::OFF)
    {
      return;
    }

    $this->options['directory'] = rtrim($this->options['directory'], '\\/') . DIRECTORY_SEPARATOR;

    if ($this->options['filename'] == null)
    {
      $this->options['filename'] = 'log_' . date('Y-m-d') . '.txt';
    }

    $this->options['filePath'] = $this->options['directory'] . $this->options['filename'];

    if ($this->options['archiveDays'] != self::ARCHIVE_NO_PURGE && rand() % 97 == 0)
    {
      $this->purge();
    }
  }
  
  /**
   * Open the log file if not already oppenned
   */
  private function open()
  {
    if ($this->status() == self::STATUS_LOG_CLOSED)
    {
      if (!file_exists($this->options['directory']))
      {
        mkgetdir($this->options['directory'], MKGETDIR_DEFAULT|MKGETDIR_PROTECT_HTACCESS);
      }

      if (file_exists($this->options['filePath']) && !is_writable($this->options['filePath']))
      {
        $this->_logStatus = self::STATUS_OPEN_FAILED;
        throw new RuntimeException(self::$_messages['writefail']);
        return;
      }

      if (($this->_fileHandle = fopen($this->options['filePath'], 'a')) != false)
      {
        $this->_logStatus = self::STATUS_LOG_OPEN;
      }
      else
      {
        $this->_logStatus = self::STATUS_OPEN_FAILED;
        throw new RuntimeException(self::$_messages['openfail']);
      }
    }
  }

  /**
   * Class destructor.
   */
  public function __destruct()
  {
    if ($this->_fileHandle)
    {
      fclose($this->_fileHandle);
    }
  }

  /**
   * Returns logger status.
   *
   * @return int
   */
  public function status()
  {
    return $this->_logStatus;
  }

  /**
   * Returns logger severity threshold.
   *
   * @return int
   */
  public function severity()
  {
    return $this->options['severity'];
  }

  /**
   * Writes a $line to the log with a severity level of DEBUG.
   *
   * @param string $line
   * @param string $cat
   * @param array $args
   */
  public function debug($line, $cat = null, $args = array())
  {
    $this->log(self::DEBUG, $line, $cat, $args);
  }

  /**
   * Writes a $line to the log with a severity level of INFO.
   *
   * @param string $line
   * @param string $cat
   * @param array $args
   */
  public function info($line, $cat = null, $args = array())
  {
    $this->log(self::INFO, $line, $cat, $args);
  }

  /**
   * Writes a $line to the log with a severity level of NOTICE.
   *
   * @param string $line
   * @param string $cat
   * @param array $args
   */
  public function notice($line, $cat = null, $args = array())
  {
    $this->log(self::NOTICE, $line, $cat, $args);
  }

  /**
   * Writes a $line to the log with a severity level of WARNING.
   *
   * @param string $line
   * @param string $cat
   * @param array $args
   */
  public function warn($line, $cat = null, $args = array())
  {
    $this->log(self::WARNING, $line, $cat, $args);
  }

  /**
   * Writes a $line to the log with a severity level of ERROR.
   *
   * @param string $line
   * @param string $cat
   * @param array $args
   */
  public function error($line, $cat = null, $args = array())
  {
    $this->log(self::ERROR, $line, $cat, $args);
  }

  /**
   * Writes a $line to the log with a severity level of ALERT.
   *
   * @param string $line
   * @param string $cat
   * @param array $args
   */
  public function alert($line, $cat = null, $args = array())
  {
    $this->log(self::ALERT, $line, $cat, $args);
  }

  /**
   * Writes a $line to the log with a severity level of CRITICAL.
   *
   * @param string $line
   * @param string $cat
   * @param array $args
   */
  public function critical($line, $cat = null, $args = array())
  {
    $this->log(self::CRITICAL, $line, $cat, $args);
  }

  /**
   * Writes a $line to the log with a severity level of EMERGENCY.
   *
   * @param string $line
   * @param string $cat
   * @param array $args
   */
  public function emergency($line, $cat = null, $args = array())
  {
    $this->log(self::EMERGENCY, $line, $cat, $args);
  }

  /**
   * Writes a $line to the log with the given severity.
   *
   * @param integer $severity
   * @param string $line
   * @param string $cat
   * @param array $args
   */
  public function log($severity, $message, $cat = null, $args = array())
  {
    if ($this->severity() >= $severity)
    {
      if (is_array($cat))
      {
        $args = $cat;
        $cat = null;
      }
      $line = $this->formatMessage($severity, $message, $cat, $args);
      $this->write($line);
    }
  }

  /**
   * Directly writes a line to the log without adding level and time.
   *
   * @param string $line
   */
  public function write($line)
  {
    $this->open();
    if ($this->status() == self::STATUS_LOG_OPEN)
    {
      if (fwrite($this->_fileHandle, $line) === false)
      {
        throw new RuntimeException(self::$_messages['writefail']);
      }
    }
  }

  /**
   * Purges files matching 'globPattern' older than 'archiveDays'.
   */
  public function purge()
  {
    $files = glob($this->options['directory'] . $this->options['globPattern']);
    $limit = time() - $this->options['archiveDays'] * 86400;

    foreach ($files as $file)
    {
      if (@filemtime($file) < $limit)
      {
        @unlink($file);
      }
    }
  }

  /**
   * Formats the message for logging.
   *
   * @param  string $level
   * @param  string $message
   * @param  array  $context
   * @return string
   */
  private function formatMessage($level, $message, $cat, $context)
  {
    if (!empty($context))
    {
      $message.= "\n" . $this->indent($this->contextToString($context));
    }
    $line = "[" . $this->getTimestamp() . "]\t[" . self::levelToCode($level) . "]\t";
    if ($cat != null)
    {
      $line.= "[" . $cat . "]\t";
    }
    return $line . $message . "\n";
  }

  /**
   * Gets the formatted Date/Time for the log entry.
   *
   * PHP DateTime is dumb, and you have to resort to trickery to get microseconds
   * to work correctly, so here it is.
   *
   * @return string
   */
  private function getTimestamp()
  {
    $originalTime = microtime(true);
    $micro = sprintf('%06d', ($originalTime - floor($originalTime)) * 1000000);
    $date = new DateTime(date('Y-m-d H:i:s.'.$micro, $originalTime));
    return $date->format($this->options['dateFormat']);
  }

  /**
   * Takes the given context and converts it to a string.
   *
   * @param  array $context
   * @return string
   */
  private function contextToString($context)
  {
    $export = '';
    foreach ($context as $key => $value)
    {
      $export.= $key . ': ';
      $export.= preg_replace(array(
        '/=>\s+([a-zA-Z])/im',
        '/array\(\s+\)/im',
        '/^  |\G  /m'
        ),
        array(
        '=> $1',
        'array()',
        '  '
        ),
        str_replace('array (', 'array(', var_export($value, true))
        );
      $export.= PHP_EOL;
    }
    return str_replace(array('\\\\', '\\\''), array('\\', '\''), rtrim($export));
  }

  /**
   * Indents the given string with the given indent.
   *
   * @param  string $string The string to indent
   * @param  string $indent What to use as the indent.
   * @return string
   */
  private function indent($string, $indent = '  ')
  {
    return $indent . str_replace("\n", "\n" . $indent, $string);
  }

  /**
   * Converts level constants to string name.
   *
   * @param int $level
   * @return string
   */
  static function levelToCode($level)
  {
    switch ($level)
    {
      case self::EMERGENCY:
        return 'EMERGENCY';
      case self::ALERT:
        return 'ALERT';
      case self::CRITICAL:
        return 'CRITICAL';
      case self::NOTICE:
        return 'NOTICE';
      case self::INFO:
        return 'INFO';
      case self::WARNING:
        return 'WARNING';
      case self::DEBUG:
        return 'DEBUG';
      case self::ERROR:
        return 'ERROR';
      default:
        throw new RuntimeException('Unknown severity level ' . $level);
    }
  }

  /**
   * Converts level names to constant.
   *
   * @param string $code
   * @return int
   */
  static function codeToLevel($code)
  {
    switch (strtoupper($code))
    {
      case 'EMERGENCY':
        return self::EMERGENCY;
      case 'ALERT':
        return self::ALERT;
      case 'CRITICAL':
        return self::CRITICAL;
      case 'NOTICE':
        return self::NOTICE;
      case 'INFO':
        return self::INFO;
      case 'WARNING':
        return self::WARNING;
      case 'DEBUG':
        return self::DEBUG;
      case 'ERROR':
        return self::ERROR;
      default:
        throw new RuntimeException('Unknown severity code ' . $code);
    }
  }
}
?>