-
Notifications
You must be signed in to change notification settings - Fork 63
feat: Add JSON logging capability to integrated_channels #2460
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
Draft
sameeramin
wants to merge
12
commits into
master
Choose a base branch
from
sameeramin/ENT-10900
base: master
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.
Draft
Changes from 1 commit
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
0cc0e3f
feat: Add JSON logging capability to integrated_channels
sameeramin de952bc
refactor: incorporated suggestions
sameeramin 0b6800a
refactor: use integrated_channels logger
sameeramin ddf081b
fix: get_integrated_channels_logger to modify handler based on flag
sameeramin 9759d09
test: add test cases for Integrated Channels logger
sameeramin 7cedb99
Merge branch 'master' into sameeramin/ENT-10900
sameeramin f536f23
chore: bump version to 6.4.3
sameeramin 93bed53
Merge branch 'master' into sameeramin/ENT-10900
sameeramin 235515d
fix: test_logger to avoid polluting global logging state
sameeramin 8f6cb07
refactor: Use direct logger methods with 'extra' for context in integ…
sameeramin 448f34d
refactor: integrated channels logging
sameeramin 8b94bcd
test: add more unit tests to meet coverage threshold
sameeramin 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,128 @@ | ||
| import json | ||
| import logging | ||
| import sys | ||
| from datetime import datetime | ||
| from django.conf import settings | ||
| from utils import generate_formatted_log | ||
|
|
||
| USE_JSON_LOGGING = getattr(settings, 'INTEGRATED_CHANNELS_JSON_LOGGING', False) | ||
|
|
||
|
|
||
| class IntegratedChannelsFormatter(logging.Formatter): | ||
| """ | ||
| Custom formatter for integrated channels that supports both JSON and string formats. | ||
| """ | ||
|
|
||
| def __init__(self): | ||
| self.use_json = USE_JSON_LOGGING | ||
| super().__init__() | ||
|
|
||
| def format(self, record): | ||
| if self.use_json: | ||
| log_entry = { | ||
| 'timestamp': datetime.fromtimestamp(record.created).strftime('%Y-%m-%d %H:%M:%S,%f')[:-3], | ||
sameeramin marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| 'level': record.levelname, | ||
| 'logger': record.name, | ||
sameeramin marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| 'message': record.getMessage(), | ||
| 'module': record.module, | ||
| 'function': record.funcName, | ||
| 'line': record.lineno | ||
| } | ||
|
|
||
sameeramin marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| log_entry['service'] = 'integrated_channels' | ||
|
|
||
sameeramin marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| if record.exc_info: | ||
| log_entry['error.kind'] = record.exc_info[0].__name__ | ||
| log_entry['error.message'] = str(record.exc_info[1]) | ||
| log_entry['error.stack'] = self.formatException(record.exc_info) | ||
|
|
||
sameeramin marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
sameeramin marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| # Add any extra attributes related to integrated channels | ||
| if hasattr(record, 'channel_code'): | ||
| log_entry['integrated_channel.code'] = record.channel_code | ||
| if hasattr(record, 'enterprise_customer_uuid'): | ||
| log_entry['integrated_channel.customer_uuid'] = record.enterprise_customer_uuid | ||
| if hasattr(record, 'plugin_configuration_id'): | ||
| log_entry['integrated_channel.configuration_id'] = record.plugin_configuration_id | ||
| if hasattr(record, 'lms_user_id'): | ||
| log_entry['integrated_channel.user_id'] = record.lms_user_id | ||
| if hasattr(record, 'course_or_course_run_key'): | ||
| log_entry['integrated_channel.course_or_course_run_key'] = record.course_or_course_run_key | ||
| if hasattr(record, 'transmission_type'): | ||
| log_entry['integrated_channel.transmission_type'] = record.transmission_type | ||
| if hasattr(record, 'enterprise_enrollment_id'): | ||
| log_entry['integrated_channel.enrollment_id'] = record.enterprise_enrollment_id | ||
|
|
||
|
|
||
| for key, value in record.__dict__.items(): | ||
| if key.startswith('dd'): | ||
| log_entry[key] = value | ||
|
|
||
| return json.dumps(log_entry, separators=(',', ':')) | ||
sameeramin marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| else: | ||
| return super().format(record) | ||
|
|
||
|
|
||
| def get_integrated_channels_logger(name=None): | ||
| """ | ||
| Get a configured logger for integrated channels. | ||
|
|
||
| Args: | ||
| name (str): Logger name, defaults to 'integrated_channels' | ||
| use_json (bool): Whether to use JSON formatting | ||
|
|
||
| Returns: | ||
| logging.Logger: Configured logger instance | ||
| """ | ||
| logger_name = name or 'integrated_channels' | ||
| logger = logging.getLogger(logger_name) | ||
|
|
||
| # Avoid adding handlers multiple times | ||
| if logger.handlers: | ||
| return logger | ||
|
|
||
| # Create console handler | ||
| console_handler = logging.StreamHandler(sys.stdout) | ||
| console_handler.setLevel(logging.INFO) | ||
sameeramin marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| # Set formatter | ||
| formatter = IntegratedChannelsFormatter() | ||
| console_handler.setFormatter(formatter) | ||
|
|
||
| # Configure logger | ||
| logger.addHandler(console_handler) | ||
| logger.setLevel(logging.INFO) | ||
| logger.propagate = False # Prevent duplicate logs | ||
|
|
||
| return logger | ||
|
|
||
|
|
||
|
|
||
| def log_with_context(logger_instance: logging.Logger, level: str, message: str, exc_info=False, **context: dict) -> None: | ||
| """ | ||
| Log a message with additional context. | ||
|
|
||
| Args: | ||
| logger_instance: Logger to use | ||
| level (str): Log level (INFO, ERROR, etc.) | ||
| message: Log message | ||
| **context: Additional context fields | ||
| """ | ||
| # Handle exception level specially | ||
| if level.upper() == 'EXCEPTION': | ||
| context_logger = logger_instance.exception | ||
| exc_info = True | ||
| else: | ||
| context_logger = getattr(logger_instance, level.lower()) | ||
|
|
||
| if USE_JSON_LOGGING: | ||
| context_logger(message, extra=context, exc_info=exc_info) | ||
| else: | ||
| formatted_message = generate_formatted_log( | ||
| channel_name=context.get("channel_name", None), | ||
| enterprise_customer_uuid=context.get("enterprise_customer_uuid", None), | ||
| lms_user_id=context.get("lms_user_id", None), | ||
| course_or_course_run_key=context.get("course_or_course_run_key", None), | ||
| message=message, | ||
| plugin_configuration_id=context.get("plugin_configuration_id", None) | ||
| ) | ||
sameeramin marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| context_logger(formatted_message) | ||
sameeramin marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
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.
Uh oh!
There was an error while loading. Please reload this page.