Python debug logging that works for me

No, it’s not going to get open-sourced just now. It’s too specific to Sauce Labs. Instead this is an overview of how it works and what it does.

Usually when I want to debug some code, I do it by logging values during execution. When I do, I don’t just want to see the value; I also want to see the value’s name, or the expression, or whatever, so I can pick it out more easily when reading logs. In the past that has meant having to have an (optional) second argument where you pass the name:

  • debug_log(my_value, “my_value”)

This is where Python being a scripting language came in handy. In a dev environment, you still have the .py files with actual code hanging around, so you can use tracebacks to grab the code on the line the debug() call came from.

That’s the main advantage. From there I added some more cool features. If the value being logged is a “primitive”, I just print its repr and type. If it’s an object, I print its type name, and all its public attributes’ reprs and types, but not recursively. I also show their docstrings if they’re available.

This is a fairly simple chunk of code, but it has saved me a ton of debug time. If you develop in a language where tracebacks and run-time object introspection are available, it’s highly recommended.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: