generated from amazon-archives/__template_Apache-2.0
-
Couldn't load subscription status.
- Fork 67
feat: Add logging util and CLI params for logging output #17
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
Open
mkmeral
wants to merge
6
commits into
strands-agents:main
Choose a base branch
from
mkmeral:logging-utils
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 2 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
d800297
feat: Add logging utils
81fb0df
Add unit tests for logging util
6c249ee
Merge branch 'main' into logging-utils
8fbadfc
Address all PR review comments for logging utilities
94d9604
fix(logging): remove logging levels function
34d4279
Merge branch 'main' into logging-utils
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,135 @@ | ||
| #!/usr/bin/env python3 | ||
mkmeral marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| """ | ||
| Utility functions for configuring and managing logging in the Strands CLI. | ||
mkmeral marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| """ | ||
|
|
||
| import logging | ||
| import os | ||
| from typing import Any, Dict, List, Optional, Union | ||
|
|
||
|
|
||
| def configure_logging( | ||
| log_level: str = "INFO", | ||
| log_file: Optional[str] = None, | ||
| log_format: str = "%(asctime)s - %(name)s - %(levelname)s - %(message)s", | ||
| ) -> None: | ||
| """ | ||
| Configure logging for the Strands CLI with file output. | ||
| Args: | ||
| log_level: The logging level to use (DEBUG, INFO, WARNING, ERROR, CRITICAL) | ||
| log_file: Path to the log file. If None, logging is disabled. | ||
| log_format: The format string for log messages | ||
| Returns: | ||
| None | ||
| """ | ||
| # Convert string log level to logging constant | ||
| numeric_level = getattr(logging, log_level.upper(), None) | ||
| if not isinstance(numeric_level, int): | ||
| raise ValueError(f"Invalid log level: {log_level}") | ||
|
|
||
| # If no log file is specified, disable logging and return | ||
| if not log_file: | ||
| # Reset root logger | ||
| root = logging.getLogger() | ||
| if root.handlers: | ||
| for handler in root.handlers[:]: | ||
| root.removeHandler(handler) | ||
|
|
||
| # Set level to CRITICAL to minimize any accidental logging | ||
| root.setLevel(logging.CRITICAL) | ||
| return | ||
|
|
||
| # Create handlers | ||
| handlers: List[logging.Handler] = [] | ||
|
|
||
| # Setup file handler | ||
| try: | ||
| log_dir = os.path.dirname(log_file) | ||
| if log_dir and not os.path.exists(log_dir): | ||
| os.makedirs(log_dir, exist_ok=True) | ||
| handlers.append(logging.FileHandler(log_file)) | ||
| except Exception as e: | ||
| print(f"Warning: Failed to create log file {log_file}: {str(e)}") | ||
| print("Logging will be disabled") | ||
| return | ||
|
|
||
| # Configure root logger | ||
| logging.basicConfig( | ||
| level=numeric_level, | ||
| format=log_format, | ||
| handlers=handlers, | ||
| force=True, # Force reconfiguration | ||
| ) | ||
|
|
||
| # Configure specific Strands loggers | ||
| loggers = ["strands", "strands.agent", "strands.models", "strands.tools", "strands_agents_builder"] | ||
mkmeral marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| for logger_name in loggers: | ||
| logger = logging.getLogger(logger_name) | ||
| logger.setLevel(numeric_level) | ||
|
|
||
| # Log configuration information to the file | ||
| logging.info(f"Logging configured with level: {log_level}") | ||
| logging.info(f"Log file: {os.path.abspath(log_file)}") | ||
|
|
||
|
|
||
| def get_available_log_levels() -> List[str]: | ||
| """ | ||
| Returns a list of available logging levels. | ||
| Returns: | ||
| List of log level names | ||
| """ | ||
| return ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] | ||
mkmeral marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
|
|
||
| def get_logging_status() -> Dict[str, Any]: | ||
mkmeral marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| """ | ||
| Get the current logging status. | ||
| Returns: | ||
| Dict with information about the current logging configuration | ||
| """ | ||
| root_logger = logging.getLogger() | ||
| handlers = root_logger.handlers | ||
|
|
||
| file_handlers = [h for h in handlers if isinstance(h, logging.FileHandler)] | ||
| file_paths = [h.baseFilename for h in file_handlers] | ||
|
|
||
| status = { | ||
| "level": logging.getLevelName(root_logger.level), | ||
| "handlers": {"console": any(isinstance(h, logging.StreamHandler) for h in handlers), "files": file_paths}, | ||
| "strands_loggers": {}, | ||
| } | ||
|
|
||
| # Get status of strands specific loggers | ||
| for logger_name in ["strands", "strands.agent", "strands.models", "strands.tools", "strands_agents_builder"]: | ||
| logger = logging.getLogger(logger_name) | ||
| status["strands_loggers"][logger_name] = logging.getLevelName(logger.level) | ||
|
|
||
| return status | ||
|
|
||
|
|
||
| def set_log_level_for_module(module_name: str, log_level: Union[str, int]) -> None: | ||
mkmeral marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| """ | ||
| Set log level for a specific module. | ||
| Args: | ||
| module_name: The name of the module logger | ||
| log_level: The log level to set (can be string or logging constant) | ||
| Returns: | ||
| None | ||
| """ | ||
| if isinstance(log_level, str): | ||
| numeric_level = getattr(logging, log_level.upper(), None) | ||
| if not isinstance(numeric_level, int): | ||
| raise ValueError(f"Invalid log level: {log_level}") | ||
| else: | ||
| numeric_level = log_level | ||
|
|
||
| logger = logging.getLogger(module_name) | ||
| logger.setLevel(numeric_level) | ||
| logging.debug(f"Set log level for {module_name} to {log_level}") | ||
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.