Lesson 88 of 158 – API Logging
88%

API Logging

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.

Note: Logs should contain useful technical information but should never expose passwords, JWT tokens, sensitive personal data, or other secrets.

1. What is API Logging?

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.

2. Why API Logging is Important

Logging is useful for:

  • Debugging API errors
  • Monitoring API requests
  • Finding failed operations
  • Investigating security incidents
  • Understanding application behavior
  • Monitoring performance
  • Maintaining production applications

3. What Information Can Be Logged?

A useful API log may contain:

  • Request method
  • Request path
  • Timestamp
  • HTTP status code
  • Response time
  • User ID when appropriate
  • IP address when appropriate
  • Error information

4. Do Not Log Passwords

Never write passwords into application logs.

Bad:

email=user@example.com
password=MyPassword123

Passwords are sensitive credentials and should never be stored in logs.

5. Do Not Log JWT Tokens

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.

6. PHP error_log()

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.

7. Logging an Exception

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.

8. Logging Request Method

$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.

9. Logging Request URI

$uri =
    $_SERVER['REQUEST_URI']
    ?? '';

error_log(
    "API URI: " . $uri
);

The URI can help identify which endpoint was requested.

10. Logging HTTP Status Codes

$statusCode = 200;

error_log(
    "API Status: "
    . $statusCode
);

Status codes such as 200, 400, 401, 404, and 500 can be useful when investigating API behavior.

11. Logging Date and Time

Every log entry should have a useful timestamp.

A timestamp makes it easier to identify when an event occurred.

12. Create a Simple Log Message

$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.

13. Logging API Errors

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.

14. Logging User ID

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.

15. Request ID

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.

16. API Request Logging Function

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.

17. Logging Request and Response Status

$method =
    $_SERVER['REQUEST_METHOD']
    ?? '';

$uri =
    $_SERVER['REQUEST_URI']
    ?? '';

$status = 200;

error_log(
    $method
    . " "
    . $uri
    . " - "
    . $status
);

This gives a simple overview of API activity.

18. Measuring API Response Time

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.

19. Logging Database Errors

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.

20. Log Levels

Applications can categorize log messages according to their importance.

  • DEBUG – detailed development information
  • INFO – normal application activity
  • WARNING – potentially problematic event
  • ERROR – operation failed
  • CRITICAL – serious application problem
INFO:
Student API request received

ERROR:
Database connection failed

21. JSON Logging Format

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.

22. Logging Authentication Events

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.

23. Logging Failed API Requests

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.

24. Logging React Native API Errors

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.

25. API Logging and Security

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.

26. What Should Not Be Logged?

  • Passwords
  • JWT access tokens
  • Refresh tokens
  • Private encryption keys
  • Database passwords
  • API secrets
  • Unnecessary sensitive personal information

Logs should contain enough information to troubleshoot the application without becoming a source of sensitive data leakage.

27. Log Rotation

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.

28. Centralized Logging

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.

29. Complete API Logging Flow

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.

30. API Logging Summary

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.

📌 Key Points

  • API logging records important API events and activities.
  • PHP provides error_log() for server-side logging.
  • Logs are useful for debugging and troubleshooting.
  • Request methods and API endpoints can be logged.
  • HTTP status codes can be recorded.
  • Response time can be measured and logged.
  • Database errors can be logged on the server.
  • Technical errors should not be exposed directly to clients.
  • Request IDs can help connect related log entries.
  • Authentication events can be logged without recording credentials.
  • Passwords and JWT tokens should never be logged.
  • Log rotation helps control log storage.
  • Structured and centralized logging can help larger applications.
  • React Native can log useful non-sensitive API information during development.
  • The next lesson will cover API versioning.

🧠 Quick Quiz

Question: Which PHP function can be used to write a message to the server error log?