r/Python • • Sep 19 '26

Discussion What’s a debugging technique that saved you hours and you wish you’d learned earlier?

I’m curious about the small debugging techniques that make a big difference when working on real projects.For developers with some experience, what debugging technique or habit has saved you the most time?It could be something simple that beginners often overlook.

What’s one debugging tip you wish someone had taught you when you were starting out?

151 Upvotes

159 comments sorted by

View all comments

100

u/mattl33 It works on my machine Sep 19 '26

Add logging as your developing new stuff. You won't know when it'll be useful but it will be.

19

u/Inkosum Sep 19 '26 edited Sep 19 '26

True, but what should I log? I can't just log everything.

Edit: Thank you guys for your input, it helps me to know other perspectives.

45

u/DNSGeek Sep 19 '26

Set the level to DEBUG and log everything. When you’re releasing it, set the minimum logging level to INFO or higher and all your debugging data just doesn’t get logged any more.

17

u/ParkingPsychology Sep 19 '26

This is the right way to do it.

https://docs.python.org/3/library/logging.html

There are also some modules that add colors to that.

https://github.com/borntyping/python-colorlog

2

u/mattl33 It works on my machine Sep 19 '26

Yea structlog is really nice imo but not necessary.

4

u/srcLegend Sep 19 '26

Doesn't it incur a performance penalty if there are logging lines everywhere, even if they're disabled by setting a lower verbosity level?

9

u/Schmittfried Sep 19 '26

If that’s a problem, you’re using the wrong language. 

2

u/srcLegend Sep 19 '26

I meant in general. Wouldn't that be true of all languages (short of preprocessor directives)?

4

u/nicholashairs Sep 20 '26

It would incur a penalty, but for most use cases it would be negligible, checking if a log level is activated should be a super fast evaluation. If you really are concerned about such performance then you should already be benchmarking and doing tricks to strip them out.

The one exception is if building your log line is expensive in which case you should put it in a guard that is fast:

# original 
self.logger.debug(expensive())

# optimised
if self.logger.enabled_for("DEBUG"):
    self.logger.debug(expensive())

3

u/DNSGeek Sep 20 '26

Also, use % string concatenation with the logging module. It has its own string evaluator, so if the level isn't going to be logged the string is never evaluated.

logging.debug("name=%s" % name)

1

u/RingularCirc Sep 21 '26

How exactly is it not evaluated?

2

u/glenbolake Sep 22 '26

u/DNSGeek had a typo. The syntax is supposed to be logging.debug("name=%s", (name,)), and it gets evaluated inside the logging module after a log level check.

→ More replies

1

u/DNSGeek Sep 21 '26

The logging system looks at the level, e.g. “logging.debug”. If the current logging level is INFO or higher, then the logging system immediately returns without even looking at the string or doing the substitutions.

3

u/chief167 Sep 19 '26

No, well technically yes, but it's on the order of sub-milliseconds

2

u/IcecreamLamp Sep 19 '26

It's also trivial to later delete all lines starting with _logger.debug(…

12

u/mattl33 It works on my machine Sep 19 '26

When in doubt I will log function inputs and return values. You just need to be careful not to log anything sensitive or giant json blobs etc.

5

u/thekamakaji It works on my machine Sep 19 '26

There are various levels of logging. You can log higher priority messages at the info level, but stuff you don't always need at the debug or trace level. I'm importing 30k records and doing some kinda slow processing on each of them that sometimes hangs.

At the info level, I'm logging completion of x records (1000, 2000/30k complete).

At the debug level, I'm logging which record I'm processing so I know whether or not I'm making progress and which records are taking a while (logs have their messaged timestamped)

At the trace level, I'm looking at which parts of the processing are taking a while so I can go in and optimize the biggest slow downs

Depending on what I'm doing, I might only be looking at a certain level of messages. I also might have certain levels of messages enabled/disabled for different parts of the code depending on what I'm working on/interested in

4

u/ottawadeveloper Sep 19 '26

I add logging as I debug. Rather than print() I just add a call to log.debug(). It helps a lot when I encounter another problem later.

A key tip when doing this is not to spend too much time building your debug log message. log.debug(f"var is {var}") is notably slower than log.debug("var is %s", var) since the second only builds the string if it would be output. 

I usually end up logging any key step in a process. Like I was working on a unit converter recently and each step in parsing the units is logged via debug. With good practices and logging settings, it adds very little overhead in production but can add a lot of detail quickly. 

3

u/Due-Organization-697 Sep 19 '26

Your point is true, but want to point out at 3.8 you can just do f"{var=}" for label&value strings.

3

u/pacific_plywood Sep 19 '26

Simply log enough but not too much

You’ll get a better sense of this the more you do it

1

u/bankrupt_bezos Sep 19 '26

For my program, it was delta timing that really helped me figure out where the issue was.

1

u/jjarcanista Sep 20 '26

think as an experienced sysadmin

1

u/brut-rusty- It works on my machine Sep 25 '26

I didn't see anyone else mention this idea, I've used this one for years: use bits to control what level of debug you want to print, and add all your logging/debugging as you develop, assigning specific bits to the levels of debug you want to print.

I usually go with something like bit 1 is "verbose" logging (prints out major steps that are occurring that you'd expect to see with a "-v" from another program), and everything else after that is mostly specific to the script.

For an example, if I'm writing something that does a HTTP call to a webserver to scrape data and stores the results in a database, bit 1 would be verbose print, bit 2 might be printing the assembled POST payloads I'm going to send throughout the script, bit 4 might be printing out what my SQL statements might look like before executing, bit 8 might enable the http.client full transaction debugging, etc. Selection of bits are printed is controlled via argparse (-d/--debug, type=int, default=0, help="List out your debugs briefly here or use a formatter to print out a nicer menu).

Run the script with a "-d 5" would enable bits 1 and 4, so any print lines matching bits 1 and 4 would print, all the others wouldn't, so you can write in as much debug as makes sense when you're developing, select what you want to debug at runtime later with a -d flag.

Just another idea to think about that I hadn't seen anyone else throw out there.

0

u/Gnaxe Sep 19 '26

1

u/nicholashairs Sep 20 '26

There's good advice in here, especially given how much logging is abused by developers.

But it doesn't change the fact that logging is a useful tool even when used incorrectly.

→ More replies (1)