Mangcoding

icon chat
samsul aripin - Thursday, 19 June 2025 - 7 months ago

Logging Is a Must — So You Don’t Have to Play Psychic When Errors Happen

single image

Imagine this :

A new feature just went live. Then, a user reports: “Why can’t I check out?”

You test it locally — everything works fine. You check the user’s browser console — nothing shows up.

Without logs, all you can do is guess. It feels like being a psychic trying to read errors from the sky. 😅

Link Mangcoding

What Is Logging and Why Is It Important?

[2025-06-04 10:15:22] production.INFO: [log_id: 6a9c3e21-778e-49d4-9c98-cbba5ea0c841] User login berhasil. user_id=101 ip=103.12.5.77 url=/api/login[2025-06-04 10:20:07] production.WARNING: [log_id: d57ab8fc-45c1-4e82-9c7d-07b8e446acf6] Permintaan aneh terdeteksi. user_id=101 ip=103.12.5.77 url=/api/products?sort=DROP+TABLE 
[2025-06-04 10:21:43] production.ERROR: [log_id: a34a89df-25b9-4a57-b210-dab32e68f4c9] Checkout gagal. user_id=101 ip=103.12.5.77 url=/api/checkout error=Payment gateway timeout 
[2025-06-04 10:22:00] production.INFO: [log_id: 55f3bc3d-7ed3-4cdd-b2e3-90cdb1d2c024] Notifikasi email berhasil dikirim. user_id=101 [email protected]

Logging is the automatic recording of what happens inside your application. Therefore, if you have clean and complete logs, you can:

  • Check the transaction ID

  • Identify the user

  • View error messages, trace, and IP address

  • Instantly locate the failure point

In short, logging is not just a bonus feature. Instead, logging is your lifeline when debugging. Without logs, you’ll run in circles, unsure where to start. With logs, however, you can quickly pinpoint the problem — no panic, no guesswork.

1. Log Every Exception with a Unique ID

When an exception occurs, always log it with a unique ID (UUID).

Why is this important?

Because with a unique ID for every error, the frontend team can simply send that ID to the backend team. As a result, the backend team can search the logs using that ID — no need to dig through a confusing stack trace.

use Illuminate\Support\Str;

try {
    // proses penting
} catch (Exception $e) {
    $logId = Str::uuid();

    Log::error("[$logId] Gagal memproses checkout", [
        'user_id' => auth()->id(),
        'ip' => request()->ip(),
        'url' => request()->fullUrl(),
        'message' => $e->getMessage(),
    ]);

    return response()->json([
        'message' => 'Terjadi kesalahan, silakan hubungi admin.',
        'log_id' => $logId,
    ], 500);
}

In addition, all of this information should go into a log file. Why?

  • In production, you should never show stack traces to users (because it’s a security risk).

  • Log files are the single source of truth for developers.

2. Include Request Context

Next, don’t just log the error message. Instead, always include:

  • user_id → who triggered it?

  • ip → where did it come from?

  • url → which endpoint was affected?

  • params → what was in the request body?

With this extra context, you can perform root cause analysis much faster.

3. Use Structured Logging (Not String Concatenation)

On the other hand, string concatenation makes logs harder to read.

Bad example ❌:

// ❌ string biasa
console.log("User gagal login: " + userId + ", error: " + err.message);

Good example ✅:

// ✅ structured
console.error("Login gagal", {
    userId: user.id,
    error: err.message,
    ip: req.ip,
    path: req.originalUrl
});

Therefore, Structured logs are easier to:

  • Search

  • Index with tools like ELK or Datadog

  • Read by both humans and machine

4. Follow a Common Log Format

Whether your logs are in plain text (.log) or JSON, you should always include:

  • timestamp → when it happened

  • level → ERROR, INFO, WARN, etc.

  • message → what happened

  • log_id → unique ID

  • user_id, ip, url → context

⚠️ Important: Never log passwords, tokens, credit card numbers, or other sensitive data.

5. Rotate Log Files Regularly to Avoid Overflow

Logs can grow quickly. If left unchecked, your disk can fill up and the application may crash.

To prevent this, use these solutions:

  • In Laravel: set logging.php to daily

  • On Linux: use logrotate

  • Add disk usage monitoring

As a result, your application remains stable without being weighed down by oversized log files.

Conclusion

Logging is more than just saving errors. Rather, it’s your lifeline during debugging. By adding unique IDs, capturing context, using structured formats, and rotating log files, you ensure stability in production.

And then, clean logs don’t just make debugging easier — they give your entire team confidence when handling issues.

Note: This article was inspired by a LinkedIn post by Mayank A., which discusses best practices in software development. You can read the original version Here.

Link Copied to Clipboard