Git Product home page Git Product logo

andy-landy / traceback_with_variables Goto Github PK

View Code? Open in Web Editor NEW
678.0 5.0 27.0 586 KB

Adds variables to python traceback. Simple, lightweight, controllable. Debug reasons of exceptions by logging or pretty printing colorful variable contexts for each frame in a stacktrace, showing every value. Dump locals environments after errors to console, files, and loggers. Works in Jupyter and IPython. Install with pip or conda.

License: MIT License

Python 100.00%
python traceback locals logging debugging print variables python3 stacktrace arguments

traceback_with_variables's Introduction

Example

Python Traceback (Error Message) Printing Variables

Very simple to use, but versatile when needed. Try for debug and keep for production.

Actions Status Codecov Language grade: Python License: MIT PyPI PyPI Platform Annotations coverage No-OOP Dependencies Open In Colab Gitter


“It is useless work that darkens the heart.” – Ursula K. Le Guin

Tired of useless job of putting all your variables into debug exception messages? Just stop it. Automate it and clean your code. Once and for all.


Contents: Installation | 🚀 Quick Start | Colors | How does it save my time? | Examples and recipes | Reference | FAQ


⚠️ I'm open to update this module to meet new use cases and to make using it easier and fun: so any proposal or advice or warning is very welcome and will be taken into account of course. When I started it I wanted to make a tool meeting all standard use cases. I think in this particular domain this is rather achievable, so I'll try. Note next_version branch also. Have fun!


Installation

pip install traceback-with-variables==2.0.4
conda install -c conda-forge traceback-with-variables=2.0.4

🚀 Quick Start

Using without code editing, running your script/command/module:

traceback-with-variables tested_script.py ...srcipt's args...

Simplest usage in regular Python, for the whole program:

    from traceback_with_variables import activate_by_import

Simplest usage in Jupyter or IPython, for the whole program:

    from traceback_with_variables import activate_in_ipython_by_import

Decorator, for a single function:

    @prints_exc
    # def main(): or def some_func(...):

Context, for a single code block:

    with printing_exc():

Work with traceback lines in a custom manner:

    lines = list(iter_exc_lines(e))

No exception but you want to print the stack anyway?:

    print_cur_tb()

Using a logger [with a decorator, with a context]:

    with printing_exc(file_=LoggerAsFile(logger)):
    # or
    @prints_exc(file_=LoggerAsFile(logger)): 

Print traceback in interactive mode after an exception:

    >>> print_exc()

Customize any of the previous examples:

    default_format.max_value_str_len = 10000
    default_format.skip_files_except = 'my_project'

Colors

Example

How does it save my time?

  • Turn a code totally covered by debug formatting from this:

      def main():
          sizes_str = sys.argv[1]
          h1, w1, h2, w2 = map(int, sizes_str.split())
    -     try:
              return get_avg_ratio([h1, w1], [h2, w2])
    -     except:
    -         logger.error(f'something happened :(, variables = {locals()[:1000]}')
    -         raise
    -         # or
    -         raise MyToolException(f'something happened :(, variables = {locals()[:1000]}')
              
      def get_avg_ratio(size1, size2):
    -     try:
              return mean(get_ratio(h, w) for h, w in [size1, size2])
    -     except:
    -         logger.error(f'something happened :(, size1 = {size1}, size2 = {size2}')
    -         raise
    -         # or
    -         raise MyToolException(f'something happened :(, size1 = {size1}, size2 = {size2}')
    
      def get_ratio(height, width):
    -     try:
              return height / width
    -     except:
    -         logger.error(f'something happened :(, width = {width}, height = {height}')
    -         raise
    -         # or
    -         raise MyToolException(f'something happened :(, width = {width}, height = {height}')

    into this (zero debug code):

    + from traceback_with_variables import activate_by_import
    
      def main():
          sizes_str = sys.argv[1]
          h1, w1, h2, w2 = map(int, sizes_str.split())
          return get_avg_ratio([h1, w1], [h2, w2])
              
      def get_avg_ratio(size1, size2):
          return mean(get_ratio(h, w) for h, w in [size1, size2])
    
      def get_ratio(height, width):
          return height / width

    And obtain total debug info spending 0 lines of code:

    Traceback with variables (most recent call last):
      File "./temp.py", line 7, in main
        return get_avg_ratio([h1, w1], [h2, w2])
          sizes_str = '300 200 300 0'
          h1 = 300
          w1 = 200
          h2 = 300
          w2 = 0
      File "./temp.py", line 10, in get_avg_ratio
        return mean([get_ratio(h, w) for h, w in [size1, size2]])
          size1 = [300, 200]
          size2 = [300, 0]
      File "./temp.py", line 10, in <listcomp>
        return mean([get_ratio(h, w) for h, w in [size1, size2]])
          .0 = <tuple_iterator object at 0x7ff61e35b820>
          h = 300
          w = 0
      File "./temp.py", line 13, in get_ratio
        return height / width
          height = 300
          width = 0
    builtins.ZeroDivisionError: division by zero
    
  • Automate your logging too:

    logger = logging.getLogger('main')
    
    def main():
        ...
        with printing_exc(file_=LoggerAsFile(logger))
            ...
    2020-03-30 18:24:31 main ERROR Traceback with variables (most recent call last):
    2020-03-30 18:24:31 main ERROR   File "./temp.py", line 7, in main
    2020-03-30 18:24:31 main ERROR     return get_avg_ratio([h1, w1], [h2, w2])
    2020-03-30 18:24:31 main ERROR       sizes_str = '300 200 300 0'
    2020-03-30 18:24:31 main ERROR       h1 = 300
    2020-03-30 18:24:31 main ERROR       w1 = 200
    2020-03-30 18:24:31 main ERROR       h2 = 300
    2020-03-30 18:24:31 main ERROR       w2 = 0
    2020-03-30 18:24:31 main ERROR   File "./temp.py", line 10, in get_avg_ratio
    2020-03-30 18:24:31 main ERROR     return mean([get_ratio(h, w) for h, w in [size1, size2]])
    2020-03-30 18:24:31 main ERROR       size1 = [300, 200]
    2020-03-30 18:24:31 main ERROR       size2 = [300, 0]
    2020-03-30 18:24:31 main ERROR   File "./temp.py", line 10, in <listcomp>
    2020-03-30 18:24:31 main ERROR     return mean([get_ratio(h, w) for h, w in [size1, size2]])
    2020-03-30 18:24:31 main ERROR       .0 = <tuple_iterator object at 0x7ff412acb820>
    2020-03-30 18:24:31 main ERROR       h = 300
    2020-03-30 18:24:31 main ERROR       w = 0
    2020-03-30 18:24:31 main ERROR   File "./temp.py", line 13, in get_ratio
    2020-03-30 18:24:31 main ERROR     return height / width
    2020-03-30 18:24:31 main ERROR       height = 300
    2020-03-30 18:24:31 main ERROR       width = 0
    2020-03-30 18:24:31 main ERROR builtins.ZeroDivisionError: division by zero
    
  • Free your exceptions of unnecessary information load:

    def make_a_cake(sugar, eggs, milk, flour, salt, water):
        is_sweet = sugar > salt
        is_vegan = not (eggs or milk)
        is_huge = (sugar + eggs + milk + flour + salt + water > 10000)
        if not (is_sweet or is_vegan or is_huge):
            raise ValueError('This is unacceptable, guess why!')
        ...
  • — Should I use it after debugging is over, i.e. in production?

    Yes, of course! That way it might save you even more time (watch out for sensitive data like passwords and tokens in you logs). Note: you can deploy more serious frameworks, e.g. Sentry :)


  • Stop this tedious practice in production:

    step 1: Notice some exception in a production service.
    step 2: Add more printouts, logging, and exception messages.
    step 3: Rerun the service.
    step 4: Wait till (hopefully) the bug repeats.
    step 5: Examine the printouts and possibly add some more info (then go back to step 2).
    step 6: Erase all recently added printouts, logging and exception messages.
    step 7: Go back to step 1 once bugs appear.

Examples and recipes

Reference

All functions have fmt= argument, a Format object with fields:

  • max_value_str_len max length of each variable string, -1 to disable, default=1000
  • max_exc_str_len max length of exception, should variable print fail, -1 to disable, default=10000
  • before number of code lines before the raising line, default=0
  • after number of code lines after the raising line, default=0
  • ellipsis_ string to denote long strings truncation, default=...
  • skip_files_except use to print only certain files; list of regexes, ignored if empty, default=None
  • brief_files_except use to print variables only in certain files; list of regexes, ignored if empty, default=None
  • custom_var_printers list of pairs of (filter, printer); filter is a name fragment, a type or a function or a list thereof; printer returns None to skip a var
  • color_scheme is None or one of ColorSchemes: .none , .common, .nice, .synthwave. None is for auto-detect

Just import it. No arguments, for real quick use in regular Python.

from traceback_with_variables import activate_by_import

Just import it. No arguments, for real quick use in Jupyter or IPython.

from traceback_with_variables import activate_in_ipython_by_import

Call once in the beginning of your program, to change how traceback after an uncaught exception looks.

def main():
    override_print_exc(...)

Call once in the beginning of your program, to change how traceback after an uncaught exception looks.

def main():
    override_print_exc(...)

Prints traceback for a given/current/last (first being not None in the priority list) exception to a file, default=sys.stderr. Convenient for manual console or Jupyter sessions or custom try/except blocks. Note that it can be called with a given exception value or it can auto discover current exception in an except: block or it can auto descover last exception value (long) after try/catch block.

print_exc()

Prints current traceback when no exception is raised.

print_cur_tb()

Function decorator, used for logging or simple printing of scoped tracebacks with variables. I.e. traceback is shorter as it includes only frames inside the function call. Program exiting due to unhandled exception still prints a usual traceback.

@prints_exc
def f(...):

@prints_exc(...)
def f(...):

Context manager (i.e. with ...), used for logging or simple printing of scoped tracebacks with variables. I.e. traceback is shorter as it includes only frames inside the with scope. Program exiting due to unhandled exception still prints a usual traceback.

with printing_exc(...):

A logger-to-file wrapper, to pass a logger to print tools as a file.


Iterates the lines, which are usually printed one-by-one in terminal.


Like iter_exc_lines but returns a single string.


Like iter_exc_lines but doesn't need an exception and prints upper frames..


Like iter_cur_tb_lines but returns a single string.


FAQ

  • In Windows console crash messages have no colors.

    The default Windows console/terminal cannot print [so called ansi] colors, but this is fixable , especially with modern Windows versions. Therefore colors are disabled by default, but you can enable them and check if it works in your case. You can force enable colors by passing --color-scheme common (for complete list of colors pass --help) console argument.

  • Windows console prints junk symbols when colors are enabled.

    The default Windows console/terminal cannot print [so called ansi] colors, but this is fixable , especially with modern Windows versions. If for some reason the colors are wrongly enabled by default, you can force disable colors by passing --color-scheme none console argument.

  • Bash tools like grep sometimes fail to digest the output when used with pipes (|) because of colors.

    Please disable colors by passing --color-scheme none console argument. The choice for keeping colors in piped output was made to allow convenient usage of head, tail, file redirection etc. In cases like | grep it might have issues, in which case you can disable colors.

  • Output redirected to a file in > output.txt manner has no colors when I cat it.

    This is considered a rare use case, so colors are disabled by default when outputting to a file. But you can force enable colors by passing --color-scheme common (for complete list of colors pass --help) console argument.

  • activate_by_import or global_print_exc don't work in Jupyter or IPython as if not called at all.

    In Jupyter or IPython you should use activate_in_ipython_by_import or global_print_exc_in_ipython. IPython handles exceptions differently than regular Python.

  • The server framework (flask, streamlit etc.) still shows usual tracebacks.

    In such frameworks tracebacks are printed not while exiting the program (the program continues running), hence you should override exception handling in a manner proper for the given framework. Please address the flask example.

  • How do I reduce output? I don't need all files or all variables.

    Use skip_files_except, brief_files_except, custom_var_printers to cut excess output.

  • I have ideas about good colors.

    Please fork, add a new ColorScheme to ColorSchemes and create a Pull Request to next_version branch. Choose the color codes and visually test it like python3 -m traceback_with_variables.main --color-scheme {its name} examples/for_readme_image.py.

  • My code doesn't work.

    Please post your case. You are very welcome!

  • Other questions or requests to elaborate answers.

    Please post your question or request. You are very welcome!

traceback_with_variables's People

Contributors

andy-landy avatar dominicj-nylas avatar synapticarbors avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

traceback_with_variables's Issues

How to reduce the output to a minimum?

Hi,

my use case for traceback_with_variables is mainly during development time. Therefore I just need a small overview what was wrong with the variables that actually caused the exception.

My question is: how can I customize it that the extra output that traceback_with_variables generates only comprises the very variables that lead to the exception?

Example:

Without using it, for this:

# from traceback_with_variables import activate_by_import
def main():
    n = 0
    x = 15
    print(1 / n)

main()

I get:

/home/usesr/venv/numba/bin/python3.6 /home/usesr/PycharmProjects/myProject/attic04.py
Traceback (most recent call last):
  File "/home/usesr/PycharmProjects/myProject/attic04.py", line 7, in <module>
    main()
  File "/home/usesr/PycharmProjects/myProject/attic04.py", line 5, in main
    print(1 / n)
ZeroDivisionError: division by zero

Process finished with exit code 1

With using it, I get:

/home/usesr/venv/numba/bin/python3.6 /home/usesr/PycharmProjects/myProject/attic04.py
Traceback with variables (most recent call last):
  File "/home/usesr/PycharmProjects/myProject/attic04.py", line 7, in <module>
    main()
      __name__ = '__main__'
      __doc__ = None
      __package__ = None
      __loader__ = <_frozen_importlib_external.SourceFileLoader object at 0x7f78c2d32f28>
      __spec__ = None
      __annotations__ = {}
      __builtins__ = <module 'builtins' (built-in)>
      __file__ = '/home/usesr/PycharmProjects/myProject/attic04.py'
      __cached__ = None
      activate_by_import = <module 'traceback_with_variables.activate_by_import' from '/home/usesr/venv/numba/lib/python3.6/site-packages/traceback_with_variables/activate_by_import.py'>
      main = <function main at 0x7f78c2d58e18>
  File "/home/usesr/PycharmProjects/myProject/attic04.py", line 5, in main
    print(1 / n)
      x = 15
      n = 0
builtins.ZeroDivisionError: division by zero

Process finished with exit code 1

Would it be possible to configure it (at one place in my code) that I only get this output:

/home/usesr/venv/numba/bin/python3.6 /home/usesr/PycharmProjects/myProject/attic04.py
Traceback (most recent call last):
  File "/home/usesr/PycharmProjects/myProject/attic04.py", line 7, in <module>
    main()
  File "/home/usesr/PycharmProjects/myProject/attic04.py", line 5, in main
    print(1 / n)
    n = 0
ZeroDivisionError: division by zero

Process finished with exit code 1

(so:
n = 0
lead to the exception, but
x = 15
was not part of the game.

As I have a lot of variables in my code, I get overwhelmed by the output and it takes me also time to find the value of the variable in the output that was causing the exception.

If I just could use a different import, that would be perfect for me :-) )

Integration with Django

To enable logging with traceback_with_variables for Django (and possibly other frameworks) the correct approach is to extend the standard Python logging integration so that it has a custom formatting function that uses traceback_with_variables. For example, in your settings.py you can add:

import traceback_with_variables

class CustomLogFormatter(logging.Formatter):
    def formatException(self, ei):
        return "\n".join(
            traceback_with_variables.iter_exc_lines(
                e=ei[1],
                fmt=traceback_with_variables.Format(
                    custom_var_printers=[
                        ("password", lambda _: "...hidden..."),
                        ("token", lambda _: "...hidden..."),
                    ]
                ),
            ),
        )

LOGGING = {
    "version": 1,
    "disable_existing_loggers": False,
    "formatters": {
        "verbose": {"format": "%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s"},
        "simple": {"format": "%(levelname)s %(message)s"},
        "custom": {  # <== our custom formatter
            "()": CustomLogFormatter,
            "format": "%(asctime)s %(levelname)s: %(message)s",
        },
    },
    "handlers": {
        "console": {"level": "INFO", "class": "logging.StreamHandler", "formatter": "custom"},
    },
    "loggers": {
        "django": {
            "handlers": ["console"],
            "propagate": True,
        },
        "django.request": {
            "handlers": ["console"],
            "level": "DEBUG",  # change debug level as appropiate
            "propagate": False,
        },
    },
    "root": {
        "handlers": ["console"],
        "level": "DEBUG",
    },
}

(writing this as an issue since I'm not sure where you'd like it in the documentation)

traceback_with_variables is not safe for production use due to password leaking, yet the documentation states "keep for production use"

Hi -

I am receiving CVE reports that my library (SQLAlchemy) is dumping passwords into log files. it of course is not, they are using this package in production to dump all private variables into their logs. I don't see any mechanism by which traceback_with_variables could recognize password strings that are necessarily present as cleartext within third party libraries.

I would propose that traceback_with_variables' documentation be amended to note that this tool is not safe for production use in any scenario where there are passwords or other secrets present at runtime. That way I can point people to this documentation when my package (or any of thousands of other packages that receive a password and/or secret within a private variable) is claimed to have CVEs in it.

Demo:

from traceback_with_variables import activate_by_import

def connect_to_something_witha_secret(host, username, password):
    raise Exception(f"could not connect to host: {host}")


def go():
    connect_to_something_witha_secret(
        "fakehost", "scott", "super_secret_password"
    )


go()

output:

Traceback with variables (most recent call last):
  File "/mnt/photon_home/classic/dev/sqlalchemy/test4.py", line 13, in <module>
    go()
      ...skipped... 12 vars
  File "/mnt/photon_home/classic/dev/sqlalchemy/test4.py", line 8, in go
    connect_to_something_witha_secret(
  File "/mnt/photon_home/classic/dev/sqlalchemy/test4.py", line 4, in connect_to_something_witha_secret
    raise Exception(f"could not connect to host: {host}")
      host = 'fakehost'
      username = 'scott'
      password = 'super_secret_password'
builtins.Exception: could not connect to host: fakehost

Publish wheel on pypi

For speedup installation, it will be nice if the wheel will be published on PyPI. It is nice because there is no need to execute any code during installation,

Recommendation to use in prod might have negative privacy implications

In the current README for this project, I've noticed the following part:

Should I use it after debugging is over, i.e. in production?
Yes, of course! That way it might save you even more time.

I think that this is a dangerous advice to provide when you consider software that might be dealing with user data (e.g. serving user queries over the network, processing database entries, etc.). You could easily end up with user data or secrets being accidentally stored in the app's debug logs, and:

  • Debug logs might have a different retention policy than the data would normally have (e.g. data only stored in RAM normally might end up being persisted to disk for an undefined amount of time)
  • Access control policy might be more relaxed for the debug logs than for raw access to the data itself. For example, this might end up leaking a secret to a developer that might not have direct access to that secret normally (e.g. it's passed through the environment or something like that).

See https://techcrunch.com/2019/03/21/facebook-plaintext-passwords/ for a precedent which this advice could accidentally end up reproducing.

I don't have a suggested rewording, but I think the caveats should probably be made clearer to potential users of the library.

Is "NoReturn" the proper annotation for global_print_exc()?

The NoReturn type indicates the function either never terminates or always throws an exception:

From PEP-484:

The typing module provides a special type NoReturn to annotate functions that never return normally. For example, a function that unconditionally raises an exception..

By having it set to NoReturn, all the code after the call to global_print_exc() is "dimmed" in type-aware IDEs like VS Code. (For example, NoReturn makes sense for annotating sys.exit() with the visual indication that none of the code after it will ever execute.)

Since the function is simply setting sys.excepthook, shouldn't the return type simply be None, or am I missing something?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.