-
Notifications
You must be signed in to change notification settings - Fork 0
[Feature][Logging] #25
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
9d57a07
[Feature] - logging in cogs
shamikkarkhanis 6b8cc84
[Feature] - log files
shamikkarkhanis 5bc03ad
sourcery fix
shamikkarkhanis 89e1223
[ci] - changed exit code for running test
shamikkarkhanis 8faefa5
Merge branch 'ci/fix-pytest-exit-code' into feature/logging
shamikkarkhanis File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,31 +1,89 @@ | ||
| import datetime | ||
| import logging | ||
| import logging.handlers | ||
| import sys | ||
| from datetime import UTC, datetime | ||
| from logging.handlers import RotatingFileHandler | ||
| from pathlib import Path | ||
| from typing import Final | ||
|
|
||
| from capy_discord.config import settings | ||
| # Standard format: [Time] [Level] [Logger Name]: Message | ||
| LOG_FORMAT: Final[str] = "[%(asctime)s] [%(levelname)s] [%(name)s]: %(message)s" | ||
| DATE_FORMAT: Final[str] = "%Y-%m-%d %H:%M:%S" | ||
|
|
||
|
|
||
| def setup_logging() -> None: | ||
| """Set up logging for the application.""" | ||
| log_format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s" | ||
| log_level = logging.getLevelNamesMapping()[settings.log_level.upper()] | ||
| log_file = f"{datetime.datetime.now(datetime.UTC).date()}.log" | ||
| class ColoredFormatter(logging.Formatter): | ||
| """A custom logging formatter that adds colors to the output.""" | ||
|
|
||
| # Create logs directory if it doesn't exist | ||
| def __init__(self, fmt: str, datefmt: str) -> None: | ||
| """Initialize the ColoredFormatter.""" | ||
| super().__init__(fmt, datefmt) | ||
| self.level_colors = { | ||
| logging.INFO: "\033[92m", # Green | ||
| logging.WARNING: "\033[93m", # Yellow | ||
| logging.ERROR: "\033[91m", # Red | ||
| logging.CRITICAL: "\033[91m", # Red | ||
| logging.DEBUG: "\033[94m", # Blue | ||
| } | ||
| self.name_color = "\033[96m" # Cyan | ||
| self.reset = "\033[0m" | ||
|
|
||
| def format(self, record: logging.LogRecord) -> str: | ||
| """Format the log record.""" | ||
| # Get the color for the level | ||
| level_color = self.level_colors.get(record.levelno, "") | ||
|
|
||
| # Temporarily add color to the levelname and name | ||
| original_levelname = record.levelname | ||
| original_name = record.name | ||
|
|
||
| record.levelname = f"{level_color}{original_levelname}{self.reset}" | ||
| record.name = f"{self.name_color}{original_name}{self.reset}" | ||
|
|
||
| # Format the message | ||
| formatted_message = super().format(record) | ||
|
|
||
| # Restore the original values | ||
| record.levelname = original_levelname | ||
| record.name = original_name | ||
|
|
||
| return formatted_message | ||
|
|
||
|
|
||
| def get_logger(name: str) -> logging.Logger: | ||
| """Get a logger instance with the specified name.""" | ||
| return logging.getLogger(name) | ||
|
|
||
|
|
||
| def setup_logging(level: int | str = logging.INFO) -> None: | ||
| """Set up the logging configuration with the specified level.""" | ||
| root_logger = logging.getLogger() | ||
| root_logger.setLevel(level) | ||
|
|
||
| # Create a handler that writes to stdout | ||
| stream_handler = logging.StreamHandler(sys.stdout) | ||
| colored_formatter = ColoredFormatter(LOG_FORMAT, datefmt=DATE_FORMAT) | ||
| stream_handler.setFormatter(colored_formatter) | ||
|
|
||
| # Create a log directory if it doesn't exist | ||
| log_dir = Path("logs") | ||
| log_dir.mkdir(exist_ok=True) | ||
|
|
||
| # Root logger | ||
| logger = logging.getLogger() | ||
| logger.setLevel(log_level) | ||
| # Create a timestamped filename | ||
| timestamp = datetime.now(UTC).strftime("%Y-%m-%d_%H-%M-%S") | ||
| log_filename = log_dir / f"capy-discord_{timestamp}.log" | ||
|
|
||
| # File handler | ||
| file_handler = logging.handlers.RotatingFileHandler( | ||
| log_dir / log_file, | ||
| maxBytes=1024 * 1024 * 5, # 5 MB | ||
| # Create a handler that writes to a file with rotation | ||
| file_handler = RotatingFileHandler( | ||
| filename=log_filename, | ||
| maxBytes=5 * 1024 * 1024, # 5 MB | ||
| backupCount=5, | ||
| encoding="utf-8", | ||
| ) | ||
| file_handler.setFormatter(logging.Formatter(log_format)) | ||
| logger.addHandler(file_handler) | ||
| file_formatter = logging.Formatter(LOG_FORMAT, datefmt=DATE_FORMAT) | ||
| file_handler.setFormatter(file_formatter) | ||
|
|
||
| # Removing previous handlers to avoid duplicate logs from discord after setup_logging invocation | ||
| if root_logger.hasHandlers(): | ||
| root_logger.handlers.clear() | ||
|
|
||
| root_logger.addHandler(stream_handler) | ||
| root_logger.addHandler(file_handler) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.