🌐 이 글의 한국어 원문이 있습니다.한국어 원문 보기 →
How to Use the Python Logger
When working with Python, there are times you need to handle logs through a logging module. These are cases where you go beyond just using the print function and need to emit logs while configuring things like the output level and format.
Java has a well-known library called log4j. In Python, the built-in logger module is what people commonly use. Using ‘logs’ well helps a lot with development. Especially as a project grows, setting levels for and managing ‘logs’ becomes important.
As a module grows, so does the number of ‘files’. You need ‘consistent’ management of the ‘logs’ those files produce. There are also cases where you need to pull out the ‘logs’ built into an existing module and use them through configuration.
logger = logging.getLogger(__name__)Usually, the logger inside a module is declared in each file in the form above. __name__ typically holds the package or module name.
If you set it up like that in every file and write logs, everything associated with the same ‘package’ or ‘module’ name can be output with the same settings. By the same settings, I mean the log format, level, handler (whether to print to the screen or save to a file), and so on.
import logging
log_format = '%(asctime)s [%(filename)s:%(lineno)s|%(levelname)s] %(funcName)s(): %(message)s'
logging.basicConfig(format=log_format, level=logging.INFO)
logger = logging.getLogger('name_of_module')In the file that serves as the initial entry point, apply the ‘necessary’ settings such as the log format and log level in basicConfig, then call the ‘logger’ via getLogger with the ‘name’ of the module whose logs you want to emit, and that module's logger will work according to the configured settings. This lets you adjust the format you want or the level you want to see.
When controlling a module's logs, you must configure logging before you import the module. Once the module has been imported, configuring it as above won't take effect.
When you first encounter the logger, it takes some grasp of the concepts and some understanding. As with all software, it feels unfamiliar while you're first getting the concepts, but once you've got them it isn't hard. The Python manual explains the concepts and usage of the logger well, so learn it and try it out with that page as a reference.
https://docs.python.org/ko/3/howto/logging.htmldocs.python.org