1 <?php
2
3 if (!defined('GEN_START')) {
4 http_response_code(404);
5 die();
6 } elseif (!defined('LOG_LEVEL') || !defined('LOG_LEVEL_ERROR') || !defined('LOG_LEVEL_DEBUG') || !defined('LOG_LEVEL_NONE') || !in_array(LOG_LEVEL, [
7 LOG_LEVEL_ERROR,
8 LOG_LEVEL_DEBUG,
9 LOG_LEVEL_NONE
10 ], true)
11 ) {
12 die('Invalid LOG_LEVEL setting. Valid values are the framework constants LOG_LEVEL_ERROR, LOG_LEVEL_DEBUG and LOG_LEVEL_NONE!');
13 }
14
15 16 17 18 19
20 abstract class Log {
21
22 23 24 25 26
27 const MSG_ERROR = 'ERROR';
28
29 30 31 32 33
34 const MSG_DEBUG = 'DEBUG';
35
36 37 38 39 40
41 protected static $log_level = LOG_LEVEL;
42
43 44 45 46 47
48 protected static $today;
49
50 51 52 53 54 55 56 57 58 59
60 static function log_level($level = null) {
61 if (in_array($level, [
62 LOG_LEVEL_DEBUG,
63 LOG_LEVEL_ERROR,
64 LOG_LEVEL_NONE
65 ], true)) {
66 self::$log_level = $level;
67
68 return true;
69 } else {
70 return self::$log_level;
71 }
72 }
73
74 75 76 77 78 79 80 81
82 static function debug($msg, $trace = null) {
83 if (self::$log_level === LOG_LEVEL_DEBUG && is_scalar($msg)) {
84 self::do_write($msg, self::MSG_DEBUG, $trace);
85 }
86
87 return $msg;
88 }
89
90 91 92 93 94 95 96 97
98 static function error($msg, $trace = null) {
99 if (self::$log_level != LOG_LEVEL_NONE && is_scalar($msg)) {
100 self::do_write($msg, self::MSG_ERROR, $trace);
101 }
102
103 return $msg;
104 }
105
106 107 108 109 110 111 112 113 114
115 protected static function do_write($msg, $level, $trace = null) {
116 $filepath = DIR_APP . 'logs' . DIRECTORY_SEPARATOR . date('Y-m-d') . '.log';
117 $fp = @fopen($filepath, 'ab');
118
119 if (!$fp) {
120 return false;
121 } else {
122 if (!$trace || !is_array($trace)) {
123 $trace = debug_backtrace();
124 array_shift($trace);
125 }
126
127 if (defined('LOG_INTENSE') && LOG_INTENSE) {
128 $trace_append = serialize($trace);
129 } else {
130 $xpl = explode(DIR_INDEX, isset($trace[0]['file']) ? $trace[0]['file'] : null);
131
132 $trace_append = (isset($trace[0]['line']) ? $trace[0]['line'] : '[unknown line]') . ' @ "'
133 . str_replace('"', '\"', isset($xpl[1]) ? $xpl[1] : $xpl[0]) . '"';
134 }
135
136 $message = str_pad('[' . timestamp_precise() . ']', 25, ' ')
137 . ' ' . str_pad($level, 5, ' ') . ' | "'
138 . str_replace('"', '\"', $msg) . '" | ' . $trace_append . PHP_EOL;
139
140 flock($fp, LOCK_EX);
141 fwrite($fp, $message);
142 flock($fp, LOCK_UN);
143 fclose($fp);
144
145 @chmod($filepath, '0666');
146
147 return true;
148 }
149 }
150
151 }