Skip to content
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 3 commits into from
Oct 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ dependencies = [
"isort~=5.12.0",
"libcst~=1.1.0",
"pylint~=3.0.0",
"python-json-logger~=2.0.0",
"PyYAML~=6.0.0",
"semgrep~=1.45.0",
"wrapt~=1.15.0",
Expand Down
6 changes: 5 additions & 1 deletion src/codemodder/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,9 +139,13 @@ def parse_args(argv, codemod_registry):
"--log-format",
type=OutputFormat,
default=OutputFormat.HUMAN,
choices=[str(x).split(".")[-1].lower() for x in list(OutputFormat)],
choices=[OutputFormat.HUMAN, OutputFormat.JSON],
help="the format for the log output",
)
parser.add_argument(
"--project-name",
help="optional descriptive name for the project used in log output",
)
parser.add_argument(
"--path-exclude",
action=CsvListAction,
Expand Down
2 changes: 1 addition & 1 deletion src/codemodder/codemodder.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ def run(original_args) -> int:
)
return 1

configure_logger(argv.verbose)
configure_logger(argv.verbose, argv.log_format, argv.project_name)

log_section("startup")
logger.info("codemodder: python/%s", __VERSION__)
Expand Down
48 changes: 42 additions & 6 deletions src/codemodder/logging.py
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")

Expand All @@ -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):
Copy link
Member Author

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.

Copy link
Contributor

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.

Copy link
Member Author

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.

Copy link
Contributor

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.

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

Check warning on line 39 in src/codemodder/logging.py

View check run for this annotation

Codecov / codecov/patch

src/codemodder/logging.py#L32-L39

Added lines #L32 - L39 were not covered by tests


def log_section(section_name: str):
"""
Expand All @@ -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:
Copy link
Contributor

Choose a reason for hiding this comment

The 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,
)
18 changes: 18 additions & 0 deletions tests/test_logging.py
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"
)