-
Notifications
You must be signed in to change notification settings - Fork 10
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 optional JSON logging #83
Merged
Merged
Changes from all commits
Commits
Show all changes
3 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
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,6 +1,9 @@ | ||
from enum import Enum | ||
import logging | ||
import sys | ||
from typing import Optional | ||
|
||
from pythonjsonlogger import jsonlogger | ||
|
||
logger = logging.getLogger("codemodder") | ||
|
||
|
@@ -13,6 +16,28 @@ | |
HUMAN = "human" | ||
JSON = "json" | ||
|
||
def __str__(self): | ||
"""For rendering properly in argparse help.""" | ||
return self.value.lower() | ||
|
||
|
||
class CodemodderJsonFormatter(jsonlogger.JsonFormatter): | ||
project_name: Optional[str] | ||
|
||
def __init__(self, *args, project_name: Optional[str] = None, **kwargs): | ||
self.project_name = project_name | ||
super().__init__(*args, **kwargs) | ||
|
||
def add_fields(self, log_record, record, message_dict): | ||
super().add_fields(log_record, record, message_dict) | ||
log_record["timestamp"] = log_record.pop("asctime") | ||
log_record.move_to_end("timestamp", last=False) | ||
log_record["level"] = record.levelname.upper() | ||
log_record["file"] = record.filename | ||
log_record["line"] = record.lineno | ||
if self.project_name: | ||
log_record["project-name"] = self.project_name | ||
|
||
|
||
def log_section(section_name: str): | ||
""" | ||
|
@@ -30,22 +55,33 @@ | |
logger.log(level, " - %s", predicate(item) if predicate else item) | ||
|
||
|
||
def configure_logger(verbose: bool): | ||
def configure_logger( | ||
verbose: bool, log_format: OutputFormat, project_name: Optional[str] = None | ||
): | ||
""" | ||
Configure the logger based on the verbosity level. | ||
""" | ||
log_level = logging.DEBUG if verbose else logging.INFO | ||
|
||
# TODO: this should all be conditional on the output format | ||
stdout_handler = logging.StreamHandler(sys.stdout) | ||
stdout_handler.setLevel(log_level) | ||
stdout_handler.addFilter(lambda record: record.levelno <= logging.WARNING) | ||
handlers = [stdout_handler] | ||
|
||
stderr_handler = logging.StreamHandler(sys.stderr) | ||
stderr_handler.setLevel(logging.ERROR) | ||
match log_format: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. <3 |
||
case OutputFormat.HUMAN: | ||
stdout_handler.addFilter(lambda record: record.levelno <= logging.WARNING) | ||
stderr_handler = logging.StreamHandler(sys.stderr) | ||
stderr_handler.setLevel(logging.ERROR) | ||
handlers.append(stderr_handler) | ||
case OutputFormat.JSON: | ||
formatter = CodemodderJsonFormatter( | ||
"%(asctime) %(level) %(message) %(file) %(line)", | ||
project_name=project_name, | ||
) | ||
stdout_handler.setFormatter(formatter) | ||
|
||
logging.basicConfig( | ||
format="%(message)s", | ||
level=log_level, | ||
handlers=[stdout_handler, stderr_handler], | ||
handlers=handlers, | ||
) |
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 |
---|---|---|
@@ -0,0 +1,18 @@ | ||
from pythonjsonlogger import jsonlogger | ||
|
||
from codemodder.logging import OutputFormat, configure_logger | ||
|
||
|
||
def test_json_logger(mocker): | ||
basic_config = mocker.patch("logging.basicConfig") | ||
configure_logger(False, OutputFormat.JSON, "test-project") | ||
assert basic_config.call_count == 1 | ||
assert basic_config.call_args[1]["format"] == "%(message)s" | ||
assert isinstance( | ||
basic_config.call_args[1]["handlers"][0].formatter, | ||
jsonlogger.JsonFormatter, | ||
) | ||
assert ( | ||
basic_config.call_args[1]["handlers"][0].formatter.project_name | ||
== "test-project" | ||
) |
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.
I'm tempted to ignore this block for the purposes of coverage. I tried to write some tests here but it's proving fairly difficult to get the mocks right.
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'm super surprised codecov says most of this isn't tested. Curious, if you put a debugger in here and run codemodder as pixeebot would, it does it it, right? That would tell me integration tests would test this but right now we only calc coverage based on unit tests. This makes sense bc the way we run integration tests with subprocess.run creates a separate process and pytest / cov can't calculate coverage there.
Is there any help from the python-json-logger docs in regards to testing? Does chatgpt help in any way here? If you've tried these avenues and felt like you've spent sufficient time, I would be ok with adding no-cover here though it does break my heart a little.
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.
This codepath is only covered if we use
--log-format=json
which probably doesn't happen in any of the integration tests right now. This basically just boils down to level of effort vs reward right now and I can't afford to spend any more time trying to get this covered.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.
Totally fine, ticket and move on. Could be a good starter task for someone who may join in the upcoming months or just an easy "end of day" task.