### Install Logly from Source Source: https://muhammad-fiaz.github.io/logly/guides/getting-started Installs Logly by cloning the Git repository and then performing a local installation using pip. This is useful for development or using the latest unreleased code. ```bash git clone https://github.com/muhammad-fiaz/logly.git cd logly pip install -e . ``` -------------------------------- ### Install Logly with pip Source: https://muhammad-fiaz.github.io/logly/guides/getting-started Installs the Logly library using pip, the standard Python package installer. This is the recommended method for most users. ```bash pip install logly ``` -------------------------------- ### Install Logly with uv Source: https://muhammad-fiaz.github.io/logly/guides/getting-started Installs the Logly library using uv, a fast Python package installer and dependency manager. This method is an alternative to pip. ```bash uv add logly ``` -------------------------------- ### Install Logly with Poetry Source: https://muhammad-fiaz.github.io/logly/guides/getting-started Adds the Logly library as a dependency to a project managed by Poetry, a dependency management and packaging tool for Python. ```bash poetry add logly ``` -------------------------------- ### Basic Logly Usage (Python) Source: https://muhammad-fiaz.github.io/logly/guides/getting-started Demonstrates the simplest way to use Logly after installation. Since version 0.1.5, Logly auto-configures a console logger upon import, allowing immediate logging without explicit configuration. ```python # app.py from logly import logger # That's it! Start logging immediately logger.info("Application started") # ✅ Works right away logger.warning("This is a warning") # ⚠️ No configure() needed logger.error("This is an error") # ❌ Auto-configured on import print("Check your console output above!") ``` -------------------------------- ### Web application logging with Logly and FastAPI (Python) Source: https://muhammad-fiaz.github.io/logly/quickstart Provides the initial setup for integrating Logly into a FastAPI application, importing the logger and creating the FastAPI instance. This pattern can be extended with request‑level logging and custom sinks. ```Python from logly import logger from fastapi import FastAPI, Request app = FastAPI() ``` -------------------------------- ### Dockerfile for Logly installation Source: https://muhammad-fiaz.github.io/logly/installation Dockerfile example for installing Logly in a containerized environment. Uses Python 3.12-slim base image. ```dockerfile FROM python:3.12-slim # Install logly RUN pip install --no-cache-dir logly # Copy application COPY . /app WORKDIR /app # Run application CMD ["python", "app.py"] ``` -------------------------------- ### Custom Logly Configuration (Python) Source: https://muhammad-fiaz.github.io/logly/guides/getting-started Shows how to customize Logly's behavior by calling the `configure()` method. This allows setting the minimum log level, enabling colorized output, and displaying timestamps. ```python from logly import logger # Customize logging (optional) logger.configure( level="DEBUG", # Change minimum log level color=True, # Enable colors show_time=True # Show timestamps ) logger.debug("Debug messages now visible") ``` -------------------------------- ### Full Logly usage example (Python) Source: https://muhammad-fiaz.github.io/logly/quickstart Shows a complete application flow using Logly: configuring the global logger, adding sinks, logging messages at various levels, handling exceptions, and cleaning up. This serves as a reference implementation for typical logging needs. ```Python from logly import logger def main(): # Configure logger.configure(level="INFO", color=True) # Add sinks .add("console") logger.add("logs/app.log", rotation="daily", retention=7) # Log messages logger.info("Application starting", version="1.0.0") try: # Your application logic process_data() logger.success("Processing complete") except Exception as e: logger.exception("Application error") raise finally: # Cleanup logger.complete() def process_data(): logger.debug("Processing data", records=1000) # ... processing logic ... logger.info("Data processed successfully") if __name__ == "__main__": main() ``` -------------------------------- ### Logly Log Levels (Python) Source: https://muhammad-fiaz.github.io/logly/guides/getting-started Illustrates the use of different log levels provided by Logly. These levels allow categorizing messages from detailed debugging information to critical errors. ```python logger.debug("Detailed debug information") logger.info("General information") logger.warning("Warning messages") logger.error("Error messages") logger.critical("Critical errors") ``` -------------------------------- ### Install Rust toolchain for source builds Source: https://muhammad-fiaz.github.io/logly/installation Installs the Rust toolchain required for building Logly from source with maturin. ```bash curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh ``` -------------------------------- ### Logly Production Configuration (Python) Source: https://muhammad-fiaz.github.io/logly/guides/getting-started Presents a robust configuration for production environments, utilizing environment variables for log level, a detailed message format including file and line number, and advanced file sink options like rotation and retention. ```python import os from logly import logger # Production configuration logger.configure( level=os.getenv("LOG_LEVEL", "INFO"), format="{time} | {level} | {file}:{line} | {message}", sinks=[ { "type": "console", "level": "INFO" }, { "type": "file", "path": "/var/log/app.log", "level": "DEBUG", "rotation": "100 MB", "retention": "30 days" } ] ) ``` -------------------------------- ### Logger anti-patterns (Python) Source: https://muhammad-fiaz.github.io/logly/quickstart Examples of improper logger usage including security risks, performance issues, and configuration mistakes to avoid. ```Python # 1. Don't log sensitive data logger.info("Login attempt", password=password) # ❌ Security risk # 2. Don't log in tight loops without filtering for i in range(1000000): logger.debug(f"Iteration {i}") # ❌ Performance hit # 3. Don't forget cleanup # ... logging ... # (missing logger.complete()) # ❌ Buffered logs may be lost # 4. Don't use string concatenation logger.info("User " + user + " logged in") # ❌ Use structured logging instead # 5. Don't configure multiple times logger.configure(level="INFO") logger.configure(level="DEBUG") # ❌ Configure once ``` -------------------------------- ### Logly Extra Data Logging (Python) Source: https://muhammad-fiaz.github.io/logly/guides/getting-started Demonstrates how to add extra key-value pairs to log messages in Logly. This is useful for including contextual information like request details, status codes, or response times. ```python logger.info("Request processed", method="POST", url="/api/users", status_code=200, response_time=0.145) ``` -------------------------------- ### Install Logly on Windows Source: https://muhammad-fiaz.github.io/logly/installation Platform-specific installation commands for Windows systems. Upgrades pip before installing Logly. ```bash python -m pip install --upgrade pip pip install logly ``` -------------------------------- ### Create project with uv and add Logly Source: https://muhammad-fiaz.github.io/logly/installation Initializes a new project with uv package manager and adds Logly as a dependency. ```bash # Create project with uv uv init myproject cd myproject # Add logly uv add logly # Run application uv run python app.py ``` -------------------------------- ### Install Logly from source with uv Source: https://muhammad-fiaz.github.io/logly/installation Installs Logly in development mode from source using uv package manager. Requires Git and Python 3.10+. ```bash # Clone repository git clone https://github.com/muhammad-fiaz/logly.git cd logly # Install with uv (recommended) uv pip install -e . ``` -------------------------------- ### Logger best practices (Python) Source: https://muhammad-fiaz.github.io/logly/quickstart Demonstrates proper logger usage including cleanup, appropriate log levels, context binding, and one-time configuration. ```Python # 1. Always call complete() before exit logger.complete() # 2. Use appropriate log levels logger.error("Connection failed", retry=3) # Error condition logger.info("User logged in", user="alice") # Normal info # 3. Include context request_logger = logger.bind(request_id=req_id) request_logger.info("Processing") # 4. Configure once at startup logger.configure(level="INFO", json=True) logger.add("console") logger.add("logs/app.log", rotation="daily") ``` -------------------------------- ### Clone repository and install dependencies Source: https://muhammad-fiaz.github.io/logly/guides/development Uses git to clone the Logly repository and sets up the Python and Rust environments. The commands install Python packages via uv and compile the Rust backend with cargo. Finally, a quick import test verifies the installation. ```bash git clone https://github.com/muhammad-fiaz/logly.git cd logly uv sync --dev cargo build uv run python -c "import logly; print('Logly installed successfully!')" ``` -------------------------------- ### Create virtual environment with venv Source: https://muhammad-fiaz.github.io/logly/installation Creates and activates a Python virtual environment using venv, then installs Logly. ```bash # Create virtual environment python -m venv venv # Activate (Windows) venv\Scripts\activate # Activate (Unix/macOS) source venv/bin/activate # Install logly pip install logly ``` -------------------------------- ### Install logly with verbose output Source: https://muhammad-fiaz.github.io/logly/guides/troubleshooting Installs the Logly package with detailed output, which can help diagnose installation problems by showing more information during the process. This is a command-line operation. ```bash pip install logly -v ``` -------------------------------- ### Logly Bug Reporting Example Source: https://muhammad-fiaz.github.io/logly/guides/troubleshooting Demonstrates the required format for reporting bugs with Logly, including version information, OS details, and a minimal code example that reproduces the issue. ```python from logly import logger logger.add("app.log") logger.info("Test") logger.complete() ``` -------------------------------- ### Multi-Process Logger Setup Source: https://muhammad-fiaz.github.io/logly/guides/production-deployment Begins setup for logging in multi-process applications using the os module. Requires os module; inputs depend on further implementation; outputs vary; limitations include incomplete snippet for full multi-process handling. ```python import os ``` -------------------------------- ### Verify Logly installation with basic logging Source: https://muhammad-fiaz.github.io/logly/installation Tests Logly installation by importing the logger and outputting a test message. Auto-configures on import since v0.1.5. ```python from logly import logger # NEW in v0.1.5: No configuration needed! logger.info("Logly installed successfully!") # ✅ Works immediately logger.complete() ``` -------------------------------- ### Install Logly with Pipenv Source: https://muhammad-fiaz.github.io/logly/installation Installs Logly in a Pipenv-managed environment. Requires pipenv to be installed. ```bash pipenv install logly ``` -------------------------------- ### Docker Compose for Logly installation Source: https://muhammad-fiaz.github.io/logly/installation Docker Compose configuration for installing Logly with volume mounting for logs directory. ```yaml version: '3.8' services: app: image: python:3.12-slim volumes: - ./:/app - ./logs:/app/logs working_dir: /app command: > sh -c "pip install logly && python app.py" ``` -------------------------------- ### Debug log format example for Logly (Python) Source: https://muhammad-fiaz.github.io/logly/quickstart Illustrates the standardized structure of Logly's internal debug log entries, including timestamps, log level, component tags, and messages. This format helps developers quickly parse and understand logged events. ```Python [2025-01-15T10:30:15.123456+00:00] [LOGLY-INFO] [init] Logger initialized with default settings [2025-01-15T10:30:15.234567+00:00] [LOGLY-INFO] [configure] level=INFO [2025-01-15T10:30:15.345678+00:00] [LOGLY-INFO] [configure] color=true [2025-01-15T10:30:15.456789+00:00] [LOGLY-INFO] [add] Adding sink: console [2025-01-15T10:30:15.567890+00:00] [LOGLY-INFO] [sink] Sink created: id=1, path=console ``` -------------------------------- ### Install Logly with user permissions Source: https://muhammad-fiaz.github.io/logly/installation Installs Logly with user permissions to avoid permission errors on Unix systems. ```bash # Use --user flag pip install --user logly # Or use sudo (not recommended) sudo pip install logly ``` -------------------------------- ### Install Logly on macOS Source: https://muhammad-fiaz.github.io/logly/installation Platform-specific installation commands for macOS systems. Uses python3 and pip3 executables. ```bash python3 -m pip install --upgrade pip pip3 install logly ``` -------------------------------- ### Complete Logly setup and scoped request handling example (Python) Source: https://muhammad-fiaz.github.io/logly/api-reference/context Provides a full end‑to‑end example: configuring Logly, adding handlers, creating a bound logger with global context, using contextualize for per‑request data, and handling errors with detailed logging. Demonstrates best practices for real‑world services. ```python from logly import logger # Configure logger.configure(level="INFO", json=True) logger.add("console") logger.add("logs/app.log") # Global context with bind() service_logger = logger.bind( service="api", version="1.0.0", environment="production" ) def handle_request(request_id: str, user_id: str): # Scoped context with contextualize() with service_logger.contextualize(request_id=request_id, user_id=user_id): service_logger.info("Request received") try: result = process_request() service_logger.success("Request succeeded", duration_ms=42) return result except Exception as e: # Include exception details service_logger.error("Request failed", error=str(e), error_type=type(e).__name__) raise # Usage handle_request("req-123", "alice") # Cleanup logger.complete() ``` -------------------------------- ### Logly Contextual Logging (Python) Source: https://muhammad-fiaz.github.io/logly/guides/getting-started Shows how to add persistent and temporary context to Logly messages. Persistent context (using `bind`) applies to all subsequent logs, while temporary context (using `contextualize`) is scoped to a `with` block. ```python from logly import logger # Set up logging logger.configure( level="INFO", format="{time} | {level} | {context} | {message}" ) # Add persistent context logger.bind(user_id=12345, session_id="abc-123") logger.info("User authentication started") logger.info("Credentials validated") # Temporary context for specific operations with logger.contextualize(request_id="req-456"): logger.info("Processing request") logger.info("Request completed") logger.info("Session ended") ``` -------------------------------- ### Build Logly in development mode with maturin Source: https://muhammad-fiaz.github.io/logly/installation Builds and installs Logly in development mode using maturin. Includes running tests. Requires Rust 1.70+ and maturin. ```bash # Clone repository git clone https://github.com/muhammad-fiaz/logly.git cd logly # Install maturin pip install maturin # Build in development mode maturin develop # Run tests pytest ``` -------------------------------- ### Setup web application request context Source: https://muhammad-fiaz.github.io/logly/examples/context-binding Example of setting up request-level context in a Flask web application. Context includes request ID, user agent, IP address, HTTP method, and path. Context is bound at the start of each request and available throughout request processing. ```python from flask import request, g from logly import logger def setup_request_logging(): """Setup context for each web request""" logger.bind( request_id=request.headers.get('X-Request-ID', 'unknown'), user_agent=request.headers.get('User-Agent'), ip=request.remote_addr, method=request.method, path=request.path ) @app.before_request def before_request(): setup_request_logging() logger.info("Request started") @app.after_request def after_request(response): logger.info("Request completed", status=response.status_code, size=len(response.data)) return response ``` -------------------------------- ### Build Logly release with maturin Source: https://muhammad-fiaz.github.io/logly/installation Builds and installs Logly release version using maturin. Requires Rust 1.70+ and maturin. ```bash # Clone repository git clone https://github.com/muhammad-fiaz/logly.git cd logly # Install maturin pip install maturin # Build wheel maturin build --release # Install wheel pip install target/wheels/logly-*.whl ``` -------------------------------- ### Install Logly from PyPI with pip Source: https://muhammad-fiaz.github.io/logly/installation Installs Logly using the standard pip package manager. Requires Python 3.10 or higher and latest pip version. ```bash pip install logly ``` -------------------------------- ### Auto-start logging with Logly Source: https://muhammad-fiaz.github.io/logly/quickstart Import and start logging immediately without configuration. Logly auto-configures on import with console sink enabled and global logging active. Supports multiple log levels with color coding: info (white), success (green), warning (yellow), error (red), fail (magenta). ```python # Just import and log - it works automatically! from logly import logger logger.info("Hello, Logly!") # ✅ Logs appear immediately (white) logger.success("Task completed!") # ✅ Green color logger.warning("This works right away!") # ✅ Yellow color logger.error("Connection failed!") # ✅ Red color logger.fail("Login failed!") # ✅ NEW: Magenta color # Logs appear automatically because: # - Auto-configure runs on import # - auto_sink=True creates console sink automatically # - console=True enables logging globally ``` -------------------------------- ### Upgrade pip, setuptools, and wheel Source: https://muhammad-fiaz.github.io/logly/guides/troubleshooting Ensures you have the latest versions of essential Python packaging tools, which can resolve installation issues. This is a command-line operation. ```bash pip install --upgrade pip setuptools wheel ``` -------------------------------- ### Complete Logly Callback Example in Python Source: https://muhammad-fiaz.github.io/logly/api-reference/callbacks A comprehensive example showing multiple callbacks for Slack notifications, metrics collection, and custom alerting. Includes setup, usage, and cleanup. ```python from logly import logger import aiohttp import asyncio # Configure logger.configure(level="INFO", json=True) logger.add("console") logger.add("logs/app.log") # Callback 1: Slack notifications for errors def slack_callback(record: dict): if record["level"] in ["ERROR", "CRITICAL"]: # Note: In real code, use requests or similar for HTTP calls print(f"Would send to Slack: 🚨 {record['level']}: {record['message']}") # Callback 2: Metrics collection log_counts = {"INFO": 0, "ERROR": 0} def metrics_callback(record: dict): level = record["level"] if level in log_counts: log_counts[level] += 1 # Callback 3: Custom alerting error_threshold = 5 def alert_callback(record: dict): if record["level"] == "ERROR": if log_counts["ERROR"] >= error_threshold: print(f"🚨 ALERT: {error_threshold} errors detected!") # Register callbacks slack_id = logger.add_callback(slack_callback) metrics_id = logger.add_callback(metrics_callback) alert_id = logger.add_callback(alert_callback, name="alerting") # Application code def main(): logger.info("Application started") # Simulate errors for i in range(10): logger.error(f"Error {i}", error_code=i) # Print metrics print(f"Final counts: {log_counts}") # Cleanup logger.remove_callback(slack_id) logger.remove_callback(metrics_id) logger.remove_callback(alert_id) logger.complete() # Run main() ``` -------------------------------- ### Add Logly to Poetry project Source: https://muhammad-fiaz.github.io/logly/installation Adds Logly as a dependency to a Poetry-managed project. Requires poetry to be installed. ```bash poetry add logly ``` -------------------------------- ### Create Conda environment for Logly Source: https://muhammad-fiaz.github.io/logly/installation Creates and activates a Conda environment with Python 3.12, then installs Logly. ```bash # Create conda environment conda create -n myproject python=3.12 # Activate environment conda activate myproject # Install logly pip install logly ``` -------------------------------- ### Install Logly with uv package manager Source: https://muhammad-fiaz.github.io/logly/installation Installs Logly using the uv package manager for faster dependency resolution. Requires Python 3.10 or higher. ```bash uv pip install logly ``` -------------------------------- ### Install specific logly version Source: https://muhammad-fiaz.github.io/logly/guides/troubleshooting Installs a particular version of the Logly package, useful for ensuring compatibility or rolling back to a known stable version. This is a command-line operation. ```bash pip install logly==0.1.5 ``` -------------------------------- ### Clean and rebuild with maturin Source: https://muhammad-fiaz.github.io/logly/installation Cleans build artifacts and rebuilds Logly in release mode using maturin. ```bash cargo clean maturin develop --release ``` -------------------------------- ### Update maturin for source builds Source: https://muhammad-fiaz.github.io/logly/installation Upgrades maturin package required for building Logly from source. ```bash pip install --upgrade maturin ``` -------------------------------- ### Enable debug logging for troubleshooting (Python) Source: https://muhammad-fiaz.github.io/logly/quickstart Enables a previously disabled debug logging sink to capture detailed diagnostic information during troubleshooting sessions. ```Python logger.enable_sink(debug_log_id) logger.debug("Detailed diagnostics") # → all three sinks ``` -------------------------------- ### Complete Python 3.14 + Logly Example Source: https://muhammad-fiaz.github.io/logly/guides/python-3 This code provides a full example demonstrating Python 3.14 features with Logly. It includes initializing a processor with context-bound logging, setting up multiple log sinks using `pathlib`, performing parallel processing with `InterpreterPoolExecutor`, and inspecting class annotations. Dependencies include `logly` and `annotationlib`. ```python #!/usr/bin/env python3.14 """Complete demo: Python 3.14 features with Logly logging.""" from __future__ import annotations from pathlib import Path from uuid import uuid7 from datetime import datetime from concurrent.futures import InterpreterPoolExecutor from logly import logger import annotationlib class DataProcessor: """Process data with full Python 3.14 + Logly integration.""" next: DataProcessor | None = None # PEP 649: no quotes needed def __init__(self, name: str): self.name = name self.request_id = uuid7() # UUID7 for tracking # Bind context self.logger = logger.bind( processor=name, request_id=str(self.request_id) ) self.logger.info("Processor initialized") def process(self, data: list[int]) -> dict: """Process data with comprehensive logging.""" self.logger.info("Processing started", items=len(data)) try: # Simulate processing result = sum(data) self.logger.success("Processing completed", result=result) return {"sum": result, "count": len(data)} except ValueError, TypeError: # Python 3.14 syntax self.logger.error("Invalid data type") return {"error": "Invalid data"} except Exception as e: self.logger.critical("Unexpected error", error=str(e), exception=True) return {"error": str(e)} def setup_logging(): """Configure logging with Python 3.14 pathlib features.""" logger.configure(level="DEBUG", color=True) # Use pathlib to manage log directory log_dir = Path("logs") log_dir.mkdir(exist_ok=True) # Add sinks with time format specs logger.add( str(log_dir / "app.log"), format="{time:YYYY-MM-DD HH:mm:ss.SSS} | {level:8} | {message}", rotation="daily" ) logger.add( str(log_dir / "requests.log"), format="{time:YYYY-MM-DDTHH:mm:ss} | {request_id} | {processor} | {message}", filter_min_level="INFO" ) logger.info("Logging configured", log_dir=str(log_dir)) def parallel_processing(): """Demonstrate InterpreterPoolExecutor with isolated loggers.""" logger.info("Starting parallel processing") def worker(data: list[int]) -> dict: from logly import logger processor = DataProcessor(f"Worker-{data[0]}") return processor.process(data) datasets = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] with InterpreterPoolExecutor(max_workers=3) as executor: futures = [executor.submit(worker, data) for data in datasets] results = [f.result() for f in futures] logger.info("Parallel processing completed", total_results=len(results)) return results def inspect_annotations_demo(): """Demonstrate PEP 649 annotation inspection.""" annotations = annotationlib.get_annotations( DataProcessor, format=annotationlib.Format.VALUE ) logger.debug("Class annotations inspected", annotations=str(annotations)) def main(): """Main entry point.""" print("=== Python 3.14 + Logly Demo ===\n") # Setup setup_logging() # Demo deferred annotations inspect_annotations_demo() # Demo single processor processor = DataProcessor("MainProcessor") result = processor.process([10, 20, 30]) logger.info("Single processing result", **result) # Demo parallel processing results = parallel_processing() # Cleanup logger.complete() print("\nDemo complete! Check logs/ directory for output files.") if __name__ == "__main__": main() ``` -------------------------------- ### Build optimized wheel and install Source: https://muhammad-fiaz.github.io/logly/guides/development Creates a release-optimized Python wheel using maturin and then installs the resulting package from the built wheels directory. This process yields a high-performance distribution ready for deployment. It is typically used in CI pipelines for production releases. ```bash # Build optimized wheel for production uv run maturin build --release # Install optimized wheel pip install target/wheels/*.whl ``` -------------------------------- ### Batch Processing Progress Logging with Logly Source: https://muhammad-fiaz.github.io/logly/quickstart Implements batch processing with detailed progress logging. Uses contextual binding for batch tracking, logs progress for each item, handles exceptions with contextual information, and provides success/failure tracking with duration metrics. ```python from logly import logger import time def process_batch(batch_id, items): batch_logger = logger.bind(batch_id=batch_id) batch_logger.info("Batch started", items=len(items)) for idx, item in enumerate(items): with batch_logger.contextualize(item_id=item.id): try: # Process item process_item(item) batch_logger.debug("Item processed", progress=f"{idx+1}/{len(items)}") except Exception: batch_logger.exception("Item failed") batch_logger.success("Batch complete", duration=time.time()) def main(): logger.configure(level="INFO") logger.add("console") logger.add("logs/batch.log", rotation="daily") batches = get_batches() for batch_id, items in enumerate(batches): process_batch(batch_id, items) logger.complete() if __name__ == "__main__": main() ``` -------------------------------- ### Install and configure pre-commit hooks Source: https://muhammad-fiaz.github.io/logly/guides/development Installs the pre-commit package and sets up hooks that automatically enforce code style and quality checks before each commit. This ensures that linting, formatting, and other validations run locally, reducing CI failures. The hook configuration is defined in the project's .pre-commit-config.yaml file. ```bash pip install pre-commit pre-commit install ``` -------------------------------- ### Install and Basic Logging in Notebooks Source: https://muhammad-fiaz.github.io/logly/examples/jupyter-colab Demonstrates how to install the Logly library using pip within a notebook environment and perform basic logging operations (info, success, warning, error). This is the foundational usage for getting started with Logly in notebooks. ```python # Install in notebook (if needed) !pip install logly # Import and start logging immediately from logly import logger logger.info("Starting data analysis") logger.success("Data loaded successfully") logger.warning("Missing values detected") logger.error("Invalid data format") ``` -------------------------------- ### Logly File Logging Configuration (Python) Source: https://muhammad-fiaz.github.io/logly/guides/getting-started Configures Logly to write logs to both the console and a file. It specifies a custom format and defines a file sink named 'app.log'. ```python from logly import logger logger.configure( level="INFO", format="{time} | {level} | {message}", sinks=[ { "type": "console" # Keep console logging }, { "type": "file", "path": "app.log" # Log to file } ] ) logger.info("This goes to both console and file") ``` -------------------------------- ### Build and serve documentation with MkDocs Source: https://muhammad-fiaz.github.io/logly/guides/development Builds the project's documentation site locally and serves it for interactive development. Additionally, command is provided to deploy the site to GitHub Pages, assuming appropriate permissions. MkDocs reads the mkdocs.yml configuration to generate the static site. ```bash # Build docs locally uv run mkdocs build # Serve docs locally for development uv run mkdocs serve # Deploy docs (requires proper permissions) uv run mkdocs gh-deploy ``` -------------------------------- ### Logly Exception Handling with @catch (Python) Source: https://muhammad-fiaz.github.io/logly/guides/getting-started Demonstrates using the `@catch` decorator provided by Logly to automatically log exceptions raised within a function. It allows specifying the log level and a custom message for the exception log. ```python from logly import logger, catch logger.configure(level="INFO") @catch(level="ERROR", message="Function failed") def risky_operation(): raise ValueError("Something went wrong!") # This will log the error automatically result = risky_operation() ``` -------------------------------- ### Verify logly installation Source: https://muhammad-fiaz.github.io/logly/guides/troubleshooting Checks if the Logly package is installed and shows its details. This helps confirm installation success and identify the installed version. These are command-line operations. ```bash pip show logly ``` ```bash pip list | grep logly ``` -------------------------------- ### FastAPI HTTP Request Logging with Logly Source: https://muhammad-fiaz.github.io/logly/quickstart Implements structured HTTP request logging for FastAPI applications. Configures JSON logging with console and file outputs, sets up middleware for request/response tracking, and binds request context for detailed logging. ```python # Configure once at startup @app.on_event("startup") async def setup_logging(): logger.configure(level="INFO", json=True) logger.add("console") logger.add("logs/api.log", rotation="hourly", retention=24) # Log requests @app.middleware("http") async def log_requests(request: Request, call_next): request_logger = logger.bind( request_id=request.headers.get("X-Request-ID", "unknown"), method=request.method, path=request.url.path ) request_logger.info("Request received") response = await call_next(request) request_logger.info("Response sent", status=response.status_code) return response @app.get("/api/users/{user_id}") async def get_user(user_id: int): logger.info("Fetching user", user_id=user_id) # ... fetch user logic ... return {"user_id": user_id, "name": "Alice"} ``` -------------------------------- ### Logly: Get Log File Size In Bytes Source: https://muhammad-fiaz.github.io/logly/api-reference/file-operations Retrieves the size of a log file in bytes. It returns an integer representing the file size or None if the file does not exist. The function also provides an example of converting bytes to kilobytes and megabytes for readability. ```python from logly import logger id = logger.add("app.log") logger.info("Hello world!") size = logger.file_size(id) print(f"File size: {size} bytes") # Convert to human-readable if size: kb = size / 1024 mb = kb / 1024 print(f"File size: {mb:.2f} MB") ``` -------------------------------- ### Python Logly: Email Notification Templates with T-Strings Source: https://muhammad-fiaz.github.io/logly/guides/python-3 Demonstrates the setup for using t-strings with Logly in Python 3.14 for email notification logging. This example shows the initial configuration of Logly and the definition of templates, setting the stage for logging notification events. ```python #!/usr/bin/env python3.14 """Using t-strings for email notification logging.""" from logly import logger # Configure Logly logger.configure(level="INFO") logger.add("notifications.log") ``` -------------------------------- ### Complete Example with Callbacks Source: https://muhammad-fiaz.github.io/logly/api-reference/callbacks A comprehensive example demonstrating the configuration of Logly, adding multiple callbacks for different purposes (Slack notifications, metrics, alerting), simulating log events, and then removing the callbacks. ```APIDOC ## Complete Logly Callback Example ### Description This example showcases a full integration of Logly, including configuration, adding multiple distinct callbacks, generating log messages (including errors), and finally cleaning up by removing the registered callbacks. ### Code ```python from logly import logger import aiohttp # Note: Example uses print for simplicity, real HTTP calls would use libraries like aiohttp or requests import asyncio # Configure logger logger.configure(level="INFO", json=True) logger.add("console") # Add console handler logger.add("logs/app.log") # Add file handler # --- Callback Definitions --- # Callback 1: Slack notifications for errors def slack_callback(record: dict): if record["level"] in ["ERROR", "CRITICAL"]: # In a real application, use a library like 'requests' or 'aiohttp' to send an HTTP POST request to Slack. print(f"Would send to Slack: 🚨 {record['level']}: {record['message']}") # Callback 2: Metrics collection log_counts = {"INFO": 0, "ERROR": 0} def metrics_callback(record: dict): level = record["level"] if level in log_counts: log_counts[level] += 1 # Callback 3: Custom alerting based on error count error_threshold = 5 def alert_callback(record: dict): if record["level"] == "ERROR": # This callback relies on the metrics_callback having updated log_counts if log_counts.get("ERROR", 0) >= error_threshold: print(f"🚨 ALERT: {error_threshold} errors detected!") # --- Register Callbacks --- # Registering callbacks and storing their IDs slack_id = logger.add_callback(slack_callback) metrics_id = logger.add_callback(metrics_callback) alert_id = logger.add_callback(alert_callback, name="alerting") # Example with a specific name # --- Application Logic --- def main(): logger.info("Application started") # Simulate generating log messages, including errors for i in range(10): logger.error(f"Error {i}", error_code=i) if i == 4: logger.info("Reached important milestone") # Print collected metrics after logging print(f"Final log counts: {log_counts}") # --- Cleanup --- # Remove registered callbacks to prevent further execution logger.remove_callback(slack_id) logger.remove_callback(metrics_id) logger.remove_callback(alert_id) # Ensure all buffered logs are flushed and handlers are closed logger.complete() # --- Execution --- if __name__ == "__main__": main() ``` ### Expected Output (Illustrative) ``` 2025-01-15 10:30:45 | INFO | Application started 2025-01-15 10:30:45 | ERROR | Error 0 error_code=0 ... 2025-01-15 10:30:45 | ERROR | Error 4 error_code=4 Would send to Slack: 🚨 ERROR: Error 4 2025-01-15 10:30:45 | INFO | Reached important milestone ... 2025-01-15 10:30:46 | ERROR | Error 9 error_code=9 Would send to Slack: 🚨 ERROR: Error 9 🚨 ALERT: 5 errors detected! Final log counts: {'INFO': 2, 'ERROR': 10} ``` ### Notes - The `slack_callback` triggers for errors. The `alert_callback` triggers only after the 5th error is logged, demonstrating dependency on metrics. - `logger.complete()` is called at the end to ensure graceful shutdown and flushing of logs. ``` -------------------------------- ### Configure Logly with custom settings Source: https://muhammad-fiaz.github.io/logly/quickstart Customize Logly configuration after import. Set logging level, enable/disable colored output, control global console logging, and manage automatic console sink creation. Configuration applies immediately and affects all subsequent logging calls. ```python from logly import logger # Configure logging level and output format (optional) logger.configure( level="INFO", # Minimum log level (default: "INFO") color=True, # Colored output for console (default: True) console=True, # Global enable/disable ALL logging (default: True) auto_sink=True # Auto-create console sink (default: True) ) # Start logging with your custom config logger.info("Logging with custom configuration") ``` -------------------------------- ### Check Logly version information Source: https://muhammad-fiaz.github.io/logly/installation Retrieves the installed version of Logly by accessing the __version__ attribute. ```python import logly print(logly.__version__) # e.g., "0.1.2" ``` -------------------------------- ### Log Levels and Filtering in Logly Source: https://muhammad-fiaz.github.io/logly/quickstart Demonstrates how to use different log levels (TRACE, DEBUG, INFO, SUCCESS, WARNING, ERROR, CRITICAL) with Logly and how to set a minimum level for filtering logs. Logs at the specified level and above are accepted. ```python # This sink captures INFO and everything more severe logger.add("app.log", filter_min_level="INFO") logger.debug("Not logged") # \u2717 Rejected (DEBUG < INFO) logger.info("Logged") # \u2713 Accepted (INFO >= INFO) logger.warning("Logged") # \u2713 Accepted (WARNING > INFO) logger.error("Logged") # \u2713 Accepted (ERROR > INFO) logger.critical("Logged") # \u2713 Accepted (CRITICAL > INFO) ``` ```python # Examples logger.trace("Function called", args={"x": 1, "y": 2}) logger.debug("Variable value", x=42) logger.info("User logged in", user="alice") logger.success("Payment processed", amount=99.99) logger.warning("API rate limit approaching", remaining=10) logger.error("Database connection failed", retry_count=3) logger.critical("System out of memory", available_mb=10) ``` -------------------------------- ### Complete Logly Example in Python Source: https://muhammad-fiaz.github.io/logly/api-reference/logging A comprehensive example of setting up Logly with configuration, multiple log levels, and cleanup. Depends on the Logly library; inputs include log messages and fields, with outputs to console and file in various formats. Demonstrates conditional logging and rotation; limited by file system permissions for logging. ```python from logly import logger # Configure logger.configure(level="DEBUG", color=True) logger.add("console") logger.add("logs/app.log", rotation="daily") # All log levels logger.trace("Trace message", detail="very verbose") logger.debug("Debug message", x=42) logger.info("Info message", user="alice") logger.success("Success message", task="complete") logger.warning("Warning message", threshold=90) logger.error("Error message", retry_count=3) logger.critical("Critical message", status="failed") # Runtime level level = "ERROR" if error_condition else "INFO" logger.log(level, "Conditional logging") # Cleanup logger.complete() ``` -------------------------------- ### Bug reproduction steps with Logly debugging (Python) Source: https://muhammad-fiaz.github.io/logly/quickstart Provides two code snippets to capture detailed logs for GitHub issue reports: first creates a logger with debugging enabled, then reproduces the problem by adding a sink and emitting a log message. The generated log file can be attached to the issue. ```Python from logly import logger # Create a logger with debug mode enabled debug_logger = logger(internal_debug=True, debug_log_path="logly_debug.log") ``` ```Python # Your code that causes the problem debug_logger.add("test.log", rotation="daily") debug_logger.info("Test message") ``` -------------------------------- ### Create Log Directories with Permissions Source: https://muhammad-fiaz.github.io/logly/guides/production-deployment Sets up log directories with appropriate permissions for secure logging in production. Requires sudo access; inputs are directory paths and ownership; outputs are created directories with set ownership and permissions; limitations include needing administrative rights and filesystem support. ```shell # Create log directories sudo mkdir -p /var/log/app sudo chown appuser:appgroup /var/log/app sudo chmod 755 /var/log/app # For high-security environments sudo chmod 700 /var/log/app # Owner only ``` -------------------------------- ### Install logly without cache Source: https://muhammad-fiaz.github.io/logly/guides/troubleshooting Installs the Logly package, bypassing the pip cache. This can resolve issues where a corrupted cached package prevents a successful installation. This is a command-line operation. ```bash pip install --no-cache-dir logly ``` -------------------------------- ### Basic Multi-Sink Setup in Logly (Python) Source: https://muhammad-fiaz.github.io/logly/examples/multi-sink This configuration sets up Logly to log to console (INFO+), a rotating text file (DEBUG+), and a JSON file (WARNING+), demonstrating independent filtering per sink and varied formats. It requires the logly library and tests logs at different levels, with outputs directed based on filters. Limitations include dependency on Logly installation and manual completion call. ```python from logly import logger # Configure global settings logger.configure(level="DEBUG") # Sink 1: Console - only INFO and above logger.add("console", filter_min_level="INFO") # Sink 2: Text file - all logs with rotation logger.add( "app.log", filter_min_level="DEBUG", rotation="daily", retention=7 ) # Sink 3: JSON file - only warnings and errors logger.add( "errors.json", filter_min_level="WARNING", pretty_json=True ) # Test logging at different levels logger.debug("Debug message - only in app.log") logger.info("Info message - console and app.log") logger.warning("Warning - all three sinks") logger.error("Error - all three sinks", error_code="E500") logger.complete() ``` -------------------------------- ### Log Formatting Examples Source: https://muhammad-fiaz.github.io/logly/guides/configuration Demonstrates various log message formatting options, including custom fields, extra fields, and caller information. It also shows how to use JSON formatting for structured logging. ```python format="{time} [{level}] {message} | user={user_id}" format="{time} [{level}] {message} | {extra}" format="{time} [{level}] {filename}:{lineno} - {message}" import json format=json.dumps({ "timestamp": "{time}", "level": "{level}", "message": "{message}", "extra": "{extra}" }) ``` -------------------------------- ### Monitor Log File Growth with Logly Source: https://muhammad-fiaz.github.io/logly/examples/file-operations This Python code snippet demonstrates how to monitor log file growth and retrieve real-time statistics using the Logly library. It shows how to get the initial and final file sizes, calculate the growth, and access detailed file metadata and entry counts. Ensure the 'logly' library is installed. ```python import logly import time logger = logly.Logger() sink_id = logger.add("app.log") # Initial state initial_size = logger.file_size(sink_id) print(f"Initial log size: {initial_size} bytes") # Write some logs for i in range(50): logger.info(f"Processing record {i}") time.sleep(0.1) # Check growth final_size = logger.file_size(sink_id) growth = final_size - initial_size print(f"Log grew by {growth} bytes ({final_size} total)") # Get full metadata metadata = logger.file_metadata(sink_id) print(f"\nLog File Information:") print(f" Path: {metadata['path']}") print(f" Created: {metadata['created']}") print(f" Modified: {metadata['modified']}") print(f" Size: {metadata['size']} bytes") # Count entries count = logger.line_count(sink_id) print(f" Total entries: {count}") ``` -------------------------------- ### Common Logly Setup Patterns Source: https://muhammad-fiaz.github.io/logly/api-reference/configuration Provides examples of common logger configurations for different environments, such as development and production. These patterns demonstrate how to combine various settings like rotation, retention, and filtering for effective log management. ```python # Development logger.add("console") logger.add("logs/dev.log", rotation="daily", retention=3) # Production logger.add("console") logger.add("logs/app.log", rotation="daily", size_limit="500MB", retention=30) logger.add("logs/errors.log", filter_min_level="ERROR", retention=90) ``` -------------------------------- ### Python: Use Specific Python Interpreter Source: https://muhammad-fiaz.github.io/logly/guides/troubleshooting Install and run your application using a specific Python interpreter version. This is useful when you have multiple Python versions installed and need to ensure compatibility. ```python python3.10 -m pip install logly python3.10 app.py ``` -------------------------------- ### Migrate from Python logging to Logly Source: https://muhammad-fiaz.github.io/logly/changelog Shows equivalent Logly setup for Python's standard logging. Requires explicit sink configuration and cleanup. Outputs to console by default. ```Python import logging logging.basicConfig(level=logging.INFO) logging.info("Hello") ``` ```Python from logly import logger logger.configure(level="INFO") logger.add("console") logger.info("Hello") ``` -------------------------------- ### Uninstall Logly package Source: https://muhammad-fiaz.github.io/logly/installation Removes Logly package from the current Python environment. ```bash pip uninstall logly ``` -------------------------------- ### Install Logly with pip or uv Source: https://muhammad-fiaz.github.io/logly/guides/python-3 Installs the Logly package and verifies Python version. Supports pip and uv package managers. Run these commands in a terminal with Python 3.14. ```Bash # Using pip pip install logly # Using uv (recommended) uv pip install logly # Verify Python version python --version # Should show Python 3.14.x ``` -------------------------------- ### Setup Logging Early with Error Handling in Python Source: https://muhammad-fiaz.github.io/logly/guides/error-handling Provides a best practice for setting up logging at application startup, including a try-except block to catch and report `ValueError` during configuration. This ensures logging is functional from the start. ```python from logly import logger def setup_logging(): """Configure logging at application startup.""" try: logger.configure( level="INFO", color=True, console=True ) logger.add( "logs/app.log", rotation="daily", retention=7 ) except ValueError as e: print(f"Logging configuration error: {e}") raise return logger # At application startup logger = setup_logging() ``` -------------------------------- ### Use Valid Format Placeholders (Python) Source: https://muhammad-fiaz.github.io/logly/guides/troubleshooting This snippet demonstrates how to use valid format placeholder within the logger configuration. It shows examples of valid placeholders and highlights incorrect syntax with a failing example. ```Python # Valid placeholders logger.add("app.log", format="{time} [{level}] {message}") logger.add("app.log", format="{time} | {level:8} | {module}:{function} | {message}") # Available placeholders: # {time} - Timestamp # {level} - Log level # {message} - Log message # {module} - Module name # {function} - Function name # {extra} - Extra fields ``` ```Python # ✗ Missing closing brace logger.add("app.log", format="{time [{level}] {message}") # ✓ Correct logger.add("app.log", format="{time} [{level}] {message}") ``` -------------------------------- ### Conditional Sink Disabling Examples Source: https://muhammad-fiaz.github.io/logly/guides/configuration Provides practical examples of using `disable_sink` for common scenarios like production mode, performance tuning, and user preference control, illustrating dynamic log routing. ```python # Disable debug file in production if os.getenv("ENV") == "production": logger.disable_sink(debug_file_id) # Temporarily disable expensive sinks during critical operations logger.disable_sink(json_api_sink_id) process_critical_data() logger.enable_sink(json_api_sink_id) # Toggle console output based on user settings if not user_settings.get("show_logs"): logger.disable_sink(console_id) ```