Python·100 questions

How to log properly (logging) instead of using print?

Answer

Using the standard print function for debugging and monitoring application performance in Python is only acceptable when writing small scripts or rapid prototyping. When it comes to production applications, web services, or complex backend systems, the only correct solution is to use the built-in logging module. Unlike console output, logging allows you to flexibly manage message streams, save them to files, send them to metrics collection systems, and configure filtering by the severity of events.

Proper organization of logging begins with initializing a logger for each specific module by calling the getLogger function. It is standard practice to pass the special variable of the current module's name as an argument, which allows you to clearly see in the future exactly where a specific message came from. All events are divided into standard severity levels, such as debug for detailed debugging, info for recording normal program steps, warning for alerts about potential issues, and error with critical for severe failures that require immediate administrator intervention.

When designing a logging system, it is critically important to follow these security and architectural rules:

Never write sensitive user data to log files, such as passwords, access tokens, secret keys, or personal information.
Configure formatting and message handlers at the level of the application's main executable file, rather than inside library modules.
Avoid configuring the root logger in third-party libraries so as not to disrupt the logging settings in end-user applications.

Proper configuration of handlers and output formatters allows you to structure all messages into a convenient text or machine-readable JSON format. This significantly simplifies subsequent troubleshooting in production, analysis of user behavior, and monitoring the health of the entire software system using automated tools.

Was this answer helpful?

More questions in this topic

Related questions from other topics