Developers can configure logging in three ways : 1. Call configuration method Python Code explicitly creates a logger 、 Handler and formatter . 1. Create log configuration file and use `fileConfig() ` Function read . 1. Create a configuration information dictionary and pass it to `dictConfig()` Function . Relative to the first kind , The second way to use configuration files has more advantages , It's mainly about the separation of configuration and code , More clearly structured , And the ability of non developers to easily modify logging properties . This article will introduce the second way to use configuration file to record Python Program log , Will Python Program logs are printed to the console and log files respectively , Log files are iterated by timestamp , And can automatically delete expired files . # Configure file mode to print log First create a configuration file `logging.conf`, Here are the contents of the file . Here is the main introduction `TimedRotatingFileHandler` Configuration arguments for `args`, First argument `/var/log/demo3/example.log` Represents the file directory of the log output , Second argument `d` Represents the iteration log file in days , Third argument `1` Said every 1 Cycles , Multiplying the second and third arguments means that a log file is iterated every few cycles , The fourth argument `3` Indicates that only three log files are kept , Log files exceeding this value will be automatically cleared . ```shell [loggers] keys=root [handlers] keys=consoleHandler,timedRotatingFileHandler [formatters] keys=simpleFormatter [logger_root] level=INFO handlers=consoleHandler,timedRotatingFileHandler [handler_consoleHandler] class=StreamHandler level=INFO formatter=simpleFormatter args=(sys.stdout,) [handler_timedRotatingFileHandler] class=handlers.TimedRotatingFileHandler level=INFO formatter=simpleFormatter args=('/var/log/demo3/example.log','d',1,3) [formatter_simpleFormatter] format=%(asctime)s %(name)s %(levelname)s - %(message)s datefmt= ``` Write Python The program , Use `fileConfig() ` Function to read the configuration file , Test printing various types of logs . You can see that the log is printed using the configuration file , The program structure is very clear . ``` import logging.config logging.config.fileConfig('logging.conf') # create logger logger = logging.getLogger() logger.debug('debug message') logger.info('info message') logger.warning('warn message') logger.error('error message') logger.critical('critical message') ``` Execute Python The program , The console and log file output the following content : ``` 2020-11-03 20:50:49,434 simple_example.py INFO - info message 2020-11-03 20:50:49,435 simple_example.py WARNING - warn message 2020-11-03 20:50:49,435 simple_example.py ERROR - error message 2020-11-03 20:50:49,435 simple_example.py CRITICAL - critical message ``` # References https://docs.python.org/zh-cn/3/howto/logging.html#logging-advanced-tutorial Advanced day