### Quick Start: Initialize and Use Tamga Logger Source: https://tamga.vercel.app/index Demonstrates the simplest way to initialize the Tamga logger and log basic informational and success messages. This snippet shows the core setup for immediate use of the library. ```Python # Quick start from tamga import Tamga logger = Tamga() logger.info("Application started") logger.success("Task completed!") ``` -------------------------------- ### Install Tamga Python Logging Library with Options Source: https://tamga.vercel.app/index Provides various installation options for the Tamga Python logging library using pip, including basic installation and optional dependencies for specific features like MongoDB support, API logging, or a full feature set. ```Python pip install tamga # Basic installation pip install tamga[mongo] # With MongoDB support pip install tamga[api] # With API logging pip install tamga[full] # All features ``` -------------------------------- ### Perform Structured Logging with Tamga `dir()` Method Source: https://tamga.vercel.app/index Shows how to use Tamga's `dir()` method for structured logging, allowing key-value data to be associated with log entries. Includes examples for logging user actions, HTTP requests, and performance monitoring, demonstrating how to capture rich, analyzable data. ```Python # Structured Logging with key-value data from tamga import Tamga import time import uuid logger = Tamga() # Log with structured data logger.dir("User action", user_id="usr_123", action="login", ip_address="192.168.1.1", success=True, duration_ms=234 ) # Request logging example def log_request(request, response): request_id = str(uuid.uuid4()) logger.dir("HTTP Request", request_id=request_id, method=request.method, path=request.path, status=response.status_code, duration_ms=response.elapsed_ms, user_agent=request.headers.get('User-Agent'), ip=request.remote_addr ) # Performance monitoring start_time = time.time() # ... your code ... duration = time.time() - start_time logger.dir("Operation completed", operation="data_processing", records_processed=10000, duration_seconds=round(duration, 2), success_rate=0.997 ) ``` -------------------------------- ### Configuring Email Alerts for Critical Events Source: https://tamga.vercel.app/index This example demonstrates how to configure Tamga to send email notifications for specific log levels (CRITICAL, ERROR, MAIL). It covers SMTP server settings, recipient lists, and shows how to trigger emails asynchronously, including using the custom `logger.mail()` method for important business events. ```python from tamga import Tamga import os logger = Tamga( # Email configuration sendMail=True, smtpServer="smtp.gmail.com", smtpPort=587, smtpMail=os.getenv("SMTP_EMAIL"), smtpPassword=os.getenv("SMTP_PASSWORD"), smtpReceivers=["alerts@company.com", "oncall@company.com"], # Which levels trigger emails mailLevels=["CRITICAL", "ERROR", "MAIL"], ) # These trigger email notifications (async) logger.critical("Database server is down!") logger.error("Failed to process payment for user_123") logger.mail("New premium subscription: $299/month") # Using mail() for important business events logger.mail("Large order placed: $10,000") logger.mail("Suspicious login detected from new location") logger.mail("Daily backup completed successfully") # These DON'T trigger emails (not in mailLevels) logger.warning("Cache miss rate increasing") logger.info("Regular operation message") # Emails are sent asynchronously with beautiful HTML templates # Including syntax highlighting and timestamp information ``` -------------------------------- ### Configure Tamga Logger with Multiple Outputs and Log Levels Source: https://tamga.vercel.app/index Illustrates advanced configuration of the Tamga logger, enabling logging to file, JSON, and console with a specified buffer size. It showcases all available predefined log levels (info, warning, error, success, debug, critical, database, metric, trace, mail) and how to define custom log levels with specific colors. Also demonstrates forcing a flush of buffered logs. ```Python # Initialize with colored output from tamga import Tamga logger = Tamga( logToFile=True, logToJSON=True, logToConsole=True, bufferSize=50 # Buffer 50 logs before writing ) # All available log levels logger.info("Connected to database") # Sky blue logger.warning("High memory usage: 85%") # Amber logger.error("Connection failed") # Rose logger.success("Task completed") # Emerald logger.debug("Processing request #1234") # Indigo logger.critical("System overload!") # Red logger.database("Query executed: SELECT *") # Green logger.metric("Response time: 125ms") # Cyan logger.trace("Entering function: process()") # Gray logger.mail("Payment received: $99.99") # Triggers email if configured # Custom logging with your own color logger.custom("Deploy completed", "DEPLOY", "purple") logger.custom("Cache miss", "CACHE", "orange") # Force write buffered logs logger.flush() ``` -------------------------------- ### Asynchronous MongoDB Logging Integration Source: https://tamga.vercel.app/index This configuration showcases Tamga's asynchronous integration with MongoDB. It details how to set up logging directly to a MongoDB database, leveraging the `motor` driver for non-blocking operations, and highlights how logs are automatically enriched with metadata and indexed for fast queries. ```python from tamga import Tamga import os logger = Tamga( # MongoDB with async support logToMongo=True, mongoURI=os.getenv("MONGO_URI"), mongoDatabaseName="logs_db", mongoCollectionName="application_logs", # Also log to files logToFile=True, logToJSON=True, # Performance settings bufferSize=100, ) # MongoDB operations are non-blocking logger.info("User logged in") logger.error("Payment processing failed") # Logs are automatically stored with: # - level, message, date, time, timezone # - timestamp (Unix timestamp) # - Indexed for fast queries # The MongoDB integration uses motor (async driver) # Perfect for high-throughput applications ``` -------------------------------- ### Tamga Logger Log Levels Reference Source: https://tamga.vercel.app/index This section provides a comprehensive reference for all standard and custom log levels available in the Tamga logging library, along with their intended use cases. ```APIDOC logger.info() General information messages logger.warning() Warning messages logger.error() Error messages logger.success() Success messages logger.debug() Debug information logger.critical() Critical issues logger.database() Database operations logger.mail() Triggers email alerts logger.metric() Performance metrics logger.trace() Detailed trace info logger.dir() Structured key-value data logger.custom() Custom level & color ``` -------------------------------- ### Comprehensive Production Logging Configuration Source: https://tamga.vercel.app/index This snippet provides a robust Tamga configuration tailored for production environments. It integrates various logging destinations including console (conditional), file (with rotation), JSON, SQL, MongoDB, and external API logging, alongside critical email alerts and performance tuning for high-throughput applications. ```python from tamga import Tamga import os logger = Tamga( # Console only in development logToConsole=os.getenv("ENV") != "production", # File outputs with rotation logToFile=True, logFile="logs/app.log", maxLogSize=50, # Rotate at 50MB enableBackup=True, # Keep backups # JSON for log aggregation logToJSON=True, logJSON="logs/app.json", maxJsonSize=50, # Database logging logToSQL=True, logSQL="logs/app.db", maxSqlSize=100, # 100MB for SQL # Performance tuning bufferSize=200 if os.getenv("ENV") == "production" else 10, # Centralized logging logToMongo=bool(os.getenv("MONGO_URI")), mongoURI=os.getenv("MONGO_URI"), # API logging (e.g., to Elasticsearch) logToAPI=bool(os.getenv("LOG_API_URL")), apiURL=os.getenv("LOG_API_URL"), # Critical alerts sendMail=bool(os.getenv("SMTP_SERVER")), smtpServer=os.getenv("SMTP_SERVER"), smtpPort=587, smtpMail=os.getenv("SMTP_USER"), smtpPassword=os.getenv("SMTP_PASS"), smtpReceivers=["alerts@company.com"], mailLevels=["CRITICAL", "MAIL"], ) # Application lifecycle try: logger.info("Application starting") logger.dir("Environment loaded", env=os.getenv("ENV"), version=os.getenv("APP_VERSION"), workers=os.cpu_count() ) # Your application code logger.success("All services initialized") except Exception as e: logger.critical(f"Fatal startup error: {str(e)}") logger.flush() # Ensure critical error is written raise finally: logger.info("Shutting down gracefully") logger.flush() # Final flush before exit ``` -------------------------------- ### Configure Tamga for High-Performance Logging Throughput Source: https://tamga.vercel.app/index Demonstrates how to optimize Tamga for maximum logging throughput, particularly useful for background jobs or data processing. This configuration disables console output and uses a large buffer size for efficient batch operations, with periodic flushes to manage memory buildup. ```Python # High-Performance Configuration from tamga import Tamga # Optimize for maximum throughput logger = Tamga( logToFile=True, logToConsole=False, # Disable console for much faster performance bufferSize=1000 # Large buffer for batch operations ) # Process large dataset efficiently for i, record in enumerate(large_dataset): logger.info(f"Processing record {record.id}") # Periodic flush to prevent memory buildup if i % 10000 == 0: logger.flush() logger.success(f"Processed {i} records") ``` -------------------------------- ### Thread-Safe Concurrent Logging with Tamga Source: https://tamga.vercel.app/index This snippet demonstrates how to implement thread-safe logging using Tamga in a multi-threaded Python application. It shows how to create multiple worker threads that log concurrently and ensures all logs are flushed before the application exits. ```python import threading def worker(worker_id): for i in range(1000): logger.debug(f"Worker {worker_id}: Processing item {i}") # Safe concurrent logging threads = [ threading.Thread(target=worker, args=(i,)) for i in range(10) ] for t in threads: t.start() for t in threads: t.join() logger.flush() # Ensure all logs are written ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.