最近写一个工程Logging模块一直出现奇怪bug调了一整天,特此记录logging的主要使用方法和一些debug。
基本用法
logging一般为输出到屏幕,和输出到文件两种用法。
最常用的配置方式为logging.basicConfig()
import logging
logging.basicConfig( # 配置日志的输出方式及格式
level=logging.DEBUG,
filename='log.txt',
filemode='a',
format='%(asctime)s %(filename)s %(message)s',
)
logging.info('[INFO]:calling method i() in h()')
logging.error('[Error]:Soory,Exception occured')
logging.debug()
logging.setLevel()
logging.addFilter()
其中logging.setLevel有五个级别,只输出所设定级别及以上的信息
Level | Describtion |
---|---|
DEBUG | details |
INFO | information |
WARNING | unforecasted problem but not important |
ERROR | some functions of program don’t work |
CRITICAL | program don’t work |
配置handler
另一种使用方式可以更自由,即句柄配置
def setup_logging(folder_path,filename):
"""Create and init logger.
Args:
logfolder_path: "/log/"
filename: "Alien-phi-0.001-mu-14.txt"
Return:
logger:
"""
logfile = os.path.join(folder_path, filename)
logging.basicConfig(
level = logging.INFO,
format ='%(asctime)s - %(levelname)s - %(message)s',
datefmt = '%y-%m-%d %H:%M',
filename = logfile,
filemode = 'a')
filehandler = logging.FileHandler(logfile,encoding='utf-8')
logger = logging.getLogger()
logger.addHandler(filehandler)
return logger
if __name__ == "__main__":
fold = os.getcwd()
filename = "1.log"
logger = setup_logging(fold,filename)
logger.info("test")
网友评论