API logging means recording important events and activities that happen inside a REST API. Logs help developers understand errors, monitor requests, troubleshoot problems, and identify suspicious activity.
API logging is the process of recording information about API activity.
Client
↓
REST API
↓
Request
↓
Processing
↓
Database
↓
Response
↓
Log Information
The logs can help developers understand what happened during an API request.
Logging is useful for:
A useful API log may contain:
Never write passwords into application logs.
Bad:
email=user@example.com
password=MyPassword123
Passwords are sensitive credentials and should never be stored in logs.
Access tokens and JWTs should not normally be written to logs.
Bad:
Authorization:
Bearer eyJhbGciOiJIUzI1Ni...
If a token is leaked through logs, someone may potentially use it until it expires or is revoked.
PHP provides the error_log() function for writing messages
to the server's error log.
error_log(
"API request failed"
);
This is useful for server-side debugging without returning internal details to the client.
try {
$stmt = $pdo->query(
"SELECT * FROM students"
);
} catch (PDOException $e) {
error_log(
$e->getMessage()
);
}
The technical error can be recorded on the server while the client receives a safe response.
$method =
$_SERVER['REQUEST_METHOD']
?? '';
error_log(
"API Method: " . $method
);
This can help identify whether the API received GET, POST, PUT, PATCH, DELETE, or another method.
$uri =
$_SERVER['REQUEST_URI']
?? '';
error_log(
"API URI: " . $uri
);
The URI can help identify which endpoint was requested.
$statusCode = 200;
error_log(
"API Status: "
. $statusCode
);
Status codes such as 200, 400, 401, 404, and 500 can be useful when investigating API behavior.
Every log entry should have a useful timestamp.
A timestamp makes it easier to identify when an event occurred.
$method =
$_SERVER['REQUEST_METHOD']
?? '';
$uri =
$_SERVER['REQUEST_URI']
?? '';
error_log(
"[" . date('Y-m-d H:i:s') . "] "
. $method
. " "
. $uri
);
This creates a basic server-side request log.
try {
// API code
} catch (Throwable $e) {
error_log(
"API Error: "
. $e->getMessage()
);
http_response_code(500);
echo json_encode([
"success" => false,
"message" =>
"Internal server error"
]);
}
The client gets a safe message while the server keeps the technical error.
For authenticated APIs, a user ID can sometimes be useful in logs.
$userId = 25;
error_log(
"User ID: "
. $userId
);
Only log user information when it is necessary and appropriate for the application.
A request ID can help connect multiple log entries belonging to the same API request.
$requestId =
bin2hex(
random_bytes(8)
);
error_log(
"Request ID: "
. $requestId
);
The request ID can also be returned to the client when useful.
function logApi(
string $message
): void {
error_log(
"[" .
date('Y-m-d H:i:s') .
"] "
. $message
);
}
logApi(
"Student API requested"
);
A reusable function keeps logging code consistent throughout the API.
$method =
$_SERVER['REQUEST_METHOD']
?? '';
$uri =
$_SERVER['REQUEST_URI']
?? '';
$status = 200;
error_log(
$method
. " "
. $uri
. " - "
. $status
);
This gives a simple overview of API activity.
Response time can be measured using a start timestamp.
$start =
microtime(true);
// API processing
$end =
microtime(true);
$duration =
$end - $start;
error_log(
"Response Time: "
. $duration
. " seconds"
);
Performance logging can help identify slow endpoints.
try {
$stmt = $pdo->prepare(
"SELECT *
FROM students
WHERE id = ?"
);
$stmt->execute([
$id
]);
} catch (PDOException $e) {
error_log(
"Database Error: "
. $e->getMessage()
);
http_response_code(500);
echo json_encode([
"success" => false,
"message" =>
"Database error"
]);
}
Database details should not normally be exposed directly to the mobile application.
Applications can categorize log messages according to their importance.
INFO:
Student API request received
ERROR:
Database connection failed
Structured logs can store information in a JSON-like format.
{
"level": "ERROR",
"method": "POST",
"endpoint": "/api/login.php",
"status": 500,
"message": "Database error"
}
Structured logging can make logs easier to process and analyze.
Security-related events can be logged without recording credentials.
error_log(
"Login failed for user ID: "
. $userId
);
Do not include the password, JWT, session secret, or other sensitive credentials in the log message.
if ($id === false) {
error_log(
"Invalid student ID"
);
http_response_code(400);
echo json_encode([
"success" => false,
"message" =>
"Invalid student ID"
]);
exit;
}
Validation failures can be useful for debugging and security monitoring.
The React Native application can also log non-sensitive information while debugging API communication.
try {
const response =
await fetch(url);
const data =
await response.json();
console.log(
"API Status:",
response.status
);
} catch (error) {
console.log(
"API Request Failed"
);
}
Do not print access tokens, passwords, or sensitive personal data into production application logs.
Logs can help identify suspicious activity.
Repeated Failed Logins
↓
API Logs
↓
Security Monitoring
↓
Investigate Activity
For example, a large number of failed login requests from the same source may deserve investigation.
Logs should contain enough information to troubleshoot the application without becoming a source of sensitive data leakage.
Logs can grow continuously as API traffic increases.
Day 1
↓
Day 2
↓
Day 3
↓
Large Log File
Production systems should use log rotation or another retention strategy so logs do not consume unlimited storage.
Large applications may collect logs from multiple servers into a centralized logging system.
API Server 1 ──┐
API Server 2 ──┼──→ Central Logs
API Server 3 ──┘
This makes it easier to search, monitor, and analyze API activity.
Client Request
↓
Generate Request ID
↓
Authenticate
↓
Validate Input
↓
Process API
↓
Database Operation
↓
Create Response
↓
Log Status + Time
↓
Return JSON
A consistent logging flow makes debugging and monitoring much easier.
API logging is an important part of maintaining a REST API. PHP's
error_log() can be used for server-side logging, while
structured logging can provide more useful information for larger
applications.
Request
↓
Log
↓
Process
↓
Database
↓
Response
↓
Log Status
↓
Monitor
Good logging should provide useful technical information while protecting passwords, tokens, secrets, and sensitive data.
error_log() for server-side logging.Question: Which PHP function can be used to write a message to the server error log?