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")
也可进一步封装方便调用