How to write logs to a file in Python?
In Python, you can use the logging module to write logs to a file. Here is a simple example:
import logging
# 配置日志记录器
logging.basicConfig(filename='app.log', level=logging.INFO)
# 记录日志
logging.debug('This is a debug message')
logging.info('This is an info message')
logging.warning('This is a warning message')
logging.error('This is an error message')
logging.critical('This is a critical message')
In the example above, the logging.basicConfig() function is used to configure the logger, with the filename parameter specifying the path and name of the log file, and the level parameter specifying the level of the log (e.g., logging.INFO indicates only logging INFO level and above). Then, logging.debug(), logging.info(), and other functions can be used to record logs at different levels.