======================== CODE SNIPPETS ======================== TITLE: Install Tamga Python Logging Library DESCRIPTION: Instructions for installing the Tamga logging library using pip, including options for basic installation, notification support, MongoDB integration, or all available features. SOURCE: https://github.com/dogukanurker/tamga/blob/main/llms.txt#_snippet_0 LANGUAGE: bash CODE: ``` pip install tamga pip install tamga[notifications] pip install tamga[mongo] pip install tamga[all] ``` ---------------------------------------- TITLE: Quick Start with Tamga Logger DESCRIPTION: Demonstrates how to initialize the Tamga logger with default settings and log messages at various standard levels: info, warning, error, success, debug, and critical. SOURCE: https://github.com/dogukanurker/tamga/blob/main/llms.txt#_snippet_1 LANGUAGE: python CODE: ``` from tamga import Tamga # Create logger with default settings logger = Tamga() # Log messages logger.info("Application started") logger.warning("Memory usage at 85%") logger.error("Failed to connect to API") logger.success("User registered successfully") logger.debug("Cache initialized with 1000 entries") logger.critical("Database connection lost") ``` ---------------------------------------- TITLE: Installing Tamga Python Library DESCRIPTION: Provides commands for installing the Tamga library using pip, including options for additional features like MongoDB support, notification services, or all features. SOURCE: https://github.com/dogukanurker/tamga/blob/main/README.md#_snippet_1 LANGUAGE: bash CODE: ``` pip install tamga # Basic installation pip install tamga[mongo] # With MongoDB support pip install tamga[notifications] # With notification support pip install tamga[all] # All features ``` ---------------------------------------- TITLE: Example Tamga File Log Output DESCRIPTION: Shows the standard format of log entries when Tamga writes to a log file (e.g., `tamga.log`), including timestamp, timezone, log level, and the message. SOURCE: https://github.com/dogukanurker/tamga/blob/main/llms.txt#_snippet_11 LANGUAGE: text CODE: ``` [28.06.25 | 14:30:45 | UTC] INFO: Application started [28.06.25 | 14:30:46 | UTC] ERROR: Connection failed ``` ---------------------------------------- TITLE: Example Tamga JSON Log Output DESCRIPTION: Provides an example of a log entry formatted as a JSON object. This format is ideal for structured logging, allowing easy parsing and integration with log aggregation systems. SOURCE: https://github.com/dogukanurker/tamga/blob/main/llms.txt#_snippet_12 LANGUAGE: json CODE: ``` { "level": "INFO", "message": "Application started", "date": "28.06.25", "time": "14:30:45", "timezone": "UTC", "timestamp": 1719584445.123456 } ``` ---------------------------------------- TITLE: Example Tamga Console Log Output DESCRIPTION: Displays the typical format of log messages when Tamga outputs to the console, including timestamp, timezone, log level, and the message content. SOURCE: https://github.com/dogukanurker/tamga/blob/main/llms.txt#_snippet_10 LANGUAGE: text CODE: ``` [28.06.25 | 14:30:45 | UTC] INFO Application started [28.06.25 | 14:30:46 | UTC] ERROR Connection failed ``` ---------------------------------------- TITLE: Comprehensive Tamga Logger Configuration and Usage in Python DESCRIPTION: Provides a complete, production-ready example of configuring the Tamga logger. It showcases various output options including console, file, JSON, MongoDB, and multi-service notifications, along with best practices for application logging, error handling, and graceful shutdown. SOURCE: https://github.com/dogukanurker/tamga/blob/main/llms.txt#_snippet_23 LANGUAGE: python CODE: ``` from tamga import Tamga import os # Production-ready configuration logger = Tamga( # Console only in development console_output=os.getenv("ENV") != "production", # Always log to file file_output=True, file_path="logs/app.log", max_file_size_mb=50, # JSON for log aggregation json_output=True, # Performance settings buffer_size=100 if os.getenv("ENV") == "production" else 10, # MongoDB for centralized logging mongo_output=bool(os.getenv("MONGO_URI")), mongo_uri=os.getenv("MONGO_URI"), # Multi-service notifications notify_services=[ os.getenv("DISCORD_WEBHOOK"), os.getenv("SLACK_WEBHOOK"), f"mailto://{os.getenv('SMTP_USER')}:{os.getenv('SMTP_PASS')}@smtp.gmail.com:587/?to=alerts@company.com", ] if os.getenv("NOTIFICATIONS_ENABLED") else [], notify_levels=["CRITICAL", "NOTIFY"], notify_title="{appname} Alert: {level}", notify_format="markdown", ) # Application usage logger.info("Application starting") logger.info("Configuration loaded", environment=os.getenv("ENV"), debug_mode=True ) try: # Application logic logger.success("Service initialized") # Important business event - triggers notification logger.notify("New premium subscription: user_123 purchased Pro plan") except Exception as e: logger.critical(f"Fatal error: {str(e)}") logger.flush() # Ensure critical error is written raise finally: logger.info("Shutting down") logger.flush() ``` ---------------------------------------- TITLE: Tamga Notification Configuration and Usage DESCRIPTION: This snippet demonstrates how to configure Tamga for sending notifications using Apprise, supporting over 80 services. It shows how to specify notification services, define which log levels trigger notifications, and set the output format (markdown, html, text). Examples illustrate which log calls will trigger notifications based on the configured levels. SOURCE: https://github.com/dogukanurker/tamga/blob/main/llms.txt#_snippet_20 LANGUAGE: python CODE: ``` logger = Tamga( notify_services=["discord://webhook_id/webhook_token"], notify_levels=["CRITICAL", "ERROR", "NOTIFY"], notify_format="markdown", # or "html", "text" ) # These trigger notifications: logger.critical("System down") logger.error("Payment failed") logger.notify("New premium subscription!") # This doesn't trigger notification: logger.warning("High memory usage") # WARNING not in notify_levels ``` ---------------------------------------- TITLE: Optimize Tamga for High-Performance Logging DESCRIPTION: This example shows how to configure Tamga for high-performance logging, suitable for processing large datasets. It disables console output, uses a large buffer size, and demonstrates periodic flushing to prevent memory buildup during intensive operations. SOURCE: https://github.com/dogukanurker/tamga/blob/main/llms.txt#_snippet_15 LANGUAGE: python CODE: ``` logger = Tamga( file_output=True, console_output=False, # Disable console for speed buffer_size=1000, # Large buffer ) # Process large dataset 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() ``` ---------------------------------------- TITLE: Implement Structured Request Logging with Tamga DESCRIPTION: This Python function demonstrates how to implement structured logging for incoming requests using Tamga. It captures request details, assigns a unique ID, logs start and completion events with relevant metadata (method, path, status, duration), and handles exceptions by logging errors. SOURCE: https://github.com/dogukanurker/tamga/blob/main/llms.txt#_snippet_17 LANGUAGE: python CODE: ``` import time import uuid def log_request(request): request_id = str(uuid.uuid4()) start_time = time.time() # Log request details logger.info("Request started", request_id=request_id, method=request.method, path=request.path, ip=request.remote_addr ) try: response = process(request) duration = time.time() - start_time logger.info("Request completed", request_id=request_id, status=response.status_code, duration_ms=round(duration * 1000) ) return response except Exception as e: logger.error(f"Request {request_id} failed: {str(e)}") raise ``` ---------------------------------------- TITLE: Define and Use Custom Log Levels in Tamga DESCRIPTION: This example illustrates how to define and utilize custom log levels within the Tamga logging library. It shows `logger.custom()` calls with a message, a custom level name (e.g., 'DEPLOY', 'PAYMENT'), and an optional color, allowing for more granular and visually distinct logging. SOURCE: https://github.com/dogukanurker/tamga/blob/main/README.md#_snippet_7 LANGUAGE: python CODE: ``` logger.custom("Deploy completed", "DEPLOY", "purple") logger.custom("Payment received", "PAYMENT", "green") ``` ---------------------------------------- TITLE: Implementing Thread-Safe Logging with Tamga in Python DESCRIPTION: Illustrates Tamga's inherent thread-safety by showing multiple worker threads concurrently logging messages. This example ensures that log operations remain consistent and free from race conditions in multi-threaded Python applications. SOURCE: https://github.com/dogukanurker/tamga/blob/main/llms.txt#_snippet_22 LANGUAGE: python CODE: ``` import threading logger = Tamga(file_output=True) def worker(worker_id): for i in range(100): logger.info(f"Worker {worker_id}: Item {i}") # Safe to use from multiple threads threads = [threading.Thread(target=worker, args=(i,)) for i in range(10)] for t in threads: t.start() for t in threads: t.join() ``` ---------------------------------------- TITLE: Basic Logging with Tamga DESCRIPTION: Demonstrates how to initialize the Tamga logger with default settings and log messages at various standard levels (info, warning, error, success, debug). SOURCE: https://github.com/dogukanurker/tamga/blob/main/README.md#_snippet_0 LANGUAGE: python CODE: ``` from tamga import Tamga # Create logger with default settings logger = Tamga() # Log messages logger.info("Application started") logger.warning("Memory usage at 85%") logger.error("Failed to connect to API") logger.success("User registered successfully") logger.debug("Cache initialized with 1000 entries") ``` ---------------------------------------- TITLE: Tamga Logger Configuration Parameters DESCRIPTION: Comprehensive documentation for the `Tamga` class constructor parameters, detailing options for output destinations, display settings, file paths, MongoDB integration, notification services, and performance tuning. SOURCE: https://github.com/dogukanurker/tamga/blob/main/llms.txt#_snippet_2 LANGUAGE: APIDOC CODE: ``` Tamga( console_output: bool = True, colored_output: bool = True, file_output: bool = False, json_output: bool = False, mongo_output: bool = False, sql_output: bool = False, show_date: bool = True, show_time: bool = True, show_timezone: bool = False, file_path: str = "tamga.log", json_path: str = "tamga.json", sql_path: str = "tamga.db", sql_table_name: str = "logs", mongo_uri: str = None, mongo_database_name: str = "tamga", mongo_collection_name: str = "logs", notify_services: list = None, notify_levels: list = [], notify_title: str = "{appname}: {level} - {date}", notify_format: str = "text", max_file_size_mb: int = 10, max_json_size_mb: int = 10, max_sql_size_mb: int = 50, enable_backup: bool = True, buffer_size: int = 50 ) Parameters: console_output (bool): Enable logging to console (default: True). colored_output (bool): Enable colored console output (default: True). file_output (bool): Enable logging to a file (default: False). json_output (bool): Enable logging to a JSON file (default: False). mongo_output (bool): Enable logging to MongoDB (default: False). sql_output (bool): Enable logging to an SQL database (default: False). show_date (bool): Show date in console logs (default: True). show_time (bool): Show time in console logs (default: True). show_timezone (bool): Show timezone in console logs (default: False). file_path (str): Path to the log file (default: "tamga.log"). json_path (str): Path to the JSON log file (default: "tamga.json"). sql_path (str): Path to the SQL log file (default: "tamga.db"). sql_table_name (str): SQL table name for logs (default: "logs"). mongo_uri (str): MongoDB connection URI (default: None). mongo_database_name (str): MongoDB database name (default: "tamga"). mongo_collection_name (str): MongoDB collection name (default: "logs"). notify_services (list): List of Apprise notification service URLs (default: None). notify_levels (list): Log levels to send notifications for (default: []). notify_title (str): Template for notification titles (default: "{appname}: {level} - {date}"). notify_format (str): Notification format type (text/markdown/html) (default: "text"). max_file_size_mb (int): Maximum size in MB for log file before rotation (default: 10). max_json_size_mb (int): Maximum size in MB for JSON file before rotation (default: 10). max_sql_size_mb (int): Maximum size in MB for SQL file before rotation (default: 50). enable_backup (bool): Enable backup when max size is reached (default: True). buffer_size (int): Number of logs to buffer before writing to file (default: 50). Example: Display Settings logger = Tamga( colored_output=True, console_output=True, show_date=True, show_time=True, show_timezone=False ) Example: Output Destinations logger = Tamga( file_output=False, file_path="tamga.log", json_output=False, json_path="tamga.json", sql_output=False, sql_path="tamga.db", sql_table_name="logs", mongo_output=False ) Example: Performance Settings logger = Tamga( buffer_size=50, max_file_size_mb=10, max_json_size_mb=10, max_sql_size_mb=50, enable_backup=True ) ``` ---------------------------------------- TITLE: Tamga Performance Guidelines and File Rotation DESCRIPTION: This section outlines recommendations for configuring Tamga's buffer size for optimal performance across different use cases, provides general performance tips, and details the approximate throughput for various logging outputs. It also explains the file rotation mechanism, including backup creation and file clearing behavior. SOURCE: https://github.com/dogukanurker/tamga/blob/main/llms.txt#_snippet_19 LANGUAGE: APIDOC CODE: ``` Buffer Size Recommendations: - Real-time monitoring: buffer_size=1 (immediate writes) - Web applications: buffer_size=50 (default, balanced) - Background jobs: buffer_size=200-500 (efficient batching) - Data processing: buffer_size=1000+ (maximum performance) Performance Tips: 1. Disable console output in production for 10x speed improvement 2. Use flush() after critical messages to ensure immediate write 3. Increase buffer size for batch operations 4. Use MongoDB logging asynchronously to avoid blocking Approximate Throughput: - Console (colored): ~1,000 logs/second - File (buffered): ~100,000 logs/second - JSON (buffered): ~80,000 logs/second - SQLite: ~50,000 logs/second - MongoDB (async): ~30,000 logs/second File Rotation: When a file reaches max_file_size_mb: 1. If enable_backup=True, creates timestamped backup: - tamga.log → tamga.log.20250628_143022.bak 2. Clears the original file: - Log files: Emptied - JSON files: Reset to [] - SQLite: Records deleted, schema preserved ``` ---------------------------------------- TITLE: Configuring Tamga for Basic Logging DESCRIPTION: Illustrates how to configure the Tamga logger with basic display settings (colored output, timestamp) and file output options (file path, buffer size). SOURCE: https://github.com/dogukanurker/tamga/blob/main/README.md#_snippet_2 LANGUAGE: python CODE: ``` logger = Tamga( # Display settings colored_output=True, # Colored output show_time=True, # Include timestamp show_timezone=False, # Include timezone # Output destinations file_output=True, # Log to file file_path="app.log", # Log file path buffer_size=50, # Buffer size for performance ) ``` ---------------------------------------- TITLE: Git Workflow Commands for Project Contribution DESCRIPTION: This snippet outlines the essential Git commands used throughout the project contribution process. It covers creating a new feature branch, committing local changes with a descriptive message, and pushing those changes to the remote repository in preparation for a pull request. SOURCE: https://github.com/dogukanurker/tamga/blob/main/docs/CONTRIBUTING.md#_snippet_0 LANGUAGE: Git CODE: ``` git checkout -b feature/your-feature ``` LANGUAGE: Git CODE: ``` git commit -m 'Add some feature' ``` LANGUAGE: Git CODE: ``` git push origin feature/your-feature ``` ---------------------------------------- TITLE: Configure Tamga Logger with Notification Services DESCRIPTION: This snippet demonstrates how to initialize the Tamga logger, configuring it with multiple notification services (Discord, Slack) and specifying notification levels, title format, and message format. It also shows basic usage for sending general notifications and critical error alerts, which trigger configured notifications. SOURCE: https://github.com/dogukanurker/tamga/blob/main/README.md#_snippet_6 LANGUAGE: python CODE: ``` logger = Tamga( notify_services=[ "discord://webhook_id/webhook_token", "slack://tokenA/tokenB/tokenC/#channel", ], notify_levels=["CRITICAL", "ERROR", "NOTIFY"], notify_title="{appname}: {level} Alert", notify_format="markdown" ) logger.notify("Payment received from user #123") logger.critical("Database connection lost") ``` ---------------------------------------- TITLE: Configuring Tamga for Production Environments DESCRIPTION: Demonstrates an advanced Tamga configuration suitable for production, including file rotation, larger buffer sizes, disabling console output for performance, and integrating with MongoDB and various notification services. SOURCE: https://github.com/dogukanurker/tamga/blob/main/README.md#_snippet_4 LANGUAGE: python CODE: ``` logger = Tamga( # File rotation file_output=True, max_file_size_mb=50, # 50MB max file size enable_backup=True, # Create backups # Performance buffer_size=200, # Larger buffer for production console_output=False, # Disable console for speed # External services mongo_output=True, mongo_uri="mongodb://...", # Multi-service notifications notify_services=[ "discord://webhook_id/webhook_token", "slack://tokenA/tokenB/tokenC/#alerts", "mailto://user:pass@smtp.gmail.com:587/?to=alerts@company.com", "twilio://SID:Token@+1234567890/+0987654321", ], notify_levels=["CRITICAL", "ERROR", "NOTIFY"], ) ``` ---------------------------------------- TITLE: Implement Custom Log Levels and Structured Logging with Tamga DESCRIPTION: Demonstrates how to define custom log levels with specific colors for unique application events. It also shows how to perform structured logging by passing key-value pairs to any logging method, enriching log data for easier analysis. SOURCE: https://github.com/dogukanurker/tamga/blob/main/llms.txt#_snippet_7 LANGUAGE: python CODE: ``` # Custom level and color logger.custom("Deploy completed", "DEPLOY", "purple") # Structured logging with key-value data using any log method logger.info("User action", user_id="123", action="login", ip_address="192.168.1.1", success=True ) # Works with all log levels logger.error("Database connection failed", host="localhost", port=5432, timeout=30) logger.success("Payment processed", amount=99.99, currency="USD", method="credit_card") logger.warning("High memory usage", memory_pct=85, threshold=80) logger.critical("System overload", cpu_pct=95, memory_pct=98) ``` ---------------------------------------- TITLE: Performing Structured Logging with Tamga DESCRIPTION: Shows how to log messages with additional key-value data using any log method, enabling structured logging for better analysis and filtering. SOURCE: https://github.com/dogukanurker/tamga/blob/main/README.md#_snippet_3 LANGUAGE: python CODE: ``` # Log with key-value data using any log method logger.info("User action", user_id="123", action="login", ip_address="192.168.1.1", success=True ) # Works with all log levels logger.error("Database connection failed", host="localhost", port=5432, timeout=30, retry_count=3 ) logger.success("Payment processed", amount=99.99, currency="USD", method="credit_card", transaction_id="tx_123" ) ``` ---------------------------------------- TITLE: Configure Tamga for Development Debugging DESCRIPTION: This configuration snippet is tailored for development environments, prioritizing maximum visibility and immediate feedback. It enables colored console output, displays full timestamps, sets a small buffer size for instant writes, and configures local file logging for debugging purposes. SOURCE: https://github.com/dogukanurker/tamga/blob/main/llms.txt#_snippet_16 LANGUAGE: python CODE: ``` logger = Tamga( # Maximum visibility colored_output=True, show_date=True, show_time=True, show_timezone=True, # Immediate feedback buffer_size=1, # Local file for debugging file_output=True, file_path="debug.log", ) ``` ---------------------------------------- TITLE: Utilize Standard Tamga Logging Levels DESCRIPTION: Illustrates the use of Tamga's built-in logging methods for different severity levels. These methods provide distinct visual cues (colors) in the console and categorize logs for filtering and analysis. SOURCE: https://github.com/dogukanurker/tamga/blob/main/llms.txt#_snippet_5 LANGUAGE: python CODE: ``` logger.info("Informational message") # Sky blue logger.warning("Warning message") # Amber logger.error("Error occurred") # Rose logger.success("Operation completed") # Emerald logger.debug("Debug information") # Indigo logger.critical("Critical failure") # Red logger.database("Query executed") # Green logger.notify("Important notification") # Purple - sends notification logger.metric("Response time: 125ms") # Cyan logger.trace("Detailed trace info") # Gray ``` ---------------------------------------- TITLE: Configure Tamga for Multi-Service Notifications DESCRIPTION: Shows how to set up the Tamga logger to send notifications through various services (e.g., Discord, Slack, Email, Twilio, Telegram, Microsoft Teams) using Apprise. It also covers configuring which log levels trigger notifications, the notification title template, and the message format. SOURCE: https://github.com/dogukanurker/tamga/blob/main/llms.txt#_snippet_4 LANGUAGE: python CODE: ``` logger = Tamga( # Apprise notification services (supports 80+ services) notify_services=[ # Discord "discord://webhook_id/webhook_token", # Slack "slack://tokenA/tokenB/tokenC/#channel", # Email via SMTP "mailto://user:pass@smtp.gmail.com:587/?to=alerts@company.com", # SMS via Twilio "twilio://SID:Token@+1234567890/+0987654321", # Telegram "tgram://bot_token/chat_id", # Microsoft Teams "msteams://TokenA/TokenB/TokenC/", # And many more... ], # Which log levels trigger notifications notify_levels=["NOTIFY"], # Default: ["NOTIFY"] # Notification title template notify_title="{appname}: {level} - {date}", # Default template # Format: "text", "markdown", or "html" notify_format="text" # Default: "text" ) ``` ---------------------------------------- TITLE: Tamga Logger Methods and Log Levels DESCRIPTION: Documents the various logging methods available in the Tamga library, their associated log levels, colors, and typical use cases. All methods accept a primary message string and optional keyword arguments for structured logging. SOURCE: https://github.com/dogukanurker/tamga/blob/main/README.md#_snippet_5 LANGUAGE: APIDOC CODE: ``` Tamga Logger Methods: logger.info(message: str, **kwargs) - Level: INFO - Color: Sky - Use Case: General information messages. logger.warning(message: str, **kwargs) - Level: WARNING - Color: Amber - Use Case: Warning messages indicating potential issues. logger.error(message: str, **kwargs) - Level: ERROR - Color: Rose - Use Case: Error messages for failed operations or exceptions. logger.success(message: str, **kwargs) - Level: SUCCESS - Color: Emerald - Use Case: Messages indicating successful completion of an action. logger.debug(message: str, **kwargs) - Level: DEBUG - Color: Indigo - Use Case: Detailed debug information for development and troubleshooting. logger.critical(message: str, **kwargs) - Level: CRITICAL - Color: Red - Use Case: Critical issues requiring immediate attention. logger.database(message: str, **kwargs) - Level: DATABASE - Color: Green - Use Case: Logging database operations. logger.notify(message: str, **kwargs) - Level: NOTIFY - Color: Purple - Use Case: Sending notifications via configured services. logger.metric(message: str, **kwargs) - Level: METRIC - Color: Cyan - Use Case: Logging performance metrics. logger.trace(message: str, **kwargs) - Level: TRACE - Color: Gray - Use Case: Extremely detailed trace information. logger.custom(message: str, **kwargs) - Level: CUSTOM - Color: Any (configurable) - Use Case: For defining and using custom log levels. ``` ---------------------------------------- TITLE: Configure Tamga for Production Logging DESCRIPTION: This snippet demonstrates a robust production configuration for the Tamga logging library. It includes file logging with rotation, JSON output for aggregation, disabled console output for performance, MongoDB integration for centralized logging, and multi-service notifications for critical events via Discord, Slack, Email, and Twilio SMS. SOURCE: https://github.com/dogukanurker/tamga/blob/main/llms.txt#_snippet_14 LANGUAGE: python CODE: ``` import os logger = Tamga( # File logging with rotation file_output=True, file_path="logs/app.log", max_file_size_mb=50, enable_backup=True, # JSON for log aggregation json_output=True, # Performance optimization console_output=False, buffer_size=200, # Centralized logging mongo_output=True, mongo_uri=os.getenv("MONGO_URI"), # Multi-service notifications for critical events notify_services=[ # Discord webhook for dev team os.getenv("DISCORD_WEBHOOK", "discord://webhook_id/webhook_token"), # Slack for ops team os.getenv("SLACK_WEBHOOK", "slack://tokenA/tokenB/tokenC/#alerts"), # Email notifications f"mailto://{os.getenv('SMTP_USER')}:{os.getenv('SMTP_PASS')}@{os.getenv('SMTP_SERVER')}:587/?to={os.getenv('ALERT_EMAIL')}", # SMS for critical issues os.getenv("TWILIO_SMS", "twilio://SID:Token@+1234567890/+0987654321"), ] if os.getenv("NOTIFICATIONS_ENABLED") else [], notify_levels=["CRITICAL", "ERROR", "NOTIFY"], notify_title="🚨 {appname} Alert: {level}", notify_format="markdown", ) ``` ---------------------------------------- TITLE: Configure Tamga for MongoDB Output DESCRIPTION: Demonstrates how to initialize the Tamga logger to output logs to a MongoDB database. This configuration allows specifying the connection URI, the database name, and the collection name for storing log entries. SOURCE: https://github.com/dogukanurker/tamga/blob/main/llms.txt#_snippet_3 LANGUAGE: python CODE: ``` logger = Tamga( mongo_output=True, mongo_uri="mongodb+srv://user:pass@cluster.mongodb.net", mongo_database_name="tamga", # Default: "tamga" mongo_collection_name="logs" # Default: "logs" ) ``` ---------------------------------------- TITLE: Configure Specific Log Levels to Trigger Notifications DESCRIPTION: Explains how to customize which standard logging levels (e.g., CRITICAL, ERROR) will automatically trigger notifications via the configured Apprise services. This allows for flexible notification policies based on log severity. SOURCE: https://github.com/dogukanurker/tamga/blob/main/llms.txt#_snippet_6 LANGUAGE: python CODE: ``` logger = Tamga( notify_services=["discord://webhook_id/webhook_token"], notify_levels=["CRITICAL", "ERROR", "NOTIFY"] # These levels send notifications ) # These trigger notifications: logger.critical("System down") logger.error("Payment failed") logger.notify("New customer signed up!") # This doesn't trigger notification: logger.warning("High memory usage") # WARNING not in notify_levels ``` ---------------------------------------- TITLE: Custom Logging with Tailwind CSS Colors in Python DESCRIPTION: Demonstrates how to use Tamga's `logger.custom` method to output messages with specific Tailwind CSS colors. This feature enhances log readability and allows for easy categorization of different event types within the console output. SOURCE: https://github.com/dogukanurker/tamga/blob/main/llms.txt#_snippet_21 LANGUAGE: python CODE: ``` logger.custom("Custom event", "EVENT", "purple") logger.custom("Alert", "ALERT", "orange") ``` ---------------------------------------- TITLE: Force Flush Buffered Logs in Tamga DESCRIPTION: Illustrates how to explicitly flush any buffered logs to their configured output destinations. This is useful in scenarios where immediate persistence of logs is required, such as before application shutdown. SOURCE: https://github.com/dogukanurker/tamga/blob/main/llms.txt#_snippet_9 LANGUAGE: python CODE: ``` logger.flush() ``` ---------------------------------------- TITLE: Configure Tamga for Multi-Service Logging DESCRIPTION: This snippet shows how to configure Tamga for logging in a multi-service architecture. It sets up MongoDB logging with service-specific collections and includes service context (name, version, instance ID) in all log entries, facilitating easier filtering and analysis across distributed services. SOURCE: https://github.com/dogukanurker/tamga/blob/main/llms.txt#_snippet_18 LANGUAGE: python CODE: ``` service_name = os.getenv("SERVICE_NAME", "unknown") logger = Tamga( # Service-specific collection mongo_output=True, mongo_collection_name=service_name, # Include service context file_output=True, file_path=f"logs/{service_name}.log", ) # Add service context to all logs def log_with_context(message, level="info"): logger.info(message, service=service_name, version=os.getenv("VERSION"), instance=os.getenv("INSTANCE_ID") ) ``` ---------------------------------------- TITLE: Send Notifications with Custom Titles and Specific Services DESCRIPTION: Shows advanced usage of the `logger.notify()` method. This includes how to override the default notification title for a specific message and how to send a notification to a subset of configured services, providing fine-grained control over notification delivery. SOURCE: https://github.com/dogukanurker/tamga/blob/main/llms.txt#_snippet_8 LANGUAGE: python CODE: ``` # Send notification with custom title logger.notify("Payment processed", title="💰 Payment Alert") # Send to specific services (overrides default) logger.notify( "Urgent: Server down", services=["mailto://admin@company.com", "sms://..."] ) ``` ---------------------------------------- TITLE: Force Flush Buffered Logs in Tamga DESCRIPTION: This snippet demonstrates how to explicitly force the Tamga logger to write all currently buffered logs to their respective destinations. The `logger.flush()` method is useful for ensuring all pending log entries are processed immediately, especially before application shutdown or at critical synchronization points. SOURCE: https://github.com/dogukanurker/tamga/blob/main/README.md#_snippet_8 LANGUAGE: python CODE: ``` logger.flush() ``` ---------------------------------------- TITLE: Tamga SQLite Log Database Schema DESCRIPTION: Defines the SQL schema for the `logs` table used by Tamga when configured to output logs to an SQLite database. It specifies the columns for log level, message, date, time, timezone, and timestamp. SOURCE: https://github.com/dogukanurker/tamga/blob/main/llms.txt#_snippet_13 LANGUAGE: sql CODE: ``` CREATE TABLE logs ( level TEXT, message TEXT, date TEXT, time TEXT, timezone TEXT, timestamp REAL ) ```