-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathErrorHandler.php
More file actions
227 lines (178 loc) · 6.79 KB
/
Copy pathErrorHandler.php
File metadata and controls
227 lines (178 loc) · 6.79 KB
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
<?php
namespace Dps;
use Cekurte\Environment\Environment as env;
use Kint;
/**
* clase Errorhandler para el manejo de errores
*
* @requires $_ENV['ERROR_LOG_ENABLED']
* @requires $_ENV['ERROR_LOG_TO_SCREEN']
* @requires $_ENV['PATH_LOG']
*/
class ErrorHandler
{
public $err;
private $errType = [
1 => "ERROR",
2 => "WARNING",
4 => "PARSING",
8 => "NOTICE",
16 => "CORE ERROR",
32 => "CORE WARNING",
64 => "COMPILE ERROR",
128 => "COMPILE WARNING",
256 => "USER ERROR",
512 => "USER WARNING",
1024 => "USER NOTICE",
2048 => "STRICT",
4096 => "ERROR FATAL CAPTURABLE",
8192 => "DEPRECATED",
16384 => "USER DEPRECATED"
];
public array $mensajes = [];
private string $log_path = '';
private string $memory;
private bool $to_log = true;
private bool $to_screen = false;
private string $usuario;
public function __construct() {
$this->to_log = env::get('ERROR_LOG_ENABLED', true);
$this->to_screen = env::get('ERROR_LOG_TO_SCREEN', false);
// Me guardo un poco de memoria, por las dudas, para ser usada en shutdown()
$this->memory = str_repeat('*', 3 * 1024 * 1024); // 3mb
ini_set('display_errors', 0);
$this->setLogPath();
set_error_handler( [ $this, 'error_handler' ] );
set_exception_handler( [ $this, 'exception_handler' ] );
register_shutdown_function( [ $this, 'shutdown' ] );
}
public function exception_handler( $ex ) {
$this->procesar( E_ERROR, $ex->getMessage(), $ex->getFile(), $ex->getLine(), $ex->getTrace() );
if( get_class( $ex ) == 'Dps\MysqlException' ) {
global $smarty;
if( $smarty ) {
$nro = $ex->MysqlNro;
$texto = MysqlMessages::getMsg( $nro ) ?? $ex->MysqlError;
$_GET['sinMenu'] = 1;
http_response_code(406);
$smarty->assign( "soloCerrar", true );
$smarty->assign( "mensaje", "<span style='color:red;font-size:xx-small;'>- $nro -</span><br>$texto" );
$smarty->mostrar( "mensajeerror.tpl" );
}
}
die;
}
public function error_handler( int $errNo, string $errMsg = '', string $file = '', int $line = 0, $context = [] ) {
// Revisa que el error este incluido en error_reporting()
if( ! ( $errNo & error_reporting() ) )
return true;
$trace = debug_backtrace();
$this->procesar( $errNo, $errMsg, $file, $line, $trace );
return true; // false para seguir con el manejador de errores nativo de php
}
private function procesar( int $errNo, string $errMsg = '', string $file = '', int $line = 0, array $trace = [] ) {
$this->save( $errNo, $errMsg, $file, $line, $trace );
$this->toLog();
$this->toScreen();
}
/**
* Guarda el error en un array agrupando los repetidos
* @param int $errNo
* @param string $errMsg
* @param string $file
* @param int $line
* @param array $trace
* @return void
*/
private function save( int $errNo, string $errMsg = '', string $file = '', int $line = 0, array $trace = [] ) {
$miniTrace = [];
foreach ($trace as $t) {
$f = $t['file'] ?? '';
$l = $t['line'] ?? '';
$miniTrace[] = "{$f} ({$l})";
}
$this->err = [
'errNo' => $errNo,
'errType' => $this->errType[$errNo],
'errMsg' => $errMsg,
'file' => $file,
'line' => $line,
'trace' => $miniTrace,
'count' => 1
];
$hash = md5( $errMsg . $file . $line );
if( array_key_exists( $hash, $this->mensajes ) ) {
$this->mensajes[$hash]['count']++;
} else {
$this->mensajes[ $hash ] = $this->err;
}
}
/**
* Envia el error al archivo de log
* @return void
*/
private function toLog() {
if( $this->to_log ) {
$this->setFullpathLog();
error_log( "[{$this->err['errType']}] {$this->err['errMsg']} {$this->err['file']} ({$this->err['line']})" );
}
}
/**
* Envia el error a la pantalla
* @return void
*/
private function toScreen() {
if( $this->to_screen ) {
Kint::dump( $this->err );
}
}
/**
* Genera la ruta del archivo de log
* @return void
*/
private function setLogPath() {
// los cron ejecutados a cada minuto, se solapaban, e intentaban todos crear la misma carpeta.
// por eso utilizo el mecanismo de FLOCK para que solo uno logre crear la carpeta.
$lockFile = fopen('/tmp/lock_mkdir_cron', 'c'); // Archivo de control
if (flock($lockFile, LOCK_EX)) {
$path = env::get('PATH_LOG', '/tmp') . date('/Y/m/d');
if( ! is_dir( $path ) )
@mkdir( $path, 0755, true);
flock($lockFile, LOCK_UN); // Liberar el bloqueo
}
fclose($lockFile);
$this->log_path = $path;
$this->setFullpathLog();
}
/**
* Configura el archivo de log, segun el usuario conectado
* @return void
* @todo Evitar que el valor se tome de SESSION
*/
private function setFullpathLog() {
$this->usuario = ( ! isset( $_SESSION['UsuarioConectado'] ) || ! $_SESSION['UsuarioConectado'] ) ? 'sinUsuario' : $_SESSION['UsuarioConectado'];
$fullPath = "{$this->log_path}/{$this->usuario}.log";
ini_set("error_log", $fullPath );
}
/**
* Esta funcion se ejecuta al final de cada script
* @return void
*/
public function shutdown() {
// devuelvo la memoria consumida a proposito
// Eso será util cuando el error haya sido por memoria consumida,
// y entonces, no me quede nada disponbile para seguir manejando el error
unset( $this->memory );
$error = error_get_last();
if ($error) {
$this->procesar( $error["type"], $error['message'], $error['file'], $error['line'] );
// Envio un segundo mensaje con algo de info de donde sucedio el error
$php = array_unique([ $_SERVER['PHP_SELF'], $_SERVER['REQUEST_URI'] ]);
$this->procesar( $error["type"], "Trace: " . implode("\n", $php) . "\n", $error['file'], $error['line'] );
http_response_code(500);
}
}
public function getUsuario() {
return ( $this->usuario ) ? $this->usuario : 'sinUsuario';
}
}