Skip to content

94 replace print with logging - #95

Merged
maxnutz merged 6 commits into
mainfrom
94-replace-print-with-logging
Aug 3, 2026
Merged

94 replace print with logging#95
maxnutz merged 6 commits into
mainfrom
94-replace-print-with-logging

Conversation

@maxnutz

@maxnutz maxnutz commented Jul 31, 2026

Copy link
Copy Markdown
Owner

Short description of this pull request

Implement a logging structure to replace the prints in all files. Adapt the tests on printing warnings etc.


Checklist

Before asking for review, please make shure, the following steps are completed (whenever possible):

  • Changes are tested locally and behave as expected.
  • Code is documented using numpy-styled function docstrings
  • All tests succeed
  • All Sourcery-bot review suggestions have been implemented or rejected with an explanation.

Sourcery-Bot starts to review your pull request, whenever it is created. This may take some time. After having finished these steps, please request for review in the Pull Request.

Summary by Sourcery

Introduce a centralized logging strategy across the package and update the CLI and tests to use it instead of print-based messaging.

New Features:

  • Add a CLI --log-level option and a package-level setup_logging helper to configure logging behavior.

Enhancements:

  • Replace print-based warnings and info messages in processing and statistics modules with module-specific loggers and structured log messages.
  • Add debug-level logging of result shapes in key statistics functions to aid diagnostics and performance monitoring.

Documentation:

  • Extend contributor documentation and README with guidelines for using logging in new code and statistics functions.

Tests:

  • Update tests to assert on logged messages via caplog instead of stdout via capsys when warnings or infos are emitted.
  • Add logging imports and configuration in tests where necessary to validate the new logging behavior.

@sourcery-ai

sourcery-ai Bot commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

Reviewer's Guide

Replace ad-hoc print-based messaging with structured logging across core modules and tests, introducing a central logging setup and updating documentation to reflect the new logging conventions.

Sequence diagram for CLI run with logging configuration

sequenceDiagram
    actor User
    participant workflow_main as workflow.main
    participant utils_setup_logging as utils.setup_logging
    participant logger_workflow as workflow.logger
    participant logger_statistics as statistics_functions.logger
    participant logging_system as logging

    User ->> workflow_main: main()
    workflow_main ->> workflow_main: build_parser()
    workflow_main ->> workflow_main: parse_args()
    workflow_main ->> utils_setup_logging: setup_logging(level=args.log_level)
    alt args.log_level == "DEBUG"
        workflow_main ->> logger_workflow: logger.info(...)
    end
    workflow_main ->> workflow_main: resolve_config_path(config)
    workflow_main ->> logging_system: logger.warning(...) [no config provided]
    workflow_main ->> logger_statistics: logger.debug(...)
    logger_statistics ->> logging_system: logger.debug(...)
    logging_system -->> User: log output (configured level and format)
Loading

File-Level Changes

Change Details Files
Replace print-based warnings/info in core processing code with module-level loggers using the standard logging API.
  • Import logging and define logger = logging.getLogger(name) in processing modules.
  • Convert print calls in timestamp formatting, statistics dispatch, unit resolution, and network config loading to logger.warning/info with parameterized messages.
  • Adjust docstrings to describe warnings as logged instead of printed.
pypsa_validation_processing/class_definitions.py
pypsa_validation_processing/statistics_functions.py
Introduce centralized logging configuration and CLI control over log level in the workflow entrypoint.
  • Add setup_logging utility that configures root logging via logging.basicConfig with a standard format.
  • Call setup_logging from workflow.main() and add a --log-level CLI argument to control logging verbosity.
  • Replace a print warning in resolve_config_path with logger.warning and add an informational log when DEBUG logging is used.
pypsa_validation_processing/workflow.py
pypsa_validation_processing/utils.py
Update tests to assert logged messages via caplog instead of captured stdout via capsys.
  • Switch tests from capsys.readouterr() to pytest caplog for warning/info assertions.
  • Scope log-level expectations with caplog.at_level and assert on log records’ level and message content.
  • Adjust tests relying on print output to work with the new logging-based behavior.
tests/test_network_processor.py
tests/test_format_timestamps.py
tests/test_statistics_functions.py
tests/test_unit_conversion.py
Document new logging expectations for contributors and statistics function implementations.
  • Add a Logging section to contributing.md describing logger usage per module and central configuration in workflow.main().
  • Update README to require logging in new statistics functions, extending the contribution checklist.
docs/contributing.md
README.md

Possibly linked issues

  • #Replace print() with structured logging: PR introduces setup_logging, module loggers, replaces all prints, updates tests to caplog, and documents logging usage, matching the issue.

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 3 issues, and left some high level feedback:

  • In build_parser(), the --log-level argument defaults to "DEBUG" while the help text says it defaults to WARNING; align the default and the help string to avoid confusion.
  • Several logging calls (e.g. the logger.debug calls in statistics_functions.py) use f-strings; consider switching to %-style formatting with arguments to avoid unnecessary string construction when the log level is disabled.
  • The logger.info(target_unit) call in _get_unit_from_common_definitions logs a bare value without context; include a descriptive message so that log output is self-explanatory.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In `build_parser()`, the `--log-level` argument defaults to `"DEBUG"` while the help text says it defaults to WARNING; align the default and the help string to avoid confusion.
- Several logging calls (e.g. the `logger.debug` calls in `statistics_functions.py`) use f-strings; consider switching to `%`-style formatting with arguments to avoid unnecessary string construction when the log level is disabled.
- The `logger.info(target_unit)` call in `_get_unit_from_common_definitions` logs a bare value without context; include a descriptive message so that log output is self-explanatory.

## Individual Comments

### Comment 1
<location path="pypsa_validation_processing/workflow.py" line_range="54-55" />
<code_context>
         default=None,
         help="Path to YAML config file. Defaults to packaged config.",
     )
+    parser.add_argument(
+        "--log-level",
+        default="DEBUG",
+        choices=["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"],
</code_context>
<issue_to_address>
**issue:** CLI log-level default and help text are inconsistent and may surprise users.

The default is set to `DEBUG`, but the help text says it defaults to `WARNING`, which is inconsistent and may surprise users given the new debug logging. Please align the actual default with the help text (e.g., change the default to `WARNING` to match the docstring and keep debug logs opt‑in, or update the help text if `DEBUG` is intended).
</issue_to_address>

### Comment 2
<location path="tests/test_format_timestamps.py" line_range="93-96" />
<code_context>


-def test_format_timestamps_sets_nat_on_localization_failure(capsys):
+def test_format_timestamps_sets_nat_on_localization_failure(caplog):
     class FakeTimestamp:
         tz = None
</code_context>
<issue_to_address>
**suggestion (testing):** Consider also asserting on the second warning about columns set to NaT

This test currently asserts only the warning for failed localization. To fully validate the logging behavior described in the docstring, please also assert that a WARNING containing "columns set to NaT" appears in `caplog.records`.

Suggested implementation:

```python
def test_format_timestamps_sets_nat_on_localization_failure(caplog):
    class FakeTimestamp:
        tz = None
        tzinfo = None

    df = pd.DataFrame([[1.0]], columns=["2050-01-01 00:00:00"])

    with caplog.at_level(logging.WARNING):
        format_timestamps(df)

    warning_messages = [
        record.getMessage()
        for record in caplog.records
        if record.levelno == logging.WARNING
    ]

    # Assert the original localization failure warning is logged
    assert any("localization" in msg.lower() for msg in warning_messages)

    # Assert the additional warning about columns set to NaT is also logged
    assert any("columns set to NaT" in msg for msg in warning_messages)

```

If the existing test already contains assertions on the localization failure warning, you may want to:
1. Keep those assertions and only add the new `warning_messages` construction and the `assert any("columns set to NaT" ...)` line, rather than replacing the whole function body.
2. Adjust the string used in the localization warning assertion (`"localization" in msg.lower()`) to match the exact wording used by `format_timestamps`, or remove that assertion if it duplicates an existing one.
</issue_to_address>

### Comment 3
<location path="README.md" line_range="189" />
<code_context>
 - Create a new branch linked to the respective issue
 - Write your pypsa-statistics and add it as a separate function to [statistics_functions.py](https://github.com/maxnutz/pypsa_validation_processing/blob/main/pypsa_validation_processing/statistics_functions.py) (please note the [naming and structural conventions](https://github.com/maxnutz/pypsa_validation_processing/tree/main#variables-statistics---functions)!)
-- add a comprehensive docstring to your function 
+- add a comprehensive docstring to your function and implement loggings
 - add the mapping variable_name <> function_name to [mapping.default.yaml](https://github.com/maxnutz/pypsa_validation_processing/blob/main/pypsa_validation_processing/configs/mapping.default.yaml) (and your personal mapping-file)
 - Add a testing routine for your Function to `tests/` - stick to the [testing-README](https://github.com/maxnutz/pypsa_validation_processing/blob/main/tests/README.md)
</code_context>
<issue_to_address>
**issue (typo):** Use singular "logging" instead of "loggings".

"implement loggings" is awkward usage; consider "implement logging" or "add appropriate logging" for clearer wording.

```suggestion
- add a comprehensive docstring to your function and add appropriate logging
```
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread pypsa_validation_processing/workflow.py
Comment thread tests/test_format_timestamps.py
Comment thread README.md Outdated
maxnutz and others added 3 commits August 3, 2026 08:40
@maxnutz
maxnutz merged commit 10ec08e into main Aug 3, 2026
2 checks passed
@maxnutz
maxnutz deleted the 94-replace-print-with-logging branch August 3, 2026 07:11
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant