python log日誌
阿新 • • 發佈:2019-02-15
python 日誌管理,可通過引入logging包,實現日誌管理
一、配置檔案
- 建立一個配置檔案,如logging.conf
[loggers] keys=root,console,file [logger_root] level=DEBUG handlers=rootHandler formatter=rootFormatter [logger_console] level=DEBUG handlers=consoleHandler formatter=consoleFormatter qualname=console [logger_file] level=DEBUG handlers=fileHandler formatter=fileFormatter qualname=file [handlers] keys=rootHandler,consoleHandler,fileHandler [handler_rootHandler] class=StreamHandler level=DEBUG formatter=rootFormatter args=(sys.stdout,) [handler_consoleHandler] class=StreamHandler level=DEBUG formatter=consoleFormatter args=(sys.stdout,) [handler_fileHandler] class=FileHandler level=DEBUG formatter=fileFormatter args=("./log.log","a") [formatters] keys=rootFormatter,consoleFormatter,fileFormatter [formatter_rootFormatter] format=[%(asctime)s][%(filename)s][line:%(lineno)d][%(levelname)s] %(message)s datefmt=%a, %d %b %Y %H:%M:%S [formatter_consoleFormatter] format=[%(asctime)s][%(filename)s][line:%(lineno)d][%(levelname)s] %(message)s datefmt=%a, %d %b %Y %H:%M:%S [formatter_fileFormatter] format=[%(asctime)s][%(filename)s][line:%(lineno)d][%(levelname)s] %(message)s datefmt=%a, %d %b %Y %H:%M:%S
- 呼叫log即可
import logging.config logging.config.fileConfig("./logging.conf") logger = logging.getLogger('file') logger.debug("debug message") logger.info("info message") logger.warn("warn message") logger.warning("warning message") logger.critical("critical message")
二、不用配置檔案,直接擼程式碼
呼叫時,直接引入即可import logging from colorlog import ColoredFormatter def create_console_formatter(formatter='%(log_color)s[%(asctime)s][%(filename)s][line:%(lineno)d][%(levelname)s] %(message)s'): return formatter def create_file_formatter(formatter='%(log_color)s[%(asctime)s][%(filename)s][line:%(lineno)d][%(levelname)s] %(message)s'): return formatter #color不同level,不同顏色 def color_formatter(formatter): return ColoredFormatter(formatter) def create_console_handler(formatter=ColoredFormatter(create_console_formatter()), level=logging.DEBUG): console_handler = logging.StreamHandler() console_handler.setLevel(level) console_handler.setFormatter(formatter) return console_handler def create_file_handler(formatter=ColoredFormatter(create_console_formatter()), level=logging.DEBUG, log_file='./log.log', mode='a',encoding='UTF-8'): file_handler = logging.FileHandler(log_file, mode, encoding) file_handler.setLevel(level) file_handler.setFormatter(formatter) return file_handler
console_handler = create_console_handler()
file_handler = create_file_handler()
logger = logging.getLogger("console")
logger.setLevel(logging.DEBUG)
logger.addHandler(console_handler)
logger.addHandler(file_handler)
也可進一步封裝方便呼叫logger.debug("debug") logger.info("info") logger.warning("warning") logger.error("error") logger.critical("critical")