1 <?php
2 3 4 5 6 7
8
9 namespace Hawk;
10
11 12 13 14 15 16
17 final class Logger extends Singleton{
18 const LEVEL_DEBUG = 'debug';
19 const LEVEL_INFO = 'info';
20 const LEVEL_NOTICE = 'notice';
21 const LEVEL_WARNING = 'warning';
22 const LEVEL_ERROR = 'error';
23
24 const MAX_FILE_SIZE = 204800;
25 const MAX_FILES_BY_LEVEL = 9;
26
27 28 29 30 31
32 protected static $instance;
33
34 35 36
37 private $resources = array();
38
39
40 41 42 43 44
45 private function open($level){
46 $basename = $level . '.log';
47 $filename = LOG_DIR . $basename;
48
49 if(is_file($filename) && filesize($filename) >= self::MAX_FILE_SIZE) {
50
51
52
53 $archives = array_reverse(glob($filename . '.*.zip'));
54 foreach($archives as $archive){
55 preg_match('/^' . preg_quote($basename, '/') . '\.(\d+)\.zip$/', basename($archive), $match);
56 if($match[1] > self::MAX_FILES_BY_LEVEL) {
57 unlink($archive);
58 }
59 else{
60 rename($archive, $filename . '.' . ($match[1] + 1) . '.zip');
61 }
62 }
63
64
65 $zip = new \ZipArchive;
66 $zip->open($filename . '.0.zip', \ZipArchive::CREATE);
67 $zip->addFile($filename);
68 $zip->close();
69
70 unlink($filename);
71 }
72 $this->resources[$level] = fopen($filename, 'a+');
73 }
74
75 76 77 78 79 80
81 private function write($level, $message){
82
83 if(defined('ENABLE_LOG') && !ENABLE_LOG) {
84 return;
85 }
86
87 if(empty($this->resources[$level])) {
88 $this->open($level);
89 }
90
91 $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
92 $trace = (object) $trace[1];
93
94 $data = array(
95 'date' => date_create()->format('Y-m-d H:i:s'),
96 'uri' => App::request()->getUri(),
97 'trace' => $trace->file . ':' . $trace->line,
98 'message' => $message,
99 );
100
101 $input = implode(' - ', $data) . PHP_EOL;
102 fwrite($this->resources[$level], $input);
103 }
104
105 106 107 108 109 110
111 public function info($message){
112 $this->write(self::LEVEL_INFO, $message);
113 }
114
115 116 117 118 119 120
121 public function debug($message){
122 $this->write(self::LEVEL_DEBUG, $message);
123 }
124
125 126 127 128 129 130
131 public function notice($message){
132 $this->write(self::LEVEL_NOTICE, $message);
133 }
134
135 136 137 138 139 140
141 public function warning($message){
142 $this->write(self::LEVEL_WARNING, $message);
143 }
144
145 146 147 148 149 150
151 public function error($message){
152 $this->write(self::LEVEL_ERROR, $message);
153 }
154 }