Keywords for this issue:
<span>logging</span>、<span>traceback</span>、<span>cProfile</span>、<span>timeit</span>、Code Debugging and Optimization Difficulty: Beginner → Essential Skills for Advancement
📌 I. Basics of logging
1. Print simple logs
import logging
logging.basicConfig(level=logging.INFO)
logging.info("Program started")
2. Customize log format
import logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s"
)
logging.warning("This is a warning")
3. Write logs to a file
import logging
logging.basicConfig(
filename="app.log",
level=logging.DEBUG,
format="%(asctime)s - %(levelname)s - %(message)s"
)
logging.error("Error log written to file")
📌 II. Debugging and Error Tracking
4. Capture and print the complete exception stack
import traceback
try:
1 / 0
except Exception:
print("Caught an exception:")
print(traceback.format_exc())
5. Use <span>pdb</span> for breakpoint debugging
import pdb
def calc():
a = 10
pdb.set_trace() # The program will pause here
b = 20
return a + b
calc()
6. Use <span>assert</span> for debugging assistance
def divide(a, b):
assert b != 0, "Denominator cannot be 0"
return a / b
print(divide(10, 2))
print(divide(10, 0)) # This will trigger an assertion error
📌 III. Performance Analysis and Optimization
7. Use <span>timeit</span> to test code execution time
import timeit
code = "[x**2 for x in range(1000)]"
print(timeit.timeit(code, number=1000))
8. Use <span>cProfile</span> to analyze program performance
import cProfile
def slow_func():
total = 0
for i in range(1000000):
total += i
return total
cProfile.run("slow_func()")
9. Simple optimization example
Original code:
nums = []
for i in range(1000000):
nums.append(i * i)
Optimized version:
nums = [i * i for i in range(1000000)]
Analysis: List comprehensions not only simplify the code but are also more efficient than using <span>append</span> in a loop.
📌 IV. Comprehensive Questions
10. Write a safe execution function that logs exception information
import logging
import traceback
logging.basicConfig(level=logging.ERROR, format="%(asctime)s - %(levelname)s - %(message)s")
def safe_run(func, *args, **kwargs):
try:
return func(*args, **kwargs)
except Exception:
logging.error("Error executing function:
%s", traceback.format_exc())
return None
def divide(a, b):
return a / b
print(safe_run(divide, 10, 2))
print(safe_run(divide, 10, 0))
📌 V. Common Interview Q&A
Q1: <span>print</span> vs <span>logging</span> – what is the difference?
| Feature | <span>print</span> |
<span>logging</span> |
|---|---|---|
| Purpose | Debug output | Debugging, monitoring, persistent logging |
| Flexibility | No log levels | Supports multiple levels (DEBUG/INFO/WARNING/ERROR/CRITICAL) |
| Production readiness | Not suitable | Fully suitable for production environments |
Q2: How to quickly locate performance bottlenecks in a Python program?
- Use
<span>cProfile</span>or<span>line_profiler</span>to analyze function execution time - Optimize the time-consuming parts, such as algorithm improvements, batch processing, or concurrency optimization
Q3: How to split log files by size or time? Use the <span>logging.handlers</span> module, for example:
from logging.handlers import RotatingFileHandler
handler = RotatingFileHandler("app.log", maxBytes=1024*1024, backupCount=5)
🎯 Self-Assessment Scoring Suggestions
| Number of Correct Answers | Your Level |
|---|---|
| ≥8 correct answers | Can independently handle logging and performance analysis issues |
| 5~7 correct answers | Master basic debugging skills, but need to strengthen optimization thinking |
| <5 correct answers | Start with <span>logging</span> and <span>timeit</span> to build a foundation |
📌 Summary
The ability to log, debug, and optimize performance is the dividing line between “being able to write code” and “writing good code.” Mastering these three skills will enable you to:
- Quickly locate issues
- Establish a maintainable project logging system
- Optimize code performance with rationale