Python日志模块-Logging的应用
1 代码示例
代码仓库:OnlyAR/Logger (github.com)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 import loggingimport osimport colorlog console_level = logging.DEBUG file_level = logging.INFO log_colors_config = { 'DEBUG' : 'white' , 'INFO' : 'green' , 'WARNING' : 'yellow' , 'ERROR' : 'red' , 'CRITICAL' : 'bold_red' , } os.chdir(os.path.dirname(os.path.abspath(__file__)))def _get_logger (): logger = logging.getLogger('logger' ) logger.setLevel(logging.DEBUG) console_handler = logging.StreamHandler() console_formatter = colorlog.ColoredFormatter( fmt='%(log_color)s[%(levelname)s]: %(message)s' , log_colors=log_colors_config ) console_handler.setFormatter(console_formatter) console_handler.setLevel(console_level) logger.addHandler(console_handler) file_handler = logging.FileHandler('log.txt' , encoding='utf8' ) file_formatter = logging.Formatter( fmt='[%(asctime)s] %(filename)s -> %(funcName)s line:%(lineno)d [%(levelname)s]: %(message)s' , ) file_handler.setFormatter(file_formatter) file_handler.setLevel(file_level) logger.addHandler(file_handler) return logger logger = _get_logger()
2 日志的终极解决方案:Loguru
后来我在项目中发现了更好用的开源日志库Delgan/loguru ,安装命令:
2.1 简单使用方法:
1 2 3 4 5 6 from loguru import logger logger.debug("This is a debug" ) logger.info("This is an info" ) logger.warning("This is a warring" ) logger.error("This is an error" )
1 2 3 4 2023-07-25 15:37:00.217 | DEBUG | __main__:<module>:3 - This is a debug 2023-07-25 15:37:00.217 | INFO | __main__:<module>:4 - This is an info 2023-07-25 15:37:00.217 | WARNING | __main__:<module>:5 - This is a warring 2023-07-25 15:37:00.217 | ERROR | __main__:<module>:6 - This is an error
1 2 3 from loguru import logger logger.add("log.txt" )
1 2 3 4 from loguru import logger log = logger.add("log.txt" ) logger.remove(log)