/

Log Levels

Log Levels

ByteHide Logs supports six severity levels for controlling log output and filtering messages.

Log Level Hierarchy

From least to most severe:

CODE
TRACE < DEBUG < INFO < WARN < ERROR < CRITICAL

Level Reference

TRACE

Most detailed logging level for in-depth debugging:

Python
from bytehide_logs import Log, LogLevel

Log.set_project_token("your-token")
Log.initialize(LogSettings(minimum_level=LogLevel.TRACE))

Log.trace("Variable x = 42")
Log.trace("Entering function calculate()")

Use cases:

  • Variable inspection
  • Function entry/exit
  • Detailed flow tracking
  • Performance profiling

DEBUG

Diagnostic information for development:

Python
Log.debug("Cache key not found, fetching from database")
Log.debug(f"Request headers: {headers}")
Log.debug("Database connection established")

Use cases:

  • Diagnostics
  • Method parameters
  • State changes
  • Configuration details

INFO

General informational messages about application operation:

Python
Log.info("Application started")
Log.info(f"User {user_id} logged in")
Log.info("Background job completed")

Use cases:

  • Application lifecycle events
  • User actions
  • Business operations
  • Job completions

WARN

Warning messages indicating potential issues:

Python
Log.warn("Database query took 5 seconds")
Log.warn("Configuration value missing, using default")
Log.warn("Disk space running low")

Use cases:

  • Non-critical issues
  • Degraded performance
  • Deprecated features
  • Resource warnings

ERROR

Error messages indicating failures:

Python
try:
    result = database.query("SELECT * FROM users")
except Exception as e:
    Log.error("Database query failed", exception=e)

Use cases:

  • Operation failures
  • Exception handling
  • Recoverable errors
  • Validation failures

CRITICAL

Critical messages indicating system failure:

Python
Log.critical("Out of memory error - system shutdown imminent")
Log.critical("Security violation detected")
Log.critical("Database unavailable - cannot continue")

Use cases:

  • System failures
  • Security issues
  • Data corruption
  • Complete loss of functionality

Filtering by Level

Use minimum_level in settings to filter log messages:

Python
from bytehide_logs import Log, LogSettings, LogLevel

settings = LogSettings(minimum_level=LogLevel.WARN)
Log.initialize(settings)

Log.trace("Not logged")      # Filtered out
Log.debug("Not logged")      # Filtered out
Log.info("Not logged")       # Filtered out
Log.warn("Logged")           # Displayed
Log.error("Logged")          # Displayed
Log.critical("Logged")       # Displayed

Environment-Based Filtering

Choose different log levels per environment:

Python
import os
from bytehide_logs import Log, LogSettings, LogLevel

def setup_logging():
    env = os.getenv("ENV", "development")
    
    level_map = {
        "development": LogLevel.DEBUG,
        "staging": LogLevel.INFO,
        "production": LogLevel.WARN
    }
    
    settings = LogSettings(
        minimum_level=level_map.get(env, LogLevel.INFO)
    )
    
    Log.initialize(settings)

if __name__ == "__main__":
    setup_logging()

Log Level Examples

Development Configuration

Python
settings = LogSettings(
    minimum_level=LogLevel.DEBUG,  # See everything
    console_enabled=True,
    include_caller_info=True
)

Output:

CODE
[DEBUG] app.py:42 Database query started
[DEBUG] app.py:43 Query parameters: {'id': 123}
[INFO] app.py:45 Query completed
[DEBUG] app.py:46 Result: {'name': 'John', 'email': 'john@example.com'}

Production Configuration

Python
settings = LogSettings(
    minimum_level=LogLevel.WARN,  # Only important issues
    console_enabled=False,
    persist=True
)

Output:

CODE
[WARN] Cache miss, fetching from database
[ERROR] Failed to process payment
[CRITICAL] Database connection lost

Staging Configuration

Python
settings = LogSettings(
    minimum_level=LogLevel.INFO,  # Balance of detail
    console_enabled=True,
    include_caller_info=False
)

Logging with Exceptions

Include exception details with ERROR and CRITICAL:

Python
try:
    user = database.get_user(user_id)
except ValueError as e:
    Log.error(f"Invalid user ID: {user_id}", exception=e)
except Exception as e:
    Log.critical("Unexpected error retrieving user", exception=e)

The exception stack trace is automatically included.

Contextual Logging

Combine levels with context for better insights:

Python
def process_payment(payment_id, amount):
    context = {"payment_id": payment_id, "amount": amount}
    
    Log.with_context("operation", "payment").debug(
        f"Processing payment: {amount}"
    )
    
    try:
        result = stripe.charge(amount)
        Log.with_context("operation", "payment").info(
            f"Payment processed: {result}"
        )
    except stripe.StripeError as e:
        Log.with_context("operation", "payment").error(
            f"Payment failed: {e}", exception=e
        )

Filtering Patterns

Log Errors and Critical Only

Python
settings = LogSettings(minimum_level=LogLevel.ERROR)
Log.initialize(settings)

Log Warnings and Above

Python
settings = LogSettings(minimum_level=LogLevel.WARN)
Log.initialize(settings)

Log Everything

Python
settings = LogSettings(minimum_level=LogLevel.TRACE)
Log.initialize(settings)

Performance Considerations

Log level filtering happens before sending logs, reducing network and storage overhead:

Python
# Expensive operations only log in DEBUG
if settings.minimum_level <= LogLevel.DEBUG:
    Log.debug(f"Heavy computation: {expensive_function()}")

Better approach - ByteHide handles this:

Python
# Always safe - only executed if DEBUG level is enabled
Log.debug(f"Expensive debug info: {data}")

Best Practices

  1. Development - Use DEBUG to see all operation details
  2. Staging - Use INFO for normal operations, catch issues before production
  3. Production - Use WARN to focus on important issues only
  4. Debugging - Temporarily lower level to TRACE when investigating
  5. Performance - Use higher levels (WARN, ERROR) to reduce log volume

Dynamic Level Adjustment

Adjust log levels at runtime:

Python
def set_debug_mode(enabled):
    if enabled:
        Log.initialize(LogSettings(minimum_level=LogLevel.DEBUG))
    else:
        Log.initialize(LogSettings(minimum_level=LogLevel.INFO))

Next Steps

Previous
Project Token