iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more
For a reliable Python logging setup, create a named logger in each module, configure logging once when the application starts, and send production events as one-line JSON to stdout. For libraries, use only a NullHandler and leave configuration to the application. The standard library is the dependable default; structlog and Loguru can make structured logging or low-boilerplate application setups more convenient.
This guide reflects the Python 3.13.18 documentation, updated October 26, 2026. It covers how to log in Python, configure files and applications, add context, avoid blocking request handling, and choose a logging stack without sacrificing compatibility or security.
What should you use logging for, and when should you use something else?
Logging records events that occur while software runs: a descriptive message, optional data, and a severity level. It is useful for operational diagnostics and for errors a long-running process must record even when it can continue. It is not a substitute for every form of output or error handling.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
| Situation | Use |
|---|---|
| Ordinary output intended for a command-line user | print() |
| Normal operational events or diagnostics | logger.info() or logger.debug() |
| An avoidable issue a library’s client should fix | warnings.warn() |
| A warning the client cannot fix but should know about | logger.warning() |
| An error the caller must handle | Raise an exception |
| An error a long-running process suppresses or handles | logger.error(), logger.exception(), or logger.critical() |
This distinction matters. Logging an exception instead of raising it can hide a failure from the caller; raising an exception for a recoverable operational event can turn a manageable condition into a failed request. Choose the mechanism based on who needs to respond and whether execution can safely continue.
Popular on Amazon
- 【90 Degree Full Function USB C Adapter】Supports the latest USB4 standard for up to 40Gbps of bandwidth, 8K video support, and up to 240W Fast charging; Support USB PD 3.1 Extended Power Range (EPR) including 140W, 180W and 240W. Your productivity is easily doubled. *Warm Tip: For the best fit, please make sure the USB-C port is fully exposed; thick or bulky cases may affect compatibility.
- 【Reliable Quality】Made from high-quality, scratch-resistant aluminum alloy, delicate metal frame. get excellent wear resistance and heat dissipation. Non-Slip Design for easier insertion and removal.
- 【Small and portable】Ultra thin size, ultra compact design, a petite physique that matches the minimalist design of your modern laptops. Coming with a slim figure that won't block the port next to the one it's plugged into.
- 【Compatibility】Widely work with most usb c, thunderbolt 4/3 devices. Compatibilit for ROG Ally, Steam Deck, Switch, MacBook Pro, Quest 3 VR headset, Surface Book 2, iPhone 18/17/16/15, Samsung Galaxy S23/S22/S21, Note 20/10, Google Pixel, ChromeBook, etc.
- 【Excellence Customer Support】If you experience any issues or cable failure, simply reach out to our dedicated customer service team. We provide a prompt response within 18 hours, providing you with the necessary technical support to resolve any concerns.
What are the Python logging levels?
Python’s standard levels run from DEBUG (10) through CRITICAL (50); a message is normally processed when it meets the configured threshold. The root logger starts at WARNING, which is why a bare logging.info() call is usually silent.
| Level | Numeric value | Typical use |
|---|---|---|
NOTSET |
0 | Delegate level decisions to an ancestor logger. |
DEBUG |
10 | Detailed information useful while diagnosing behavior. |
INFO |
20 | Expected operational milestones and state changes. |
WARNING |
30 | An unexpected or undesirable condition that has not stopped the process. |
ERROR |
40 | A failure that prevents an operation from completing. |
CRITICAL |
50 | A severe failure that may prevent the application from continuing. |
The numeric values are defined by the Python 3.13 logging documentation. In a typical production configuration, the application chooses a threshold such as INFO and raises it to DEBUG temporarily when more detail is needed. Levels are not a replacement for clear event names or useful fields.
import logging
logging.warning("Watch out!") # WARNING:root:Watch out!
logging.info("I told you so") # Silent with the default WARNING threshold
Module-level convenience calls such as logging.warning() use the root logger. If logging is not configured yet, these calls may invoke basicConfig() automatically. That behavior is handy for a short script, but named loggers and explicit configuration are easier to control in an application.
Free tools Windows power users keep installed
One-click scans. No signup required.
How do I get a logger in each Python module?
Use logging.getLogger(__name__) at module scope. It gives each module a name that mirrors its place in the package hierarchy, so application configuration can target a package or let its loggers inherit a shared setup.
import logging
logger = logging.getLogger(__name__)
def load_settings(path):
logger.info("Loading settings from %s", path)
Do not instantiate Logger directly. The Python logging reference says: “Loggers should NEVER be instantiated directly, but always through the module-level function logging.getLogger(name). Multiple calls to getLogger() with the same name will always return a reference to the same Logger object.” Repeated calls with the same name therefore retrieve the same logger rather than creating unrelated objects.
Message arguments use lazy percent-style formatting: logger.info("Loaded %s records", count). Logging can defer interpolation until it knows the message will pass the level and filters. An f-string, by contrast, is evaluated before the logging call, even if the event is discarded. This does not defer the cost of calculating arguments: guard expensive work with logger.isEnabledFor(logging.DEBUG).
if logger.isEnabledFor(logging.DEBUG):
logger.debug("Calculated %s and %s", expensive_func1(), expensive_func2())
Logging supports percent, brace, and dollar formatter styles. The formatter’s style setting controls the output format string; it does not change the recommended lazy formatting of message arguments.
How does Python logging route a message?
A logging event travels from a logger through filters to one or more handlers; a handler sends it to a destination and a formatter decides how it looks. Understanding that path explains common surprises such as duplicate lines, missing debug messages, or output appearing in an unexpected place.
- Logger: the API application code calls, such as a module’s
__name__logger. - Filter: accepts or rejects records and can add information such as request context.
- Handler: sends records to a stream, file, queue, email, network destination, or another sink.
- Formatter: renders the final text or JSON payload.
Logger names form a dotted hierarchy. For example, scan.text is a child of scan, and both ultimately descend from the root logger. A newly created logger has level NOTSET, so its effective level comes from the first ancestor with a level set. The root logger starts at WARNING.
By default, a logger propagates a record that passes its own level and filters to ancestor handlers. Ancestor logger levels are not checked again during this hand-off. A common arrangement is to put handlers on the root logger, allow module loggers to propagate, and avoid attaching the same handler at multiple points. Attaching one to both a child and an ancestor can print a single event twice.
Also popular on Amazon
- 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
- Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
- Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
- HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
- What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
If a record needs output but no handler exists anywhere in its logger hierarchy, Python’s lastResort handler provides a fallback: a stream handler to sys.stderr at WARNING, with no formatter, so only the message appears. It has existed since Python 3.2. Setting logging.lastResort to None restores older silent-drop behavior.
Windows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallCrashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minuteHow do I log to a file in a script?
For a small script, call logging.basicConfig() once near startup, before the first logging call. To write to a file with UTF-8 encoding and include debug events, use:
import logging
logging.basicConfig(
filename="example.log",
encoding="utf-8",
level=logging.DEBUG,
)
logger = logging.getLogger(__name__)
logger.info("Started processing")
encoding for file logging was added in Python 3.9. The default file mode is append, so existing content remains; set filemode="w" if the script should truncate the file when it starts. The default format is severity:logger name:message. For example, it can render a warning as WARNING:package.module:message.
basicConfig() configures the root logger. It is intentionally simple, but it will not replace an existing root configuration by default. That means calling it after another component has already configured logging may have no effect. Configure first, and use an application-level configuration when you need multiple handlers, custom formatting, or control over third-party loggers.
How should a Python library configure logging?
A library should create named loggers and leave destinations and formatting to the application that imports it. Add a NullHandler to the package logger if needed, and do not configure the process-wide root logger.
The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →import logging
logging.getLogger("foo").addHandler(logging.NullHandler())
A NullHandler discards records and prevents a library from imposing output policy on its users. The Python Logging HOWTO says: “It is strongly advised that you do not log to the root logger in your library. Instead, use a logger with a unique and easily identifiable name, such as the __name__ for your library’s top-level package or module.” It also advises: “It is strongly advised that you do not add any handlers other than NullHandler to your library’s loggers. This is because the configuration of handlers is the prerogative of the application developer who uses your library.”
Do not call basicConfig() during library import. It changes process-wide root behavior and can interfere with the host application’s own logging. A library should emit useful events; the application decides whether those events go to a console, file, aggregator, or nowhere.
How do I configure logging for a Python application?
Use logging.config.dictConfig() to configure an application at startup. The configuration schema’s version must be integer 1; explicitly set disable_existing_loggers to False so loggers created by imported dependencies are not unexpectedly disabled.
import logging
import logging.config
import os
LOGGING = {
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"standard": {
"format": "%(asctime)s %(levelname)s %(name)s %(message)s",
},
},
"handlers": {
"console": {
"class": "logging.StreamHandler",
"stream": "ext://sys.stdout",
"formatter": "standard",
},
},
"root": {
"handlers": ["console"],
"level": os.getenv("LOG_LEVEL", "INFO"),
},
}
logging.config.dictConfig(LOGGING)
logger = logging.getLogger(__name__)
logger.info("Application started")
This is a readable text baseline, not a complete production JSON configuration. It sends records to stdout and reads the root threshold from LOG_LEVEL; the value should be a valid logging level name, such as INFO or DEBUG. The core dictConfig keys include formatters, filters, handlers, loggers, root, incremental, and disable_existing_loggers.
One easily missed trap is that disable_existing_loggers defaults to True when omitted in dictConfig or the older fileConfig API. Existing non-root loggers may be disabled unless they, or an ancestor, are named in the configuration. Setting it to False is a safer default for an application with dependencies.
Also popular on Amazon
- Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
- Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
- Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
- Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
- What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
fileConfig() is the older INI-style option. It cannot configure filter objects, and Python’s documentation directs new application configuration toward dictConfig(). Since Python 3.12, fileConfig() raises an exception for a missing, invalid, or empty configuration file. Both logging configuration APIs can load callables or handler arguments, so configuration should be treated as executable input rather than harmless data.
How do I write production logs as JSON?
For a container or cluster deployment, write unbuffered events to stdout and let the runtime or logging platform route, store, and archive them. Use one JSON object per line, stable field names, and a UTC ISO-8601 timestamp; pretty-printed multi-line JSON can confuse log shippers.
This follows the Twelve-Factor App logs principle: “A twelve-factor app never concerns itself with routing or storage of its output stream.” Instead, “each running process writes its event stream, unbuffered, to stdout.” The application emits events; its environment handles collection and retention. Local files remain appropriate for a developer laptop or a single-host daemon, but having a containerized application manage its own log files makes collection and rotation harder to centralize.
Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Fix the driver behind crashes, sound loss and screen glitches3Clear out junk files and repair common Windows errorsThe standard library does not provide a built-in JSON formatter, but a custom logging.Formatter can create a dictionary and pass it to json.dumps(). A third-party formatter such as python-json-logger is another option. Its import path has appeared differently in 2026 guides; check the documentation for the installed package version instead of copying a path from an unrelated example.
For a structured event, include a timestamp, severity, logger name, message, and relevant fields such as request or trace identifiers. Keep names stable so downstream queries do not need to account for multiple spellings of the same concept. Use UTC and ISO-8601 to avoid ambiguity when events from different hosts are combined. Do not make the JSON pretty: each serialized event should occupy exactly one line.
When choosing an output format, separate human development output from machine ingestion. A terminal can benefit from color and readable tracebacks; a production stream should remain parseable. With structlog, its documented best-practice split is to use a console renderer when sys.stderr.isatty() is true and JSON otherwise, with structured tracebacks in the JSON path.
How do I add request IDs and trace context?
Add correlation fields at the point where the request or task context is known, so every event for that operation can be connected later. In the standard library, use call-level extra, a LoggerAdapter, or a filter that copies values from contextvars onto each LogRecord.
logger.info(
"Payment authorized",
extra={"request_id": request_id, "user_id": user_id},
)
The formatter or JSON renderer must also include those record fields in the output. Adding a value to a record does not automatically make it visible in every format. Python 3.12 added the taskName LogRecord attribute, which can be rendered with %(taskName)s to identify an asyncio task by name.
For async work, avoid creating one logger per request or connection; the logging cookbook warns that these logger instances are not garbage-collected as users may expect. Keep logger identity tied to modules and put changing request data in context instead. In structlog, bind() and unbind() provide immutable context handling, while contextvars.bind_contextvars() and the merge_contextvars processor can carry request-scoped values across asyncio tasks. Loguru offers bind(), contextualize(), and patch().
OpenTelemetry can correlate logs with traces by injecting fields such as trace_id, span_id, and resource.service.name into standard-library records through its logging instrumentation. Another integration path is an OpenTelemetry SDK logging handler. These APIs depend on the installed OpenTelemetry Python package versions, so verify current package documentation and module paths when implementing them.
Also popular on Amazon
- Portable and powerful USB-C HUB: BENFEI USB Type-C HUB, with super-soft and knot-free silicone woven design cable, meets most mobile office needs. Compact, lightweight, stylish, and powerful portable USB C Hub equipped with 1 x HDMI port, 1 x 100W charging, and 3 x USB ports. 18-month warranty, 24-hour response, to ensure you feel at ease when using our product.
- Design centered on comfort and reliability: Thanks to BENFEI's end-to-end in-house cable production capability, in-house PCBA and assembly capability, using the industry's most advanced silicone woven design and process, 20cm cable in length, no knots, super-soft, the HUB is easy to use in all scenarios: laptop, tablet, stand etc. Super-soft, 25000+ life cycles, to meet your daily carrying and office needs.
- 100W Charging: Support up to 90W USB C pass-through charging via Type-C port to keep your laptop powered. 10W is reserved for other interface operations. No data and video function on the Type-C port.
- 4K HDMI Display: The HDMI port supports media display at resolutions up to 4K 30Hz, keeping every incredible moment detailed and ultra vivid. Please note that the C port of the Host device needs to support video output.
- Transfer Files in Seconds: Transfer files and from your laptop at speeds up to 10 Gbps with USB A 3.2 port. Extra 2 USB A 2.0 ports are perfectly for your keyboards and mouse.
How can I keep logging from slowing requests?
Move potentially blocking output off the request or event-loop thread with QueueHandler and QueueListener. The application thread enqueues a record; a listener thread drains the queue and sends it to the slow destination.
File writes, SMTP, and network handlers can block. Even a socket handler can incur a slow DNS lookup. In asyncio code, a blocking file or network handler can stall the event loop just as it can delay a synchronous request. The logging cookbook’s queue recipe keeps the hot path focused on enqueueing while the listener performs sink I/O.
In Python 3.12 and later, dictConfig() can wire a queue handler and listener together through a handler entry whose handlers list names the sink handlers. The listener is available as logging.getHandlerByName("queue").listener; start it during application startup and stop it during shutdown so queued events can be drained. With a manually created listener, respect_handler_level=True has been supported since Python 3.5 and makes each sink’s level apply.
There is an important context caveat: a listener runs on another thread and does not automatically see the request thread’s contextvars. Add request fields on the emitting thread—on the logger or queue handler—before the record enters the queue. The standard QueueHandler.prepare() formats messages and clears args and exc_info to make records suitable for pickling. For an in-process queue.Queue, a custom subclass can preserve the original record when structured exception fields are needed; consider queue serialization requirements before changing that behavior.
Which handlers can send Python logs to files and services?
Choose a handler based on the destination and the deployment environment. The standard library provides stream, file, and null handlers directly, with additional handlers in logging.handlers.
Quick wins for a faster PC:
Clear out junk files and repair common Windows errorsFree Scan →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Repair Windows errors before they cause bigger problemsFix Now →| Handler | Use and caveat |
|---|---|
StreamHandler |
Writes to a stream; defaults to sys.stderr. |
FileHandler |
Writes to a file. |
NullHandler |
Discards events; appropriate as a library’s no-op handler. |
RotatingFileHandler |
Rotates by size using maxBytes and backupCount; rollover does not occur if either value is zero. |
TimedRotatingFileHandler |
Rotates files on a time schedule. |
WatchedFileHandler |
Works with external rotation such as Unix/Linux logrotate; not appropriate on Windows. |
QueueHandler and QueueListener |
Move sink work to a listener thread to reduce blocking on the emitting path. |
SocketHandler, DatagramHandler, HTTPHandler |
Send records over network-related transports; account for I/O delays and transport security. |
SMTPHandler |
Sends email; can block, so avoid sending directly on a latency-sensitive path. |
SysLogHandler |
Sends to Unix syslog, including a remote syslog service where configured. |
NTEventLogHandler |
Writes to the Windows event log. |
MemoryHandler |
Buffers records before forwarding them to another handler. |
A rotating-file example in the Python documentation uses maxBytes=1024 and backupCount=3; a 2026 production recipe uses maxBytes=10_000_000, backupCount=5, and UTF-8. Those are examples, not universal retention recommendations. Choose limits based on the host’s storage, event volume, retention needs, and whether an external system already owns log rotation.
SocketHandler uses pickle serialization by default. The logging cookbook warns about pickle’s security implications; if records cross a trust boundary, do not accept untrusted pickled data. Consider a safer serialization format and an authenticated, appropriately protected transport.
How should Python log exceptions?
Inside an except block, use logger.exception() when the event should include the active exception information. It is equivalent to logger.error(..., exc_info=True).
try:
process_record(record)
except ValueError:
logger.exception("Could not process record")
Use stack_info=True when you need the current stack even without an active exception. Use stacklevel in a logging helper when you want the recorded source location to point to the helper’s caller rather than the helper implementation. For uncaught exceptions, applications can route tracebacks through the same configured output by installing sys.excepthook and, for thread exceptions, threading.excepthook.
Recommended Free Tools
By default, logging.raiseExceptions is True, which helps expose handler failures during development. The Python HOWTO advises setting it to False for production so an error while emitting a log record does not disrupt the application. This does not swallow SystemExit or KeyboardInterrupt. Ensure that silently suppressing handler errors is paired with monitoring of the logging pipeline itself.
Also popular on Amazon
- 【Read before You Buy】 Note: This adapter is USB 2.0 version and cannot transmit HDM, VGA, or other video signals. Nevertheless, they are fully capable of charging devices,duplicating files, and can be seamlessly integrated with USB-C earphones, wireless network adapters, and SD card adapters.
- 【Easy to Use and Safe】Thanks to modern manufacturing techniques, we've made these adapters sufficiently compact so that they can remain inserted in your device without noticeable protrusion or inconvenience. This means you don't have to constantly plug and unplug them, reducing the likelihood of wear and misalignment, and making them more convenient to carry around.
- 【Reliable Quality】Engineered for enhanced durability, durable aluminum alloy shell material,get excellent wear resistance and heat dissipation,the male USB C and female USB connectors & the male USB and female USB C connectors are designed to be plugged and unplugged up to 20000 times. Provides data transfer, device charging, memory space expansion, and additional computer peripherals.
- 【Think more for you】Do you need to connect a USB-C-enabled device to an odd device that only has USB-A ports? Then these USB-A male to USB-C female adapters are made for you.Simply insert the adapter into the USB-A port on the device, and you can instantly connect your USB-C device to the device that originally didn't have the correct connection port.
- 【Trusted xiwxi Quality and Service】As a responsible brand seller, you will receive xiwxi's 12-month Quality assurance and lifetime friendly customer service, you're not just buying a product,you're investing in peace of mind with all-round quality and exceptional customer service.
Should I choose stdlib logging, structlog, or Loguru?
They are not mutually exclusive. Standard-library logging offers the broadest compatibility and is the right library interface; structlog adds structured events and processor pipelines; Loguru gives applications a compact, opinionated API with built-in conveniences.
| Concern | Standard-library logging | structlog | Loguru |
|---|---|---|---|
| Ships with Python | Yes | No; install separately | No; install separately |
| Configuration | dictConfig() |
structlog.configure(); can wrap standard logging |
Remove default sink, then configure with logger.add() |
| JSON | Custom formatter or third-party formatter | End the processor chain with JSONRenderer |
serialize=True |
| Structured fields | extra or filters |
Native event keyword arguments and bind() |
bind() and extra fields |
| Context | Use adapters, filters, or contextvars |
merge_contextvars and binding |
bind() or contextualize() |
| Non-blocking output | QueueHandler and QueueListener |
Can route through standard-library queue handlers | enqueue=True |
| File rotation | RotatingFileHandler or TimedRotatingFileHandler |
Can delegate to standard-library handlers | Built-in rotation, retention, and compression options |
| Library etiquette | Use a package logger and NullHandler |
Avoid globally configuring an importing application’s logging | Can disable a library namespace with logger.disable() |
| Good fit | Libraries, compatibility, and a dependable default | Structured service events and processor pipelines | Small apps or scripts seeking fewer configuration steps |
For a library, use standard logging and a NullHandler; introducing a third-party logging dependency can constrain the host application. For an application that needs queryable structured events, structlog can wrap standard handlers so third-party standard-library records still use the same output format. Its documented stable release is 26.1.0; it can also run on its own. Processor functions receive a logger, method name, and event dictionary, and the renderer belongs at the end of the chain. Placing a renderer before processors that still modify the event dictionary can cause errors.
For a small app or script that values a compact API, Loguru includes formatting, rotation, retention, compression, and exception-diagnostic options. It can intercept standard-library records when an application wants one output pipeline. Its README’s “10x faster” statement is a vendor claim, not an independent benchmark; choose a library for integration and workflow fit rather than that unverified comparison.
One practical default is standard logging, a JSON formatter, stdout, and a queue when the sink could block. If the event model or ergonomics justify another library, add it deliberately rather than treating the logging choices as an all-or-nothing migration.
How do I protect sensitive data in logs?
Do not log passwords, access tokens, full payment-card numbers, or session cookies. Log a safe identifier or a redacted value instead, and review both event fields and exception output for secrets.
Structured logging makes redaction easier to centralize. A structlog processor can redact fields such as password, token, and api_key before rendering. Apply equivalent controls in a standard-library filter or formatter if those fields can arrive through extra. Redaction should be based on the data model, not only on message text, because secrets can be embedded in exception messages or arbitrary fields.
Loguru’s diagnose=True is enabled by default and may expose local variable values in tracebacks; disable it in production when those values could contain sensitive information. The Python logging configuration documentation also warns that configuration from untrusted sources should be treated with “extreme caution.” The older fileConfig() evaluates handler arguments in the logging namespace, and dictConfig() can import or invoke configured objects. Likewise, logging.config.listen() can accept a local configuration capable of code execution; use its verify argument where appropriate and do not expose it as an unauthenticated configuration channel.
Windows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallOutdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchWhat production checklist should I use?
A production-ready setup is less about one logging package than a set of decisions that keep events useful, parseable, and safe.
- Create
logging.getLogger(__name__)in each module; do not instantiate loggers directly. - Configure once at application startup. Use
dictConfig()for an application and setdisable_existing_loggerstoFalse. - Send container or cluster logs as one JSON object per stdout line, with UTC ISO-8601 timestamps and stable field names.
- Add request IDs and trace fields before records leave the request or task context.
- Use a queue handler/listener when file, network, email, or other sink I/O could block a request or event loop.
- Record exceptions intentionally; raise errors the caller must handle rather than merely logging them.
- Redact credentials, tokens, cookies, and other sensitive data; check traceback diagnostics as well as ordinary fields.
- Keep file rotation on a suitable single host, or let the deployment platform own routing and retention in containerized systems.
- Protect logging configuration and transports as security-sensitive components.
The Python documentation is the authoritative source for standard-library behavior and the cited version details here are for Python 3.13.18. structlog’s documented release is 26.1.0. OpenTelemetry integration APIs and third-party formatter import paths can vary by installed release, so verify those package-specific details against the version in the application.
Frequently Asked Questions
Why does logging.info not print anything in Python?
The root logger begins at WARNING, so INFO records fall below its default threshold. Set a lower level during configuration, for example with basicConfig(level=logging.INFO), before emitting the message.
Can I use print and logging in the same Python program?
Yes. Use print() for ordinary output intended for a person running a command-line program, and logging for operational events or diagnostics. Keeping those channels distinct makes it easier to redirect or collect diagnostic output.
The Tool Desk
Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Does Python logging work across multiple processes?
A standard in-process queue and listener coordinate threads, not separate processes by themselves. For multi-process applications, use a process-safe design—such as a queue managed for inter-process use or a dedicated log collector—and ensure each process does not independently rotate the same file.
How can I inspect the effective level of a Python logger?
Call logger.getEffectiveLevel() to see the numeric threshold inherited through its hierarchy. In Python 3.11 and later, logging.getLevelNamesMapping() can return the mapping of registered level names to numeric values.

