AuditLog.php
1.19 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
<?php
final class AuditLog
{
public static function record(string $usuario, string $acao, ?string $alvo = null, ?string $detalhe = null): void
{
$ip = $_SERVER['REMOTE_ADDR'] ?? null;
try {
$stmt = Database::pdo()->prepare(
'INSERT INTO audit_log (usuario, acao, alvo, detalhe, ip) VALUES (:usuario, :acao, :alvo, :detalhe, :ip)'
);
$stmt->execute([
'usuario' => $usuario,
'acao' => $acao,
'alvo' => $alvo,
'detalhe' => $detalhe,
'ip' => $ip,
]);
} catch (Throwable $e) {
// Nunca deixa uma falha de log derrubar a ação principal.
error_log('AuditLog falhou: ' . $e->getMessage());
}
$logFile = Config::get('app.log_file');
if ($logFile) {
$line = sprintf(
"%s|%s|%s|%s|%s|%s\n",
date('Y-m-d H:i:s'),
$ip,
$usuario,
$acao,
$alvo ?? '-',
$detalhe ?? '-'
);
@file_put_contents($logFile, $line, FILE_APPEND | LOCK_EX);
}
}
}