-
-
Notifications
You must be signed in to change notification settings - Fork 52
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
add log collection #306
Closed
Closed
add log collection #306
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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 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 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
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains 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 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,63 +1,78 @@ | ||
import asyncio | ||
import logging | ||
import sys | ||
from contextlib import contextmanager | ||
from typing import IO, Any, Generator, List, TextIO | ||
from logging import LogRecord | ||
from typing import Dict, List, Union | ||
|
||
from bidict import bidict | ||
|
||
class Redirector: | ||
"""A class to write to multiple streams.""" | ||
|
||
def __init__(self, *streams: IO[Any]) -> None: | ||
self.streams = streams | ||
class TaskiqLogHandler(logging.Handler): | ||
"""Log handler class.""" | ||
|
||
def write(self, message: Any) -> None: | ||
def __init__(self, level: Union[int, str] = 0) -> None: | ||
self.stream: Dict[Union[str, None], List[logging.LogRecord]] = {} | ||
self._associations: bidict[Union[str, None], Union[str, None]] = bidict() | ||
super().__init__(level) | ||
|
||
@staticmethod | ||
def _get_async_task_name() -> Union[str, None]: | ||
try: | ||
task = asyncio.current_task() | ||
except RuntimeError: | ||
return None | ||
else: | ||
if task: | ||
return task.get_name() | ||
|
||
return None | ||
|
||
def associate(self, task_id: str) -> None: | ||
""" | ||
Associate the current async task with the Taskiq task ID. | ||
|
||
:param task_id: The Taskiq task ID. | ||
:type task_id: str | ||
""" | ||
async_task_name = self._get_async_task_name() | ||
self._associations[task_id] = async_task_name | ||
|
||
def retrieve_logs(self, task_id: str) -> List[LogRecord]: | ||
""" | ||
Collect logs. | ||
|
||
Collect the logs of a Taskiq task and return | ||
them after removing them from memory. | ||
|
||
:param task_id: The Taskiq task ID | ||
:type task_id: str | ||
:return: A list of LogRecords | ||
:rtype: List[LogRecord] | ||
""" | ||
async_task_name = self._associations[task_id] | ||
try: | ||
stream = self.stream[async_task_name] | ||
except KeyError: | ||
stream = [] | ||
else: | ||
del self._associations[task_id] | ||
return stream | ||
|
||
def emit(self, record: LogRecord) -> None: | ||
""" | ||
This write request writes to all available streams. | ||
Collect a log record. | ||
|
||
:param message: message to write. | ||
:param record: The log record to collect. | ||
:type record: LogRecord | ||
""" | ||
for stream in self.streams: | ||
stream.write(message) | ||
|
||
|
||
@contextmanager | ||
def log_collector( | ||
new_target: TextIO, | ||
custom_format: str, | ||
) -> "Generator[TextIO, None, None]": | ||
""" | ||
Context manager to collect logs. | ||
|
||
This useful class redirects all logs | ||
from stdout, stderr and root logger | ||
to some new target. | ||
|
||
It can be used like this: | ||
|
||
>>> logs = io.StringIO() | ||
>>> with log_collector(logs, "%(levelname)s %(message)s"): | ||
>>> print("A") | ||
>>> | ||
>>> print(f"Collected logs: {logs.get_value()}") | ||
|
||
:param new_target: new target for logs. All | ||
logs are written in new_target. | ||
:param custom_format: custom format for | ||
collected logging calls. | ||
:yields: new target. | ||
""" | ||
old_targets: "List[TextIO]" = [] | ||
log_handler = logging.StreamHandler(new_target) | ||
log_handler.setFormatter(logging.Formatter(custom_format)) | ||
|
||
old_targets.extend([sys.stdout, sys.stderr]) | ||
logging.root.addHandler(log_handler) | ||
sys.stdout = Redirector(new_target, sys.stdout) # type: ignore | ||
sys.stderr = Redirector(new_target, sys.stderr) # type: ignore | ||
|
||
try: | ||
yield new_target | ||
finally: | ||
sys.stderr = old_targets.pop() | ||
sys.stdout = old_targets.pop() | ||
logging.root.removeHandler(log_handler) | ||
self.format(record) | ||
async_task_name = self._get_async_task_name() | ||
if not async_task_name: | ||
return | ||
try: | ||
record.task_id = self._associations.inverse[async_task_name] | ||
except KeyError: | ||
return | ||
try: | ||
self.stream[async_task_name].append(record) | ||
except KeyError: | ||
self.stream[async_task_name] = [record] |
This file contains 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 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
Oops, something went wrong.
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The log here seems to be just the normal log in the task function, do we need to collect the exceptions generated by
NoResultError
andBaseException
as well?