/

Console Output

Console Output

Enable and configure console logging for immediate visibility of log messages during development and debugging.

Enable Console Logging

Enable console output with a simple flag:

Python
from bytehide_logs import Log, LogSettings

settings = LogSettings(console_enabled=True)
Log.initialize(settings)

Log.info("This message appears in console")

Disable Console Logging

Turn off console output while keeping other logging active:

Python
settings = LogSettings(console_enabled=False)
Log.initialize(settings)

Log.info("This message is NOT shown in console")

Console with File Logging

Log to both console and file simultaneously:

Python
from bytehide_logs import Log, LogSettings, RollingInterval

settings = LogSettings(
    console_enabled=True,      # Output to console
    persist=True,              # Also write to file
    file_path="./logs/app.log",
    rolling_interval=RollingInterval.DAY
)

Log.initialize(settings)

Log.info("Logged to both console and file")

Console Output Examples

Basic Output

Python
Log.info("Application started")
Log.warn("High memory usage detected")
Log.error("Failed to connect to database")

Output:

CODE
[INFO] Application started
[WARN] High memory usage detected
[ERROR] Failed to connect to database

With Caller Information

Include filename and line number in console output:

Python
settings = LogSettings(
    console_enabled=True,
    include_caller_info=True
)

Log.initialize(settings)
Log.info("Request received")

Output:

CODE
[INFO] app.py:42 Request received

Colored Output by Level

ByteHide automatically colors console output by log level:

Python
Log.trace("Trace message")        # Gray
Log.debug("Debug message")        # Cyan
Log.info("Info message")          # Green
Log.warn("Warning message")       # Yellow
Log.error("Error message")        # Red
Log.critical("Critical message")  # Bright Red

Console Output with Context

Tags

Add tags to organize console output:

Python
Log.with_tags("auth").info("User login successful")
Log.with_tags("api", "v2").warn("Deprecated endpoint used")

Output:

CODE
[INFO] [auth] User login successful
[WARN] [api][v2] Deprecated endpoint used

Custom Context

Add key-value pairs to console output:

Python
Log.with_context("user_id", "123").info("User action recorded")
Log.with_context("endpoint", "/api/users").with_context("status", 200).info("Request completed")

Output:

CODE
[INFO] user_id=123 User action recorded
[INFO] endpoint=/api/users status=200 Request completed

Correlation ID

Track related log messages in console:

Python
request_id = "req-abc123"
Log.with_correlation_id(request_id).info("Request started")
Log.with_correlation_id(request_id).debug("Processing user data")
Log.with_correlation_id(request_id).info("Request completed")

Output:

CODE
[INFO] (req-abc123) Request started
[DEBUG] (req-abc123) Processing user data
[INFO] (req-abc123) Request completed

Console Output Configuration

Development Configuration

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

Log.initialize(settings)

Output style:

  • Shows all messages (DEBUG and above)
  • Includes source file and line number
  • Colored by level
  • Visible immediately

Production Configuration

Python
settings = LogSettings(
    console_enabled=False,  # Usually disabled in production
    persist=True,
    minimum_level=LogLevel.WARN
)

Log.initialize(settings)

Interactive Development

Python
settings = LogSettings(
    console_enabled=True,
    minimum_level=LogLevel.TRACE,
    include_caller_info=True
)

Log.initialize(settings)

# Now see detailed execution flow
for i in range(3):
    Log.trace(f"Loop iteration {i}")
    Log.debug(f"Processing item {i}")
    Log.info(f"Item {i} completed")

Redirecting Console Output

To File (Operating System Level)

Bash
# Redirect to file
python app.py > logs.txt 2>&1

# Append to file
python app.py >> logs.txt 2>&1

In Python Code

Python
import sys

# Redirect stdout to file
with open("console_output.log", "w") as f:
    original_stdout = sys.stdout
    sys.stdout = f
    try:
        Log.info("This is redirected")
    finally:
        sys.stdout = original_stdout

Console Formatting

Include Timestamps

While ByteHide doesn't format timestamps by default, you can add them:

Python
from datetime import datetime
import time

Log.info(f"[{datetime.now().isoformat()}] Application started")

Pretty Printing Objects

Python
import json

user_data = {"id": 123, "name": "John", "email": "john@example.com"}
Log.info(f"User data: {json.dumps(user_data, indent=2)}")

Multiline Output

Python
error_details = """
Database Error Details:
- Host: localhost:5432
- Database: myapp
- Error: Connection timeout
"""

Log.error(f"Database connection failed:{error_details}")

Combining with File Logging

Write detailed logs to file while showing summary in console:

Python
from bytehide_logs import Log, LogSettings, LogLevel

settings = LogSettings(
    # Console: high level only
    console_enabled=True,
    # File: all details
    persist=True,
    file_path="./logs/detailed.log",
    # Different minimum levels
    minimum_level=LogLevel.WARN  # File gets all levels via persist
)

Log.initialize(settings)

Log.trace("Trace - only in file")
Log.debug("Debug - only in file")
Log.info("Info - only in file")
Log.warn("Warning - in console and file")
Log.error("Error - in console and file")

Sensitive Data in Console

Protect sensitive data from appearing in console:

Python
settings = LogSettings(
    console_enabled=True,
    mask_sensitive_data=["password", "token", "api_key"]
)

Log.initialize(settings)

password = "secret123"
Log.info(f"Login attempt with password: {password}")
# Output: [INFO] Login attempt with password: ***

Environment-Based Console Configuration

Python
import os
from bytehide_logs import Log, LogSettings, LogLevel

def setup_console():
    env = os.getenv("ENV", "development")
    
    config = {
        "development": {
            "console_enabled": True,
            "minimum_level": LogLevel.DEBUG,
            "include_caller_info": True
        },
        "staging": {
            "console_enabled": True,
            "minimum_level": LogLevel.INFO,
            "include_caller_info": False
        },
        "production": {
            "console_enabled": False,
            "minimum_level": LogLevel.WARN
        }
    }
    
    cfg = config.get(env, config["development"])
    Log.initialize(LogSettings(**cfg))

if __name__ == "__main__":
    setup_console()

Performance Impact

Console logging is asynchronous and has minimal performance impact. For high-throughput applications:

Python
# Reduce console verbosity
settings = LogSettings(
    console_enabled=True,
    minimum_level=LogLevel.WARN  # Only important messages
)

Log.initialize(settings)

Troubleshooting

Console Output Not Appearing

Python
# Ensure console is enabled
settings = LogSettings(console_enabled=True)
Log.initialize(settings)

# Check the log level filter
from bytehide_logs import LogLevel
settings = LogSettings(
    console_enabled=True,
    minimum_level=LogLevel.TRACE
)

Colors Not Working

Colors should work on most terminals. If not:

Python
# Verify basic output is working
Log.info("Testing console output")

# Check your terminal supports colors
# Try a different terminal or configure SSH with: ssh -t hostname

Next Steps

Previous
Log Levels