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

[f-string 1/2] Remove mylog formatting strings #2820

Merged
merged 8 commits into from
Aug 7, 2020

Conversation

cphyc
Copy link
Member

@cphyc cphyc commented Aug 6, 2020

PR Summary

Replaces all occurrence of mylog.info("Some information message about %s %s" % ("foo", "bar")) by mylog.info("Some information message about %s %s", "foo", "bar")

PR Checklist

  • pass black --check yt/
  • pass isort . --check --diff
  • pass flake8 yt/
  • revert insane loglevel to initial value once tests pass

Extra information

This relies on the following code to detect the occurences:

import argparse
import ast
import os
import re
from glob import glob

parser = argparse.ArgumentParser()
parser.add_argument("folder", type=str, default=".")
parser.add_argument("-v", "--verbose", action="store_true")


class MyLogVisitor(ast.NodeVisitor):
    def __init__(self, filename, source):
        self.filename = filename
        self.source = source

    def visit_Call(self, node):
        if (
            isinstance(node, ast.Call)
            and isinstance(node.func, ast.Attribute)
            and hasattr(node.func.value, "id")
            and node.func.value.id == "mylog"
            and node.func.attr in ("debug", "info", "warn", "error", "warning", "critical")
            and not isinstance(node.args[0], ast.Str)
        ):
            lstart = max(0, node.lineno - 2)
            lend = min(len(self.source), node.lineno + 2)
            print(f"{self.filename}:{node.lineno}:{node.col_offset} error")

        self.generic_visit(node)


def main():
    args = parser.parse_args()

    # Find filenames
    if os.path.isfile(args.folder):
        filenames = [args.folder]
    else:
        filenames = []
        for root, dirs, files in os.walk(args.folder):
            if '__pycache__' in root:
                continue
            for fn in files:
                if fn.endswith('.py'):
                    path = os.path.join(root, fn)
                    filenames.append(path)
        filenames = sorted(filenames)

    # Find filenames
    for fn in filenames:
        if args.verbose:
            print(f"Analysing {fn}")
        with open(fn) as f:
            line_by_line = f.readlines()
            f.seek(0)
            lines = f.read()
        try:
            tree = ast.parse(lines, fn)
        except SyntaxError as e:
            print(e)
        mlv = MyLogVisitor(fn, line_by_line)
        mlv.visit(tree)


if __name__ == "__main__":
    main()

If you're using vs code, you can also add a problem detector using

{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "2.0.0",
    "tasks": [
        {
            "label": "find bad mylog calls",
            "type": "shell",
            "command": "python /path/to/find_mylog_errors.py .",
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "isBackground": false,
            "problemMatcher": {
                "owner": "python",
                "fileLocation": ["relative", "${workspaceFolder}"],
                "pattern": {
                  "regexp": "^(.*):(\\d+):(\\d+) \\s+(warning|error)$",
                  "file": 1,
                  "line": 2,
                  "column": 3,
                  "severity": 4
                }
              }
        }
    ]
}

@cphyc cphyc changed the title Remove mylog formatting strings [f-string 1/2] Remove mylog formatting strings Aug 6, 2020
@neutrinoceros
Copy link
Member

Looks like this would enable solving #2757 with a mere call to flynt yt/ !!! Love it.

@neutrinoceros neutrinoceros added code style Related to linting tools enhancement Making something better labels Aug 6, 2020
@neutrinoceros
Copy link
Member

neutrinoceros commented Aug 6, 2020

Thanks for including the detection script, this allowed me to catch this line

            and node.func.attr in ("debug", "info", "warn", "error")

where you forgot to include the fifth and ultimate logging level "critical" ! Also "warning" exists and I'm pretty sure it's still used in yt (though it's a deprecated alias for "warn", see https://docs.python.org/3/library/logging.html#logging.Logger.warning)

edit: my bad, it's the other way around, warn is the deprecated one. It was addressed in #2285, but we still have 4 occurrences of it in the code base (two of which are in the RAMSES frontend 😛 )

@cphyc
Copy link
Member Author

cphyc commented Aug 6, 2020

Thanks for including the detection script, this allowed me to catch this line

            and node.func.attr in ("debug", "info", "warn", "error")

where you forgot to include the fifth and ultimate logging level "critical" ! Also "warning" exists and I'm pretty sure it's still used in yt (though it's a deprecated alias for "warn", see https://docs.python.org/3/library/logging.html#logging.Logger.warning)

edit: my bad, it's the other way around, warn is the deprecated one. It was addressed in #2285, but we still have 4 occurrences of it in the code base (two of which are in the RAMSES frontend stuck_out_tongue )

Good catch, and you're right that I missed a handful of them!

@neutrinoceros
Copy link
Member

mylog.critical is actually never used atm, so it doesn't make a difference actually, but I see you caught a lot more anyway, well done !

@@ -2,8 +2,13 @@
7edfcee093cca277307aabdb180e0ffc69768291
81418e459f16c48d6b7a75d6ef8035dfe9651b39

# transisiton to black
# transition to black
Copy link
Member

Choose a reason for hiding this comment

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

oops, this is on me, thanks !

Copy link
Member

@matthewturk matthewturk left a comment

Choose a reason for hiding this comment

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

Awesome

@cphyc cphyc mentioned this pull request Aug 6, 2020
4 tasks
@cphyc cphyc marked this pull request as ready for review August 6, 2020 14:20
@@ -238,14 +238,6 @@ def check_parallel_rank(*args, **kwargs):
return check_parallel_rank


def rootloginfo(*args):
Copy link
Member Author

Choose a reason for hiding this comment

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

Note: this was not used anywhere.

@cphyc
Copy link
Member Author

cphyc commented Aug 6, 2020

@matthewturk @neutrinoceros before merging this, do you think we could set the default logging level to 40 (and then revert it) so that all logs are visited and we're sure nothing is going wrong?

@neutrinoceros
Copy link
Member

sure ! may as well go for 50 ! :-) (disregard if I'm mistaken, I think this is the maximal meaningful level)

@matthewturk
Copy link
Member

matthewturk commented Aug 6, 2020 via email

Copy link
Member

@neutrinoceros neutrinoceros left a comment

Choose a reason for hiding this comment

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

Found two remaining unjustified strings concatenations, otherwise all good ! Thanks again for doing this !

setupext.py Outdated Show resolved Hide resolved
yt/visualization/volume_rendering/old_camera.py Outdated Show resolved Hide resolved
Co-authored-by: Clément Robert <cr52@protonmail.com>
@cphyc cphyc marked this pull request as draft August 6, 2020 15:19
@cphyc
Copy link
Member Author

cphyc commented Aug 6, 2020

I'm converting to draft until the tests are done, after that I'll revert 19f78f1 and that'll be good to go!

@cphyc cphyc marked this pull request as ready for review August 6, 2020 22:13
@cphyc
Copy link
Member Author

cphyc commented Aug 6, 2020

Good to go now!

@neutrinoceros
Copy link
Member

Awesome ! There's a huge queue on CI runner right now, so I'll happily merge this in 10 to 12 hours when it clears.
For immediate reference, is this the travis job that ran with all log entries activated ?
https://tests.yt-project.org/job/yt_py38_git/928/

@cphyc
Copy link
Member Author

cphyc commented Aug 7, 2020

Yes ; it ran successfully before reverting the commit that was (temporarily) setting the default log value to 50.

@cphyc cphyc mentioned this pull request Aug 7, 2020
4 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
code style Related to linting tools enhancement Making something better
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants