first commit
This commit is contained in:
61
backend/includes/Logger.php
Normal file
61
backend/includes/Logger.php
Normal file
@@ -0,0 +1,61 @@
|
||||
<?php
|
||||
/**
|
||||
* Request Logger — Logs all API requests to MySQL
|
||||
*/
|
||||
|
||||
require_once __DIR__ . '/Database.php';
|
||||
|
||||
class RequestLogger
|
||||
{
|
||||
/**
|
||||
* Log an API request.
|
||||
*/
|
||||
public static function log(
|
||||
string $endpoint,
|
||||
string $method,
|
||||
?array $requestBody = null,
|
||||
int $responseCode = 200,
|
||||
?string $error = null
|
||||
): void {
|
||||
if (!LOG_REQUESTS) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$db = Database::getInstance();
|
||||
$ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
|
||||
$userAgent = $_SERVER['HTTP_USER_AGENT'] ?? 'unknown';
|
||||
$body = $requestBody ? json_encode($requestBody) : null;
|
||||
|
||||
// Mask sensitive fields
|
||||
if ($body) {
|
||||
$body = self::maskSensitive($body);
|
||||
}
|
||||
|
||||
$stmt = $db->prepare(
|
||||
"INSERT INTO api_logs (endpoint, method, ip_address, user_agent, request_body, response_code, error, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, NOW())"
|
||||
);
|
||||
$stmt->execute([$endpoint, $method, $ip, $userAgent, $body, $responseCode, $error]);
|
||||
} catch (\Throwable $e) {
|
||||
// Logging should never break the app
|
||||
error_log("RequestLogger error: " . $e->getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Mask sensitive fields in request body.
|
||||
*/
|
||||
private static function maskSensitive(string $body): string
|
||||
{
|
||||
$sensitive = ['app_key', 'password', 'otp', 'otp_code'];
|
||||
foreach ($sensitive as $field) {
|
||||
$body = preg_replace(
|
||||
'/"' . $field . '"\s*:\s*"[^"]*"/',
|
||||
'"' . $field . '":"***"',
|
||||
$body
|
||||
);
|
||||
}
|
||||
return $body;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user