Logging in Python — All You Need To Know
From the publisher’s feed, collected in the ZeroLabs newsroom.
What logging is, why you need it, how it works in Python, and how to use it correctly in real projects.What Problem Does Logging Solve?You write a program. It runs. Something breaks → Now what?The program is done. You have no idea what happened, when, or where.That is the problem.Logging is the solution. It’s your program keeping a record of everything it does while it runs.Think of it like the black box on an airplane. The plane records everything — altitude, speed, every decision the pilot makes. If something goes wrong, investigators open the black box and see exactly what happened, when, and in what order. Without it, they’d be guessing."8:02 AM — Takeoff complete. Altitude 3,000 ft.""8:15 AM — Slight turbulence detected. Adjusting route.""8:45 AM — Engine 2 shutdown initiated."If something went wrong, you play back the recording. You know exactly what happened, when, and in what order.That’s all logging is. Your program writing notes while it runs.The Simplest Possible ExampleCreate a file called first_log.py:import logginglogging.basicConfig(level=logging.DEBUG)logging.debug("Step 1 - I am starting")logging.debug("Step 2 - I am doing some work")logging.debug("Step 3 - I am done")Run it:python first_log.pyYou’ll see:DEBUG:root:Step 1 - I am startingDEBUG:root:Step 2 - I am doing some workDEBUG:root:Step 3 - I am doneYour program just left notes. That’s logging.Now — you’re probably looking at this and thinking: “What is basicConfig? What does root mean? What is level?"Good. We’ll answer every one of those. But first, let’s start with the most fundamental concept.What Is a Logger?A logger is a Python object that you use to write log messages.That’s its only job. You create one, give it a name, and then call methods on it like .info(), .error(), or .warning() to leave notes.By itself, a logger just accepts messages. Where those messages end up — the terminal, a file, or both — depends on how you configure it (which we’ll get to shortly).Let’s create your first logger:import logging# Create a logger — give it a namelogger = logging.getLogger("my_notepad")That’s a logger. It has a name ("my_notepad"), and you use it to write notes:logger.debug("Very detailed info")logger.info("Something important happened")logger.warning("Something looks off")logger.error("Something broke")logger.critical("Total failure")But if you save this as a file and run it, something odd happens — only the warning, error, and critical lines produce output, and the output looks bare:Something looks offSomething brokeTotal failureNo timestamps, no level labels, no logger name.And the debug and info lines are completely missing.Why?Because a logger by itself has no proper setup. It has no handler (nothing telling it where to send notes) and no formatter (nothing telling it how to display notes).Note: Python has a built-in safety net called the “last resort handler” that will print WARNING-level messages and above as bare text to the terminal — but it’s only meant as a fallback, not something you should rely on.For your logs to be properly useful, you need to set up three things:A Handler — decides where the notes go (terminal? file?)A Formatter — decides how the notes look (timestamp? level label?)A Level — decides the minimum urgency to showLet’s set those up manually so you can see every piece:import logging# Step 1: Create the logger (your notepad)logger = logging.getLogger("my_notepad")logger.setLevel(logging.DEBUG) # "Accept notes of any urgency level"# Step 2: Create a handler (where do the notes go?)# StreamHandler = "send notes to the terminal"console_handler = logging.StreamHandler()# Step 3: Create a formatter (how do the notes look?)formatter = logging.Formatter("%(asctime)s | %(name)s | %(levelname)s | %(message)s")# Step 4: Connect them togetherconsole_handler.setFormatter(formatter) # tell the handler how to formatlogger.addHandler(console_handler) # tell the logger where to send# Step 5: Use itlogger.info("Application started")logger.warning("Something looks off")Output:2024-03-05 08:42:11,432 | my_notepad | INFO | Application started2024-03-05 08:42:11,433 | my_notepad | WARNING | Something looks offNow all levels show up (including INFO), and each line has a timestamp, the logger's name, the level, and your message.Here's every piece and what it does:┌───────────────────────────────────────────────────────────────────┐│ ││ Logger ("my_notepad") ← The object you write notes with, ││ │ you call .info(), .error(), etc. ││ ▼ ││ level = DEBUG ← "Accept all urgency levels" ││ │ ││ ▼ ││ Handler (StreamHandler) ← "Send notes to the terminal" ││ │ ││ ▼ ││ Formatter ← "Show timestamp, name, level, msg" ││ │ ││ ▼ ││ Terminal output ← What you see on screen ││ │└───────────────────────────────────────────────────────────────────┘That’s the entire logging system [Logger → Handler → Formatter → Output]. Everything else we talk about is building on top of this.basicConfig() — The ShortcutSetting up a logger, a handler, and a formatter manually every time is a lot of code. Python gives you a shortcut that does all of it in one line:import logginglogging.basicConfig( level=logging.DEBUG, format="%(asctime)s | %(levelname)s | %(message)s")logging.info("Application started")logging.warning("Something looks off")Output:2024-03-05 08:42:11,432 | INFO | Application started2024-03-05 08:42:11,433 | WARNING | Something looks offSame kind of result, way less code.But what did basicConfig() actually do?There's no magic — it did the exact same manual steps we just wrote, but on a special built-in logger called the root logger:# What basicConfig() does under the hood (roughly):root_logger = logging.getLogger() # Get the root logger (no name provided = root)root_logger.setLevel(logging.DEBUG) # Set the level you passedhandler = logging.StreamHandler() # Create a terminal handlerformatter = logging.Formatter("%(asctime)s | %(levelname)s | %(message)s")handler.setFormatter(formatter) # Attach formatter to handlerroot_logger.addHandler(handler) # Attach handler to root loggerRemember this for later: basicConfig() always configures the root logger — the one at the top of the logger tree.This will matter a lot when we talk about the hierarchy later on.And when you call logging.info(...) (the function directly on the logging module, without creating your own logger first), it's just a shortcut for writing to that same root logger.It only works once. If you call it again, it does nothing — it silently ignores the second call. So always call it early, before any other logging happens.It configures the root logger — a special shared logger that sits at the top of the logger tree (I'll explain this exactly in the hierarchy section).So basicConfig() is great for getting started quickly. But as your project grows, you'll need named loggers — which is exactly what we'll build toward.First, let's understand levels.Log Levels — Not All Notes Are Equally ImportantThink about a doctor writing notes. Not everything has the same urgency:"Patient arrived." → routine, no urgency"Patient's blood pressure is high." → worth watching"Patient is not breathing." → emergency, act nowPython logging works the same way. Every note has a level — a label that says “how urgent is this?”There are five levels, from least urgent to most urgent:┌──────────┬────────────────────────────────────────────────────────┐│ Level │ When to use it │├──────────┼────────────────────────────────────────────────────────┤│ DEBUG │ Very detailed step-by-step info. "Here's what I'm ││ │ doing right now." Only useful when actively debugging. │├──────────┼────────────────────────────────────────────────────────┤│ INFO │ Confirmation that something important worked. ││ │ "Config loaded." "Pipeline finished." │├──────────┼────────────────────────────────────────────────────────┤│ WARNING │ Something unexpected happened, but the program is ││ │ still running. "Missing a config value, using default."│├──────────┼────────────────────────────────────────────────────────┤│ ERROR │ Something failed. A specific operation didn't work. ││ │ "Could not connect to the database." │├──────────┼────────────────────────────────────────────────────────┤│ CRITICAL │ A total failure. The program probably can't continue. ││ │ "Database is completely down." │└──────────┴────────────────────────────────────────────────────────┘The Level Is Also a FilterYou can tell Python: “I only want to see notes that are at least this urgent.”import logginglogging.basicConfig(level=logging.WARNING) # ← only WARNING and abovelogging.debug("Reading the config file") # ← filtered outlogging.info("Config loaded successfully") # ← filtered outlogging.warning("Config is missing a value") # ← shownlogging.error("Could not connect to the database")# ← shownlogging.critical("Database is completely down") # ← shownOutput:WARNING:root:Config is missing a valueERROR:root:Could not connect to the databaseCRITICAL:root:Database is completely downThe DEBUG and INFO lines disappeared. The level acts like a minimum-urgency filter — anything below it is silently dropped.This is incredibly useful:While developing: set to DEBUG — see everythingIn production: set to INFO or WARNING — only see what mattersFormatting — Making Your Notes UsefulThe default output looks like WARNING:root:some message. If something breaks at 3 AM, you also want to know when and where:import logginglogging.basicConfig( level=logging.DEBUG, format="%(asctime)s | %(levelname)s | %(message)s")logging.info("Pipeline started")logging.warning("Something looks off")Output:2024-03-05 08:42:11,432 | INFO | Pipeline started2024-03-05 08:42:11,433 | WARNING | Something looks offThe %(...)s placeholders get replaced with real data:%(asctime)s → date and time%(levelname)s → level name (INFO, WARNING, etc.)%(message)s → your message%(name)s → the logger's name%(filename)s → which file wrote the line%(lineno)d → which line number (%d because it's a number)All this info is always captured internally. What shows up depends on which placeholders you include in format.Handlers — Controlling Where Your Notes GoA Handler decides where log messages go. That’s its only job.Logging to a Fileimport logginglogging.basicConfig( level=logging.DEBUG, format="%(asctime)s | %(levelname)s | %(message)s", filename="my_app.log" # ← notes go to a file instead of the terminal)logging.info("Pipeline started")logging.error("Something broke")Nothing appears in the terminal. Open my_app.log — your notes are saved to disk.Both Terminal AND FileThis is where you need set multiple handlers. One sends to the terminal, another saves to a file:import logginglogger = logging.getLogger("my_app")logger.setLevel(logging.DEBUG)formatter = logging.Formatter("%(asctime)s | %(levelname)s | %(message)s")# Handler 1: terminal — only INFO and aboveconsole_handler = logging.StreamHandler()console_handler.setLevel(logging.INFO)console_handler.setFormatter(formatter)# Handler 2: file — everything including DEBUGfile_handler = logging.FileHandler("my_app.log")file_handler.setLevel(logging.DEBUG)file_handler.setFormatter(formatter)# Attach bothlogger.addHandler(console_handler)logger.addHandler(file_handler)# Use itlogger.debug("Detailed step")logger.info("Important step")logger.error("Something broke")Terminal shows (INFO and above only):2024-03-05 08:42:11,432 | INFO | Important step2024-03-05 08:42:11,433 | ERROR | Something brokeFile shows (everything):2024-03-05 08:42:11,431 | DEBUG | Detailed step2024-03-05 08:42:11,432 | INFO | Important step2024-03-05 08:42:11,433 | ERROR | Something brokeWhy is the logger’s level set to DEBUG if the handlers already filter?Because the logger’s level is the first gate. If the logger’s level were WARNING, it would reject DEBUG and INFO messages before they even reached any handler. So you set the logger to DEBUG (let everything through) and let each handler decide its own minimum:Message: DEBUG "Detailed step" │ ▼Logger level = DEBUG → ✔ Passes first gate │ ├──> Console Handler (level=INFO) → ✘ Blocked (DEBUG │ └──> File Handler (level=DEBUG) → ✔ Passes → written to fileWhy You Need Named LoggersEverything so far has used either logging.info() (the shortcut that uses the root logger) or a single logger logger = logging.getLogger(“my_app”) named "my_app" we created manually. This works fine when your entire program is one file… But real projects have multiple files and multiple loggers. And that’s where a problem shows up.The Problem: You Can’t Tell Where a Log Came FromImagine your project has three files: loader.py, transformer.py, and writer.py. If all three use the root logger shortcut logging.info():# loader.pylogging.info("Started")logging.info("Done")# transformer.pylogging.error("Failed")# writer.pylogging.info("Finished")Your combined log output looks like this:INFO:root:StartedINFO:root:DoneERROR:root:FailedINFO:root:FinishedWhich file wrote “Failed”? → You have no idea. Every single line says root because all three files are writing through the same unnamed root logger. There is no label telling you which file each message came from.In a small script, this is fine. In a project with 10, 20, or 50 files, this is a nightmare.The Solution: Give Each File Its Own LoggerInstead of using the root logger, each file creates its own logger with a unique name:# loader.pyimport logginglogger = logging.getLogger("loader")logger.info("Started")logger.info("Done")# transformer.pyimport logginglogger = logging.getLogger("transformer")logger.error("Failed")# writer.pyimport logginglogger = logging.getLogger("writer")logger.info("Finished")Now your log output looks like this:INFO:loader:StartedINFO:loader:DoneERROR:transformer:FailedINFO:writer:FinishedNow you can instantly see that the error came from transformer. No guessing, no searching through files.The name you pass to getLogger() is just a label — it gets attached to every log line that logger produces, so you can tell where each message came from. That's all it does at this basic level. (The name also has a deeper purpose that we'll cover shortly — but for now, just think of it as a label.)__name__ — The Automatic NameTyping names manually ("loader", "transformer") works, but it's tedious and easy to get wrong — especially when your project has nested folders like myproject/pipeline/loader.py.Instead of typing names manually, use Python’s built-in __name__ variable:logger = logging.getLogger(__name__)logging.getLogger(__name__) automatically creates a logger named after the file it's in.You never type the name manually, and it's always correct.If your file is myproject/pipeline/loader.py, then __name__ is "myproject.pipeline.loader".This is the line you put at the top of every Python file:import logginglogger = logging.getLogger(__name__)No exceptions. Every file. Two lines.If each file creates its own logger, do you need to configure handlers and formatters on every single one?No. That’s what the logger hierarchy solves — and it’s the next section.The Logger Hierarchy — The Concept That Makes Everything WorkLoggers Form a Family TreeWhen you create loggers, the dots in their names automatically create parent-child relationships — like folders on your computer:root ← logging.getLogger() -> (no name = "root")│├── myapp ← logging.getLogger("myapp")│ ├── myapp.api ← logging.getLogger("myapp.api")│ └── myapp.database ← logging.getLogger("myapp.database")│├── __main__ ← logging.getLogger("__main__")│└── urllib3 ← (a library you imported) └── urllib3.connectionpoolThe rules are simple:myapp is the parent of myapp.api (because myapp.api starts with myapp.)root is the ancestor of everything — it sits at the very top__main__ and myapp are siblings — they're both children of root, but they are NOT parent-child of each otherYou don’t create this tree manually. Python builds it automatically from the names.Messages Flow Upward (Propagation)Here’s the key behavior: when you write a log message (like logger.info("...")), Python checks whether this logger has a handler attached:If yes, the message gets output there. But that's not all — Python also sends the message up to the logger's parent.The parent checks for its own handlers (and outputs if it has any), and next it passes the message up to its parent, and so on — all the way up to root.At each stop along the way, if that logger has a handler, the message gets output through it. The message always keeps traveling upward.Every message always travels all the way up to root, regardless of whether it was already handled somewhere below.This upward flow is called propagation.Let me show you exactly what happens. Say you have this code:# myapp/api.pyimport logginglogger = logging.getLogger("myapp.api")logger.info("Fetching data...")Python does this internally:Step 1: - "myapp.api" logger → Do I have any handlers? → No- Pass the message UP to my parent.Step 2: - "myapp" logger → Do I have any handlers? → No- Pass the message UP to my parent.Step 3: - "root" logger → Do I have any handlers? → YES! - Output the message !!! Or visually: root (has a handler — catches the message!) ⬆ │ myapp (no handler — passes it up) ⬆ │ myapp.api (no handler — passes it up) │ logger.info("Fetching data...")The message bubbles up from child → parent → grandparent → root. That’s propagation.Why This Matters → One Configuration Catches EverythingThis is the whole point. Because messages flow upward, you only need to attach handlers to the root logger.Every logger in your entire application — including third-party libraries — will send messages there automatically.Let me prove it with a runnable example. Create this file structure:root ← logging.getLogger() → (no name = "root")│├── myapp ← logging.getLogger("myapp")│ ├── myapp.api ← logging.getLogger("myapp.api")│ └── myapp.database ← logging.getLogger("myapp.database")│├── __main__ ← logging.getLogger("__main__")│└── urllib3 ← (a library you imported) └── urllib3.connectionpool# myapp/api.pyimport logginglogger = logging.getLogger(__name__) # name: "myapp.api"def fetch(): logger.info("Fetching data from API")# myapp/database.pyimport logginglogger = logging.getLogger(__name__) # name: "myapp.database"def query(): logger.info("Running database query")# main.pyimport loggingfrom myapp.api import fetchfrom myapp.database import query# Configure ONLY the root loggerlogging.basicConfig( level=logging.DEBUG, format="%(name)s | %(levelname)s | %(message)s")logger = logging.getLogger(__name__) # name: "__main__"logger.info("App starting")fetch()query()Run it:__main__ | INFO | App startingmyapp.api | INFO | Fetching data from APImyapp.database | INFO | Running database queryReminder: basicConfig() always configures the root logger — the one at the top of the logger tree.All three modules appeared, even though we only configured logging in main.py. Here's what happened:root (✔ handlers live here - catches everything) ⬆ ⬆ ⬆ / | \ __main__ mypackage urllib3 ← All logs flow UP to root | mypackage.api ← This log flows up tooNo module needed its own handler.No module needed any configuration.They just created a logger with getLogger(__name__) and wrote messages.Propagation did the rest — all messages went up to the root logger which was set up via logging.basicConfig() directly configurating root logger.Reminder — What basicConfig() Does to the TreeLet’s be very precise about what basicConfig() does: when you call logging.basicConfig(level=logging.DEBUG, format="..."), it attaches a handler to the root logger. That's it.BEFORE basicConfig(): root ← no handler, no formatter, default level WARNING ├── __main__ ← no handler (just created with getLogger) └── myapp └── myapp.api ← no handler (just created with getLogger) Nobody has a handler. Messages have nowhere to go.============================================================================AFTER basicConfig(): root ← ✔ HANDLER NOW has a StreamHandler + Formatter, level DEBUG ├── __main__ ← still no handler (doesn't need one!) └── myapp └── myapp.api ← still no handler (doesn't need one!) ✔ Root has a handler. All messages propagate up to root → they get printed.The key insight: basicConfig() only touches root.The child loggers (__main__, myapp.api) don't get handlers — they don't need them. They rely on propagation to send messages up to root, where root's handler does the work.What Happens If You DON’T Call basicConfig()Now the important question: what if you skip basicConfig() entirely?# main.py — no basicConfig, no configuration at allimport loggingfrom myapp.api import fetchlogger = logging.getLogger(__name__)logger.info("App starting")fetch()Output:Nothing. Completely silent. Here’s why:root ← no handler ✘ ├── __main__ ← no handler ✘ └── myapp └── myapp.api ← no handler ✘# What happens step by step: 1.logger.info("App starting") → __main__ has no handler → propagate up to root ✘ → root has no handler → message is LOST ✘2. fetch() → logger.info("Fetching data from API") → myapp.api has no handler → propagate up to myapp ✘ → myapp has no handler → propagate up to root ✘ → root has no handler → message is LOST ✘There’s no handler anywhere in the entire tree. Messages travel all the way up to root and find nothing. They vanish.As I mentioned before — technically, Python has a hidden “last resort” fallback that will print WARNING-level messages and above as bare text — but only as a safety net. INFO and DEBUG messages produce absolutely nothing.This is why basicConfig() exists. Without it (or other configuration), your loggers have nowhere to send messages.The Mistake: Putting the Handler on the Wrong LoggerNow here’s where people get confused. Instead of calling basicConfig() (which configures root), they manually add a handler to their own specific logger:# main.pyimport loggingfrom myapp.api import fetch# Create the __main__ logger and give IT a handlerlogger = logging.getLogger(__name__) # name: "__main__"logger.setLevel(logging.DEBUG)handler = logging.StreamHandler()handler.setFormatter(logging.Formatter("%(name)s | %(levelname)s | %(message)s"))logger.addHandler(handler) # handler on __main__, NOT on rootlogger.info("App starting")fetch()Output:__main__ | INFO | App startingThe fetch() message is gone. Only __main__'s own message appeared.Why?root ← no handler ✘ (we never configured root!) ├── __main__ ← ✔ has handler (we put it here) └── myapp └── myapp.api ← no handler ✘# What happens step by step: 1.logger.info("App starting") → __main__ has a handler → ✔ prints "App starting" ✔ → Also propagates up to root → root has no handler ✘ → nothing else happens# This message works only on the messages which reach this logger that has the handler.2. fetch() → logger.info("Fetching data from API") → myapp.api has no handler → propagate up to myapp ✘ → myapp has no handler → propagate up to root ✘ → root has no handler → message is LOST ✘# This message never visits __main__. # Why? Because __main__ is a sibling of myapp, not a parent.Look at the tree — messages flow upward (child → parent), never sideways (sibling → sibling): root ← message arrives here, but no handler = mess is gone / \ __main__ myapp ← these two are SIBLINGS, not parent-child (with handler) \ myapp.api ← message flows UP: myapp.api → myapp → root ← it NEVER flows sideways to __main__The handler is on the wrong branch.The Fix Is Always the SamePut the handler on root logger — the one ancestor that everything flows up to:# main.py — ✔ CORRECTimport loggingfrom myapp.api import fetch# basicConfig configures the ROOT logger — the top of the treelogging.basicConfig( level=logging.DEBUG, format="%(name)s | %(levelname)s | %(message)s")logger = logging.getLogger(__name__)logger.info("App starting")fetch()Output:__main__ | INFO | App startingmyapp.api | INFO | Fetching data from APIBoth appear: root (has handler — catches EVERYTHING) / \ / \ __main__ myapp \ myapp.api → message flows up → myapp → root → ✔ printed!Where to Put basicConfig() in Your FilebasicConfig() only works once. Internally, it checks: "Does the root logger already have handlers?" If yes, it exits and does nothing — silently.This means if anything configures the root logger before your basicConfig() runs, your configuration gets ignored. That's why you call it as early as possible:# main.pyimport logging # 1. Import logging FIRSTlogging.basicConfig( # 2. Configure IMMEDIATELY level=logging.DEBUG, format="%(asctime)s | %(name)s | %(levelname)s | %(message)s")from myapp.api import fetch # 3. THEN import your modulesfrom myapp.database import querylogger = logging.getLogger(__name__) # 4. THEN create your loggerWhy does the import order matter? Because when Python runs from myapp.api import fetch, it executes api.py from top to bottom. If that file logs something at the top level (outside a function), it could trigger logging before your basicConfig() runs:# myapp/api.py — ✘ BAD: logging at import timeimport logginglogger = logging.getLogger(__name__)logger.info("api module loaded") # ← runs during import!def fetch(): logger.info("Fetching data")The rule for modules: create the logger at the top level, but only call logging methods (.info(), .debug(), etc.) inside functions — never at the top level:# myapp/api.py — ✔ CORRECTimport logginglogger = logging.getLogger(__name__) # ← fine at top leveldef fetch(): logger.info("Fetching data") # ← logging inside a functionprint() vs loggingprint("User logged in") # no timestamp, no level, no sourcelogger.info("User logged in. user_id=%s", user_id) # all of those, automaticallyWith print(), you add debug prints during development, then hunt them down and delete them before shipping.With logging, you just change the level — debug lines stay in your code forever, invisible in production, visible when needed.Logging Exceptions CorrectlyInside an except block, use logger.exception(). It logs at ERROR level and automatically includes the full traceback:try: result = 42 / 0except ZeroDivisionError: logger.exception("Division failed")Output:ERROR:__main__:Division failedTraceback (most recent call last): File "main.py", line 2, in result = 42 / 0ZeroDivisionError: division by zeroWithout the traceback, you’d only see “Division failed” — useless for debugging.┌──────────────────────────────────────────┬───────┬────────────────────┐│ Method │ Level │ Includes traceback?│├──────────────────────────────────────────┼───────┼────────────────────┤│ logger.exception("msg") │ ERROR │ ✔ Automatically ││ logger.error("msg", exc_info=True) │ ERROR │ ✔ Explicitly ││ logger.error("msg") │ ERROR │ ✘ No │└──────────────────────────────────────────┴───────┴────────────────────┘logger.exception() is just a shortcut for logger.error(msg,exc_info=True). Only call it inside except blocks.Where Should You Log an Exception?The code that handles the error should log it.# ✘ BAD: logging AND re-raising — the caller will probably log it againexcept FileNotFoundError: logger.error("File not found", exc_info=True) raise # caller catches and logs AGAIN → duplicate# ✔ GOOD: re-raising? Don't log — let the caller decideexcept FileNotFoundError: raise# ✔ ALSO GOOD: handling it here? Log it hereexcept FileNotFoundError: logger.warning("File not found, using default") return default_valueCommon Mistakes — And How to Avoid ThemMistake 1: Configuring Logging in Module Files# loader.py ← WRONGimport logginglogging.basicConfig(level=logging.DEBUG) # ← Never do this herelogger = logging.getLogger(__name__)Modules should only write log messages — they should never decide where those messages go. That’s the job of the application (your main.py). If a module adds its own handlers, it takes that decision away from the person using the module, and their logging configuration may not work as expected.The rule: Configure logging once, in main.py only. Module files (like loader.py, pipeline.py) just create loggers and use them — they never configure them.# loader.py ← CORRECTimport logginglogger = logging.getLogger(__name__) # create it — that's ALL# main.py ← configuration goes HERElogging.basicConfig(level=logging.DEBUG, format="...")Mistake 2: Using f-strings in Log Messages# WRONGlogger.info(f"Loaded {len(data)} rows from {path}")# RIGHTlogger.info("Loaded %d rows from %s", len(data), path)Why does this matter? With f-strings, Python always builds the full string — even if the logger’s level would filter the message out (for example, a DEBUG message when the level is set to INFO). It does this because Python evaluates the f-string before passing it to the logger.With %s formatting, Python only builds the string if the message is actually going to be logged. The logger receives the template and the arguments separately, and only combines them if needed. This is a real performance win in code that logs frequently.Mistake 3: Logging Sensitive Data# NEVER DO THISlogger.info("User login. username=%s password=%s", username, password)# GOOD — log the event, not the secretlogger.info("User login attempt. username=%s", username)Never log passwords, API keys, tokens, or personal data (like email addresses or social security numbers). Logs end up in files, monitoring systems, and dashboards — often accessible to many people.Mistake 4: Swallowing Exceptions Silently# THE WORST THING YOU CAN DOtry: risky_operation()except Exception: pass # ← silent failure. You will NEVER know what broke.If something fails and you catch the exception but don’t log it, the error vanishes into thin air. When your program produces wrong results weeks later, you’ll have zero clues.Always log what went wrong:try: risky_operation()except Exception: logger.exception("risky_operation failed") raise # or handle it — but never ignore it silentlyMistake 5: Logging Inside Tight Loops# BAD — logs millions of lines, kills performance and fills your diskfor row in ten_million_rows: logger.debug("Processing row: %s", row)Log summaries, not every single iteration:# GOOD — log at the start and end, and on errorslogger.info("Starting processing. total_rows=%d", len(rows))errors = 0for i, row in enumerate(rows): try: process(row) except Exception: errors += 1 logger.error("Failed on row %d", i, exc_info=True)logger.info("Processing complete. errors=%d", errors)THE ENDOkay, that’s it for this article! I hope I helped you better understand how Python’s logging module actually works — from the basics of loggers, handlers, and formatters, to the logger hierarchy and propagation, to the common mistakes that trip people up in real projects. You now have a solid foundation to start using logging correctly in any Python codebase.Did this help? If you found this article useful, I’d really appreciate your support: 👏 clap for this story (once or 50!), 🔔 follow for more content, ✍ ️leave a comment telling me what you think!I’ll be sharing more material on data and software engineering concepts!You can find me also on LinkedIn.Cheers, see you next time!Logging in Python — All You Need To Know was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.