| name | debugging |
| description | Debugging techniques and tools |
| license | MIT |
| compatibility | opencode |
| metadata | {"audience":"developers","category":"code-quality"} |
What I do
- Debug application issues effectively
- Use debugging tools and techniques
- Analyze crash dumps and stack traces
- Profile performance bottlenecks
- Debug network issues
- Handle production incidents
- Use logging for debugging
- Write debuggable code
When to use me
When debugging issues or troubleshooting problems.
Debugging Techniques
Scientific Method for Debugging
1. Observe the symptom
- What error message?
- What was the input?
- When does it happen?
2. Form a hypothesis
- What could cause this?
- What's the most likely cause?
3. Test hypothesis
- Can I reproduce it?
- What changes the behavior?
4. Refine hypothesis
- Narrow down the cause
- Test edge cases
5. Fix the bug
- Make minimal change
- Verify the fix
6. Prevent regression
- Add test case
- Document the issue
Python Debugging
import pdb
from typing import Any
def debug_with_pdb():
"""Start interactive debugger."""
breakpoint()
import rpdb
def start_remote_debugger(port=4444):
"""Start debugger on specified port."""
rpdb.set_trace(port=port)
from icecream import ic
def debug_with_icecream():
"""Print variable values with expressions."""
x = 10
y = 20
z = x + y
ic(x)
ic(y)
ic(z)
ic(x + y)
import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
def debug_with_logging(data: dict) -> dict:
"""Debug with structured logging."""
logger.debug("Processing data", extra={
'data_keys': list(data.keys()),
'data_size': len(data),
})
result = {k: v * 2 for k, v in data.items()}
logger.debug("Processed result", extra={
'result': result,
'result_keys': list(result.keys()),
})
return result
from rich import print as rprint
from rich.pretty import pprint
def debug_with_rich():
"""Pretty print with rich."""
data = {'name': 'test', 'values': [1, 2, 3], 'nested': {'a': 1}}
pprint(data)
JavaScript Debugging
function debugWithConsole() {
const data = { name: 'test', value: 42 };
console.log('Data:', data);
console.group('Processing');
console.log('Start');
console.log('Processing...');
console.log('Done');
console.groupEnd();
const users = [
{ name: 'Alice', age: 30 },
{ name: 'Bob', age: 25 },
];
console.table(users);
console.trace('Stack trace');
console.time('operation');
console.timeEnd();
}
() {
;
}
{
: ,
: [
{
: ,
: ,
: ,
: ,
: []
}
]
}
Performance Profiling
import cProfile
import pstats
from memory_profiler import profile, memory_usage
import time
def profile_code():
"""Profile CPU usage."""
profiler = cProfile.Profile()
profiler.enable()
result = [i * 2 for i in range(10000)]
profiler.disable()
stats = pstats.Stats(profiler)
stats.sort_stats('cumulative')
stats.print_stats(20)
@profile
def profile_memory():
"""Profile memory usage."""
data = [i * 2 for i in range(100000)]
time.sleep(0.1)
return data
from line_profiler import LineProfiler
def profile_lines():
profiler = LineProfiler()
profiler.add_function(slow_function)
profiler.enable_by_count()
slow_function()
profiler.disable()
profiler.print_stats()
Debugging Production Issues
import sys
import traceback
class ProductionDebugger:
"""Debug issues in production safely."""
def __init__(self, log_file: str = '/var/log/app/debug.log') -> None:
self.log_file = log_file
def setup_error_handling(self) -> None:
"""Setup comprehensive error handling."""
sys.excepthook = self.handle_exception
def handle_exception(self, exc_type, exc_value, exc_traceback) -> None:
"""Log exceptions with full context."""
import os
with open(self.log_file, 'a') as f:
f.write(f"\n{'='*60}\n")
f.write(f"Exception: {exc_type.__name__}\n")
f.write(f"Message: {exc_value}\n")
f.write(f"Traceback:\n")
tb = traceback.format_exception(exc_type, exc_value, exc_traceback)
f.write(''.join(tb))
f.write(f"\nProcess ID: {os.getpid()}\n")
f.write(f"Working Directory: \n")
() -> :
() -> :
gc
psutil
os
process = psutil.Process(os.getpid())
{
: process.memory_info().rss / / ,
: process.cpu_percent(),
: (process.open_files()),
: (process.threads()),
: gc.get_stats(),
}
flask Flask, jsonify
app = Flask(__name__)
():
debugger = ProductionDebugger()
jsonify({
: debugger.capture_state(),
: {
: ,
},
: {
: sys.version,
},
})
Network Debugging
import requests
from requests.exceptions import RequestException
class NetworkDebugger:
"""Debug network requests."""
def __init__(self, base_url: str) -> None:
self.base_url = base_url
self.session = requests.Session()
def debug_request(
self,
method: str,
url: str,
**kwargs
) -> requests.Response:
"""Debug a network request."""
full_url = f"{self.base_url}{url}"
print(f"\n{'='*60}")
print(f"Request: {method.upper()} {full_url}")
headers = kwargs.get('headers', {})
print(f"Headers: {dict(headers)}")
if 'json' in kwargs:
print(f"Body (JSON): {kwargs['json']}")
elif 'data' in kwargs:
print()
:
response = .session.request(method, full_url, **kwargs)
()
()
content = response.text[:]
()
response
RequestException e:
()
() -> :
socket
checks = {}
:
socket.gethostbyname(.base_url)
checks[] =
socket.gaierror:
checks[] =
:
host = .base_url.split()[].split()[]
port = .base_url
socket.create_connection((host, port), timeout)
checks[] =
Exception:
checks[] =
checks
Common Debugging Patterns
def bisect_debug():
"""Find the breaking change with binary search."""
versions = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
mid = len(versions) // 2
print(f"Testing version {versions[mid]}")
def minimal_reproduction():
"""Create minimal code to reproduce bug."""
def diff_debug():
"""Compare working vs broken state."""
import difflib
working = "correct behavior"
broken = "current behavior"
diff = difflib.unified_diff(
working.splitlines(),
broken.splitlines(),
lineterm='',
)
for line in diff:
print(line)
Debugging Tools Reference
Python:
- pdb - Built-in debugger
- ipdb - IPython-based debugger
- rpdb - Remote debugger
- icecream - Better print debugging
- rich - Rich output
- memory_profiler - Memory profiling
- line_profiler - Line-by-line profiling
- cProfile - CPU profiling
- py-spy - Low-overhead sampling profiler
JavaScript:
- Chrome DevTools - Browser debugging
- VS Code debugger - IDE debugging
- Node.js inspector - Node debugging
- ndb - Improved Node debugging
General:
- strace - System call tracing (Linux)
- ltrace - Library call tracing
- dtrace - Dynamic tracing
- wireshark - Network analysis
- mitmproxy - HTTP proxy for debugging