Debugging

This is a small trick I use whenever I must debug something on production using pdb without (hopefully) disturbing other users.

All I do is ssh my production server, connect to a shell_plus console or just a shell console using manage.py, and inside the shell I do:

pdb.run('func_I_want_to_debug()')

Sometimes I want to call different functions, make something more complex so I do:

In [1]: def test():
   ...:     import pdb;pdb.set_trace()
   ...:     func_I_want_to_debug()
   ...:     something else()
   ...:     

In [2]: test()
> (3)test()
-> func_I_want_to_debug()
(Pdb) s

And then the fun part begins :) Of course, you have to be careful! you could trigger some events you don't want to or save some thing you dont want to. I only proceed like this when It's hard (impossible) to reproduce the bug locally or on a pre-prod environment.

Finally if you have a long process, and you don't want to spend your day pressing 'n' until you arrive to the exception, you can enable the pdb mode on ipython using %pdb and it will start the debugger on every uncaught exception

Explanation

If you're not familiar with pdb, it is an interactive module that allows you execute your code step by step, You can read more here, but the most important commands are:

  • s (step): It will try to go inside the current function, property, class, etc.
  • n (next): It will execute the current line and move to the next line.
  • c (continue): Continue execution and stops only if there's another breakpoint.
  • q (quit): Exits everything raising an exception.
  • l (list): shows the code around the current line.

Hint

If you can, use ipdb instead of pdb like this:

  import ipdb
  ipdb.set_trace()

ipdb has an autocomplete!!! \o/

Happy debugging!