-
Notifications
You must be signed in to change notification settings - Fork 14
Added logger with basic debugging info #86
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
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
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,94 @@ | ||
import functools | ||
import inspect | ||
import json | ||
import logging | ||
from contextvars import ContextVar | ||
from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, Tuple, Type, cast | ||
|
||
# Conditional import only executed when type checking, otherwise we'd get circular dependency issues | ||
if TYPE_CHECKING: | ||
from .clients.base.base_client import _BaseBaseClient | ||
|
||
# Name of the logger used throughout the library | ||
logger_name = __name__.split('.')[0] | ||
|
||
# Logger used throughout the library | ||
logger = logging.getLogger(logger_name) | ||
|
||
|
||
# Context variables containing the current resource client running in that context | ||
# Used during logging to inject the resource client context to the log | ||
ctx_client_method = ContextVar[Optional[str]]('client_method', default=None) | ||
ctx_resource_id = ContextVar[Optional[str]]('resource_id', default=None) | ||
ctx_url = ContextVar[Optional[str]]('url', default=None) | ||
|
||
|
||
# Metaclass for resource clients which wraps all their public methods | ||
# With injection of their details to the log context vars | ||
class _WithLogDetailsClient(type): | ||
def __new__(cls: Type[type], name: str, bases: Tuple, attrs: Dict) -> '_WithLogDetailsClient': | ||
for attr_name, attr_value in attrs.items(): | ||
if not attr_name.startswith('_'): | ||
if inspect.isfunction(attr_value): | ||
attrs[attr_name] = _injects_client_details_to_log_context(attr_value) | ||
|
||
return cast(_WithLogDetailsClient, type.__new__(cls, name, bases, attrs)) | ||
|
||
|
||
# Wraps an unbound method so that its call will inject the details | ||
# of the resource client (which is the `self` argument of the method) | ||
# to the log context vars | ||
def _injects_client_details_to_log_context(fun: Callable) -> Callable: | ||
if inspect.iscoroutinefunction(fun) or inspect.isasyncgenfunction(fun): | ||
@functools.wraps(fun) | ||
async def async_wrapper(resource_client: '_BaseBaseClient', *args: Any, **kwargs: Any) -> Any: | ||
ctx_client_method.set(fun.__qualname__) | ||
ctx_resource_id.set(resource_client.resource_id) | ||
ctx_url.set(resource_client.url) | ||
|
||
return await fun(resource_client, *args, **kwargs) | ||
return async_wrapper | ||
else: | ||
@functools.wraps(fun) | ||
def wrapper(resource_client: '_BaseBaseClient', *args: Any, **kwargs: Any) -> Any: | ||
ctx_client_method.set(fun.__qualname__) | ||
ctx_resource_id.set(resource_client.resource_id) | ||
ctx_url.set(resource_client.url) | ||
|
||
return fun(resource_client, *args, **kwargs) | ||
return wrapper | ||
|
||
|
||
# A filter which lets every log record through, | ||
# but adds the current logging context to the record | ||
class _ContextInjectingFilter(logging.Filter): | ||
def filter(self, record: logging.LogRecord) -> bool: | ||
record.client_method = ctx_client_method.get() | ||
record.resource_id = ctx_resource_id.get() | ||
record.url = ctx_url.get() | ||
return True | ||
|
||
|
||
logger.addFilter(_ContextInjectingFilter()) | ||
|
||
|
||
# Log formatter useful for debugging of the client | ||
# Will print out all the extra fields added to the log record | ||
class _DebugLogFormatter(logging.Formatter): | ||
empty_record = logging.LogRecord('dummy', 0, 'dummy', 0, 'dummy', None, None) | ||
|
||
def _get_extra_fields(self, record: logging.LogRecord) -> Dict[str, Any]: | ||
extra_fields: Dict[str, Any] = {} | ||
for key, value in record.__dict__.items(): | ||
if key not in self.empty_record.__dict__: | ||
extra_fields[key] = value | ||
|
||
return extra_fields | ||
|
||
def format(self, record: logging.LogRecord) -> str: | ||
extra = self._get_extra_fields(record) | ||
|
||
log_string = super().format(record) | ||
if extra: | ||
log_string = f'{log_string} ({json.dumps(extra)})' | ||
return log_string |
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.
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.
Maybe it would be beneficial here to show a simple example with custom log formatter? So the users don't need to go dig in the official docs.
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.
I was trying to write something, but then I realized there's so many ways how users can have their formatters configured, and I kinda gave up. Usually, if you need logging in your app, you're already using some log formatters, and you won't be learning about them from this library.
Anyway, the logging here is most useful to us while developing the client, not so much to the users (especially the extra log properties), maybe I'll add a mention of the
_DebugLogFormatter
somewhere to README or something like that.