KAHIBARO
Discord Login Register

20.2. Log Levels

Why Log Levels Matter

Log levels help you control how much information your application logs, and how important that information is. Without log levels, your logs quickly become a noisy wall of text that is hard to search and almost impossible to use for debugging or monitoring.

Log levels let you:

Most languages, frameworks, and logging libraries use a similar set of levels, from least to most severe:

Severity (low β†’ high)Typical name
1TRACE
2DEBUG
3INFO
4WARN / WARNING
5ERROR
6FATAL / CRITICAL

Rule: Log levels are about importance, not about where the code is. The deeper in your code, the more context you might log, but the level still depends only on how serious the situation is.

Common Log Levels and Their Meanings

TRACE

TRACE is the most detailed level. It is often turned off in most environments.

Use TRACE to log:

Examples:

text
2024-08-01T12:00:01Z TRACE Starting cache lookup for key=user:123
2024-08-01T12:00:01Z TRACE Cache miss, querying database for user_id=123
2024-08-01T12:00:01Z TRACE Mapping DB row to UserDTO for user_id=123

When to use:

When not to use:

DEBUG

DEBUG logs are for developers, not for business users or support teams. They help you understand how the application works internally.

Use DEBUG to log:

Examples:

text
2024-08-01T12:10:05Z DEBUG AuthMiddleware: JWT token validated for user_id=42
2024-08-01T12:10:05Z DEBUG get_user_orders: fetching orders for user_id=42, status='open'
2024-08-01T12:10:05Z DEBUG DB query executed in 12ms (SELECT * FROM orders WHERE ...)

Typical usage by environment:

EnvironmentDEBUG enabled?Reason
Local devYesYou want maximum visibility.
StagingOften yesTo debug issues before production.
ProductionOften noTo reduce noise and log volume.

INFO

INFO is for normal, high-level events in your application. These are things that are expected and not problems.

Use INFO to log:

Examples:

text
2024-08-01T12:15:00Z INFO HTTP server started on port=8000, env=production
2024-08-01T12:15:02Z INFO User registered successfully user_id=987, email=user@example.com
2024-08-01T12:15:10Z INFO Daily report job completed duration_ms=4500, generated_reports=153

INFO logs are usually always on in production, because they show:

WARNING / WARN

WARNING means something unexpected happened, or something is not ideal, but the application can still continue.

Use WARNING to log:

Examples:

text
2024-08-01T12:20:00Z WARNING Cache server not reachable, falling back to database
2024-08-01T12:20:01Z WARNING Deprecated endpoint /v1/users used by client_id=mobile-app-v1
2024-08-01T12:20:03Z WARNING Invalid login attempt for email=unknown@example.com, ip=203.0.113.5

When to use WARNING instead of ERROR:

ERROR

ERROR means a request or operation failed, and the application could not do what it should have.

Use ERROR to log:

Examples:

text
2024-08-01T12:25:10Z ERROR Failed to process order order_id=555, reason="payment declined"
2024-08-01T12:25:11Z ERROR Unhandled exception in /api/orders
Traceback (most recent call last):
  ...
2024-08-01T12:25:12Z ERROR Failed to send email to user_id=987, smtp_error="Timeout"

Typical behavior:

FATAL / CRITICAL

FATAL or CRITICAL logs mean something very serious happened. The system cannot continue working normally.

Use FATAL / CRITICAL to log:

Examples:

text
2024-08-01T12:30:00Z CRITICAL Database connection failed at startup, exiting. error="connection refused"
2024-08-01T12:30:05Z CRITICAL Configuration error: SECRET_KEY is missing, application cannot start
2024-08-01T12:30:10Z FATAL Unrecoverable error in payment service, shutting down workers

Usually:

Choosing the Right Level

Using the right log level is a skill. It directly affects how useful your logs are.

Here is a simple decision table:

SituationSuggested level
A normal API request completes with 200 OKINFO or DEBUG
A background job starts and finishes normallyINFO
You are checking internal variables while developing a featureDEBUG or TRACE
A cache lookup fails, but you fall back to the database successfullyWARNING
A user provides invalid input, and you return 400 Bad RequestINFO or WARNING
A request causes an unhandled exception and returns 500 Internal Server ErrorERROR
The app cannot connect to the database at startupCRITICAL
You detect possible data corruptionCRITICAL

Rule of thumb:

  • INFO for normal events.
  • WARNING when something is unusual but handled.
  • ERROR when an operation fails.
  • CRITICAL when the whole service is in danger.

HTTP Status Codes and Log Levels

You will often log based on HTTP status codes. A simple mapping you can start with:

HTTP status rangeTypical meaningUsual log level
1xx / 2xxSuccessINFO or DEBUG
3xxRedirectINFO
4xx (client error)Client did something wrongINFO or WARNING
5xx (server error)Server failedERROR or CRITICAL

Examples:

Log Level Configuration

Most logging systems let you set a minimum level. Logs below that level are ignored.

For example:

EnvironmentMinimum levelMeaning
Local devDEBUGSee everything except TRACE.
CI / testingINFO or DEBUGFocus on important events and debugging.
StagingINFOLess noise, but still enough details.
ProductionINFO or WARNINGIgnore verbose debug logs.

Pseudo configuration example:

yaml
logging:
  level:
    root: INFO
    "my_app.database": DEBUG
    "my_app.security": WARNING

In this example:

Examples of Good vs Bad Log Levels

Example 1: Cache and Database

Bad usage:

text
DEBUG Cache connection failed, falling back to database
ERROR Cache miss for user_id=123
INFO Database query OK for user_id=123

Problems:

Better usage:

text
WARNING Cache connection failed, falling back to database
DEBUG Cache miss for user_id=123
INFO Loaded user profile user_id=123 from database

Example 2: Validation Errors

Bad usage:

text
ERROR Validation failed for signup form: invalid email

If the user simply typed their email wrong, this is not an internal error.

Better usage:

text
INFO Signup validation error email=not-an-email reason="invalid format"

If you see a lot of such logs from the same IP or user, you can investigate.

Example 3: Startup Failure

Bad usage:

text
ERROR Database not reachable at startup

The application cannot start. This is more than just an ERROR.

Better usage:

text
CRITICAL Database not reachable at startup, exiting. host=db:5432

This tells you that the entire service is down and needs urgent attention.

Log Levels and Alerting

Monitoring and alerting tools often use levels to decide what to alert on.

A common pattern:

Example policies:

LevelAlerting strategy
DEBUGNo alerts.
INFONo alerts. Used for dashboards & history.
WARNINGAlert if rate is high for a long period.
ERRORAlert if rate spikes or key endpoints affected.
CRITICALImmediate alert.

Practical Guidelines for Writing Logs

  1. Choose level by impact, not by how tricky the code feels.
  2. Keep secrets out of logs, especially at DEBUG or TRACE:
    • Do not log passwords, tokens, full credit card numbers, or full personal data.
  3. Be consistent:
    • Use the same level for the same kind of event everywhere.
  4. Use higher levels for business failures:
    • A failed payment or failed order processing is at least ERROR, even if the code did not crash.
  5. Use lower levels for expected irregular events:
    • Cache misses, occasional invalid inputs, or retries can be INFO or WARNING.

Example of a full log story for a failed request:

text
2024-08-01T13:00:00Z INFO POST /api/orders user_id=42
2024-08-01T13:00:00Z DEBUG Validating order payload for user_id=42
2024-08-01T13:00:00Z WARNING Payment service timeout, retrying attempt=1
2024-08-01T13:00:01Z WARNING Payment service timeout, retrying attempt=2
2024-08-01T13:00:02Z ERROR Payment failed for order_id=777 user_id=42 reason="service unavailable"

From these levels you can quickly see:

This is the main purpose of log levels: to let you understand the story of your system at a glance.

Views: 7

Comments

Please login to add a comment.

Don't have an account? Register now!