当前位置: 首页 > 后端技术 > Python

pythonloggingUtils

时间:2023-03-26 12:24:17 Python

"""loggingconfiguration"""importosimportlogging.configimporttime#定义三种日志输出格式startstandard_format='[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]'\'[%(levelname)s][%(message)s]'#其中name是getlogger指定的名称simple_format='[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'id_simple_format='[%(levelname)s][%(asctime)s]%(message)s'#定义日志输出格式endlogfile_dir=os.path.dirname(os.path.abspath(__file__))+"/"+"log"#日志文件目录current_data=time.strftime("%Y-%m-%d",time.localtime())#logfile_name='data/yolo_app.log'#日志文件名logfile_name=logfile_dir+'/'+current_data+'.log'#如果没有定义日志目录,则创建一个ifnotos.path.isdir(logfile_dir):os.mkdir(logfile_dir)#日志文件的完整路径logfile_path=os.path.join(logfile_dir,logfile_name)#日志配置字典LOGGING_DIC={'version':1,'disable_existing_loggers':False,'formatters':{'standard':{'format':standard_format},'simple':{'format':simple_format},},'filters':{},'handlers':{#打印到终端的日志'console':{'level':'DEBUG','class':'logging.StreamHandler',#打印到屏幕'formatter':'simple'},#打印日志到文件,收集信息及以上的日志'default':{'level':'DEBUG','class':'logging.handlers.RotatingFileHandler',#保存到文件'formatter':'standard','filename':logfile_path,#logfile'maxBytes':1024*1024*5,#logsize5M'backupCount':5,'encoding':'utf-8',#日志文件的编码,再也不用担心中文日志乱码了},},'loggers':{#logging.getLogger(__name__)获取的logger配置'':{'handlers':['default','console'],#在这里添加上面定义的两个handler,即日志数据既写入文件又打印到屏幕'level':'DEBUG','propagate':True,#up(Higherlevellogger)pass},},}logging.config.dictConfig(LOGGING_DIC)#导入上面定义的日志配置logger=logging.getLogger(__name__)#生成日志实例#logger.setLevel(logging.DEBUG)#logger.info('Itworks!')#记录文件的运行状态