Transport-for-the-North / caf.toolkit

Toolkit of transport planning and appraisal functionalities.
https://caftoolkit.readthedocs.io/en/stable/
Other
0 stars 2 forks source link

Logging Simple Warning Format #135

Open MattBuckley-TfN opened 3 months ago

MattBuckley-TfN commented 3 months ago

Create a new function to replace the default warnings.formatwarning to provide a simpler warning format which doesn't span multiple lines, example function below.

def simple_warning_format(
    message: Warning | str,
    category: type[Warning],
    filename: str,
    lineno: int,
    *args,
    **kwargs,
) -> str:
    del args, kwargs
    path = pathlib.Path(filename)
    return f"{path.parent.name}/{path.name}:{lineno}: {category.__name__}: {message}"

The formatwarning function in warnings can be overwritten by the simple function above (warnings.formatwarning = simple_warning_format) but the old function should be kept track of so it can be reset if needed. This could also be integrated within LogHelpers to by default use the simple function and reset to the original in the class __exit__ method.

It would be worth clarifying what the best format for the function is.

MattBuckley-TfN commented 3 weeks ago

This is the default warning format

C:\Users\MattBuckley\Documents\GitHub\caf.toolkit\.temp\scratch.py:18: UserWarning: test warning default format
  warnings.warn("test warning default format", UserWarning)

This is the format output from the function above

.temp/scratch.py:34: UserWarning: test simple warning format

When either warnings are captured by the logging they will still following the logging format 10:15 [ WARNING ] {message} where message is the full text from above including the filepaths e.g.

10:15 [ WARNING ] .temp/scratch.py:34: UserWarning: test simple warning format

@BenTaylor-TfN, @isaac-tfn - any thoughts on the new format?

BenTaylor-TfN commented 3 weeks ago

The removal of warnings.warn("test warning default format", UserWarning) is definitely appreciated here as it's just repeated information.

I'm not sure how I feel about the removal of the full path beforehand though. It can sometimes be useful to see exactly what file is raising a warning, obscuring some of the path might lead to harder to find bugs in future.

MattBuckley-TfN commented 3 weeks ago

New output:

C:\Users\MattBuckley\Documents\GitHub\caf.toolkit\.temp\scratch.py:33: UserWarning: test simple warning format

New function:

def simple_warning_format(
    message: Warning | str,
    category: type[Warning],
    filename: str,
    lineno: int,
    *args,
    **kwargs,
) -> str:
    del args, kwargs
    return f"{filename}:{lineno}: {category.__name__}: {message}"