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:
TRACE < DEBUG < INFO < WARN < ERROR < CRITICALTRACE < DEBUG < INFO < WARN < ERROR < CRITICALLevel Reference
TRACE
Most detailed logging level for in-depth debugging:
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()")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:
Log.debug("Cache key not found, fetching from database")
Log.debug(f"Request headers: {headers}")
Log.debug("Database connection established")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:
Log.info("Application started")
Log.info(f"User {user_id} logged in")
Log.info("Background job completed")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:
Log.warn("Database query took 5 seconds")
Log.warn("Configuration value missing, using default")
Log.warn("Disk space running low")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:
try:
result = database.query("SELECT * FROM users")
except Exception as e:
Log.error("Database query failed", exception=e)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:
Log.critical("Out of memory error - system shutdown imminent")
Log.critical("Security violation detected")
Log.critical("Database unavailable - cannot continue")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:
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") # Displayedfrom 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") # DisplayedEnvironment-Based Filtering
Choose different log levels per environment:
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()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
settings = LogSettings(
minimum_level=LogLevel.DEBUG, # See everything
console_enabled=True,
include_caller_info=True
)settings = LogSettings(
minimum_level=LogLevel.DEBUG, # See everything
console_enabled=True,
include_caller_info=True
)Output:
[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'}[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
settings = LogSettings(
minimum_level=LogLevel.WARN, # Only important issues
console_enabled=False,
persist=True
)settings = LogSettings(
minimum_level=LogLevel.WARN, # Only important issues
console_enabled=False,
persist=True
)Output:
[WARN] Cache miss, fetching from database
[ERROR] Failed to process payment
[CRITICAL] Database connection lost[WARN] Cache miss, fetching from database
[ERROR] Failed to process payment
[CRITICAL] Database connection lostStaging Configuration
settings = LogSettings(
minimum_level=LogLevel.INFO, # Balance of detail
console_enabled=True,
include_caller_info=False
)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:
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)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:
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
)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
settings = LogSettings(minimum_level=LogLevel.ERROR)
Log.initialize(settings)settings = LogSettings(minimum_level=LogLevel.ERROR)
Log.initialize(settings)Log Warnings and Above
settings = LogSettings(minimum_level=LogLevel.WARN)
Log.initialize(settings)settings = LogSettings(minimum_level=LogLevel.WARN)
Log.initialize(settings)Log Everything
settings = LogSettings(minimum_level=LogLevel.TRACE)
Log.initialize(settings)settings = LogSettings(minimum_level=LogLevel.TRACE)
Log.initialize(settings)Performance Considerations
Log level filtering happens before sending logs, reducing network and storage overhead:
# Expensive operations only log in DEBUG
if settings.minimum_level <= LogLevel.DEBUG:
Log.debug(f"Heavy computation: {expensive_function()}")# Expensive operations only log in DEBUG
if settings.minimum_level <= LogLevel.DEBUG:
Log.debug(f"Heavy computation: {expensive_function()}")Better approach - ByteHide handles this:
# Always safe - only executed if DEBUG level is enabled
Log.debug(f"Expensive debug info: {data}")# Always safe - only executed if DEBUG level is enabled
Log.debug(f"Expensive debug info: {data}")Best Practices
- Development - Use
DEBUGto see all operation details - Staging - Use
INFOfor normal operations, catch issues before production - Production - Use
WARNto focus on important issues only - Debugging - Temporarily lower level to
TRACEwhen investigating - Performance - Use higher levels (
WARN,ERROR) to reduce log volume
Dynamic Level Adjustment
Adjust log levels at runtime:
def set_debug_mode(enabled):
if enabled:
Log.initialize(LogSettings(minimum_level=LogLevel.DEBUG))
else:
Log.initialize(LogSettings(minimum_level=LogLevel.INFO))def set_debug_mode(enabled):
if enabled:
Log.initialize(LogSettings(minimum_level=LogLevel.DEBUG))
else:
Log.initialize(LogSettings(minimum_level=LogLevel.INFO))Next Steps
- Quick Start - Start logging
- Configuration - All configuration options
- Console Output - Customize console display