This python logging tutorial covers a script that stops overnight on a device and leaves nothing to explain why. Log to a rotating file so the evidence survives, then use pdb when you can sit at the board.
- Start here: call logging.basicConfig with a level and a format that includes a timestamp.
- For unattended runs: send records to a rotating file so old logs are capped.
- Around risky calls: wrap sensor reads in try except and log the failure with its traceback.
- When you are at the device: step through the failing code with pdb.
The shell side of this work, such as finding and reading the log files afterwards, is covered in our linux command line tutorials. Python’s standard library documentation, including the logging module, is published online on python.org.
Setting up logging in a Python script
The logging module gives every message a severity and a timestamp, and one call near the top of the script decides what gets shown. The simplest form is logging.basicConfig(level=logging.INFO), which sets the minimum level a record needs to be emitted, as shown in a logging module walkthrough.
Two more basicConfig parameters make the output useful on a device you cannot watch:
- level: the threshold below which records are dropped. Start at INFO for a script you trust, and lower it only while diagnosing.
- format: the layout of each line. The walkthrough’s example is “%(asctime)s – %(name)s – %(levelname)s – %(message)s”, which gives time, logger name, severity and text.
- datefmt: how the timestamp reads, for example “%Y-%m-%d %H:%M:%S”. A readable date and time lets you match a log line to the moment a sensor misbehaved.
In every module, create a logger with logging.getLogger(__name__) and call its methods instead of the root functions. The name then appears in the %(name)s field, so a line tells you which file produced it.

Choosing a log level
Each level has a numeric value, and choosing one is a decision about who needs to read the line and when. For an unattended script, the useful split is between lines that prove it is healthy and lines that explain a failure.

| Level | Numeric value | Meaning | Planning use on a device |
|---|---|---|---|
| DEBUG | 10 | Detailed information for diagnosing problems | Raw readings and intermediate values while you chase a bug |
| INFO | 20 | Confirmation that things work as expected | Start-up, a completed read cycle, a finished upload |
| WARNING | 30 | Something unexpected, but not an error | A reading outside the usual range that the script can carry on past |
| ERROR | 40 | A serious problem; some functionality failed | A failed sensor read or a lost connection |
| CRITICAL | 50 | A very serious error; the program may crash | Failures after which the script cannot continue |
The levels and their numeric values come from this logging module guide.
A records level is compared with the threshold you set, so a higher threshold means a quieter log. The practical rule is to run at INFO day to day and drop to DEBUG only for a specific investigation. Reserve ERROR for failures that need attention, so that searching the file for that word returns something meaningful.
Writing logs to a file that stays manageable
To write logs to a file, add a FileHandler. The guide’s example is logging.FileHandler(“app.log”), attached to a logger so every record also lands in that file. On a device that runs for weeks, a plain file keeps growing, so a rotating handler is the better default.
Rotating by size
RotatingFileHandler starts a new file when the current one reaches a size limit. The walkthrough’s example uses maxBytes of 10*1024*1024, which is 10 MB, with backupCount=5, so a bounded set of older files is kept. This suits a script whose output volume varies, because the cap depends on size rather than on the clock.
Rotating by time
TimedRotatingFileHandler rotates on a schedule. The same guide uses when=”midnight”, interval=1 and backupCount=30, which gives one file per day and keeps 30 backups. Choose this when you want to say “show me what happened on Tuesday” and open a single file.
If you cannot predict how chatty the script will be, pick size-based rotation. If you review the device on a routine, pick the daily one.
Catching failures with try except
A sensor read is the classic place for an unattended script to fail, so wrap it in try except and record what happened instead of letting the whole script stop. The guide’s example catches a named exception type, except ZeroDivisionError:. Name the specific exception you expect rather than catching everything, so unrelated bugs still surface.
Inside the except block, call logger.exception(“message”). The same logging guide notes that exception() automatically includes the exception information, so the log keeps the full traceback. Use it only inside an except block, where there is a live exception to record. Then decide what the script does next: skip this reading and carry on, or stop.

If the value you read is then sent to a web service, handle that call’s failures the same way. Our guide to the python requests post json example shows the sending side.
Reading a traceback
A traceback is the report Python prints when an exception is not handled, and it is the quickest route to the failing line. Read it from the bottom: the last line gives the exception type and its message, and the lines above trace the calls that led there, ending at the line where it failed.
When you handle an exception yourself, you can still keep that report. Passing exc_info=True to a logging call adds the stack trace to the record, according to the same walkthrough. The ERROR line in your file then carries the same information you would have seen on screen, which matters when nobody was watching.
Stepping through code with pdb
Logging tells you what happened after the fact. pdb, Python’s built-in debugger, lets you stop the script and inspect it live, so use it when you can sit at the board with a terminal open. Starting the script with python -m pdb script.py runs it under the debugger, and a breakpoint() call in the code pauses it at a line you choose.
At the (Pdb) prompt you control execution with short commands:
- n: run the next line without entering function calls.
- s: step into the function called on the current line.
- p name: print the value of a variable, for example the sensor reading you suspect.
- c: continue running until the next breakpoint or the end.
- q: quit the debugger.
Let the log narrow the search first. Once an ERROR line names the failing function, place the breakpoint just before it. If you are editing the script on the device itself, the comparison of nano vs vim helps you pick an editor for those quick changes.
Troubleshooting logging problems
- A debug call prints nothing. The guide’s example sets the level to INFO, and at that setting a debug message is not shown. Lower the level to DEBUG while you diagnose, then raise it again.
- You cannot tell which line wrote a message. Add %(lineno)d to the format string. It inserts the line number into every record.
- A failure leaves no detail in the file. Log inside the except block with exception(), as above, so the traceback is stored along with the message.
Frequently asked questions
| Question | Answer |
|---|---|
| Can one script log to the screen and to a file with different detail? | Yes. Give each handler its own level. The guide’s example sends INFO and above to the console and DEBUG and above to the file, so the file holds more detail than the screen. |
| What replaces basicConfig when the setup gets complicated? | Dictionary configuration. The guide recommends it for complex setups and loads it with logging.config.dictConfig(LOGGING_CONFIG). |
| Why pass values as arguments instead of building the message string myself? | A call like logger.debug(“User data: %s”, user_data) only formats the string when DEBUG is enabled, so disabled messages cost little formatting work. |
| Which level should a long-running script use? | INFO is a sensible baseline, because it confirms that things work as expected. Switch to DEBUG only while diagnosing a specific fault. |



