Python(2)封装log方法
作者:互联网
logging模块是Python内置的标准模块,主要用于输出运行日志
logging模块的日志级别
日志等级(level) | 描述 |
---|---|
DEBUG | 最详细的日志信息,典型应用场景是 问题诊断 |
INFO | 信息详细程度仅次于DEBUG,通常只记录关键节点信息,用于确认一切都是按照我们预期的那样进行工作 |
WARNING | 当某些不期望的事情发生时记录的信息(如,磁盘可用空间较低),但是此时应用程序还是正常运行的 |
ERROR | 由于一个更严重的问题导致某些功能不能正常运行时记录的信息 |
CRITICAL | 当发生严重错误,导致应用程序不能继续运行时记录的信息 |
二次封装
本封装实现如下简单的调用方式,将自动在项目下创建log目录并记录日志,err日志会单独进行记录
import ... log=logger.MyLog() log.info("this is info") log.debug("this is debug") log.error("this is error") log.warning("this is waring")
完整代码如下
import logging import os import time LEVELS = { 'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'critical': logging.CRITICAL } logger = logging.getLogger() level = 'default' def create_file(filename): path = filename[0:filename.rfind('/')] if not os.path.isdir(path): os.makedirs(path) if not os.path.isfile(filename): fd = open(filename, mode='w', encoding='utf-8') fd.close() else: pass def set_handler(levels): if levels == 'error': logger.addHandler(MyLog.err_handler) logger.addHandler(MyLog.handler) def remove_handler(levels): if levels == 'error': logger.removeHandler(MyLog.err_handler) logger.removeHandler(MyLog.handler) def get_current_time(): return time.strftime(MyLog.date, time.localtime(time.time())) class MyLog: path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) log_file = path+'/log/'+time.strftime('%Y_%m_%d')+'_log.log' err_file = path+'/log/'+time.strftime('%Y_%m_%d')+'_err.log' logger.setLevel(LEVELS.get(level, logging.NOTSET)) create_file(log_file) create_file(err_file) date = '%Y-%m-%d %H:%M:%S' handler = logging.FileHandler(log_file, encoding='utf-8') err_handler = logging.FileHandler(err_file, encoding='utf-8') @staticmethod def debug(log_meg): set_handler('debug') logger.debug("[DEBUG " + get_current_time() + "]" + log_meg) remove_handler('debug') @staticmethod def info(log_meg): set_handler('info') logger.info("[INFO " + get_current_time() + "]" + log_meg) remove_handler('info') @staticmethod def warning(log_meg): set_handler('warning') logger.warning("[WARNING " + get_current_time() + "]" + log_meg) remove_handler('warning') @staticmethod def error(log_meg): set_handler('error') logger.error("[ERROR " + get_current_time() + "]" + log_meg) remove_handler('error') @staticmethod def critical(log_meg): set_handler('critical') logger.error("[CRITICAL " + get_current_time() + "]" + log_meg) remove_handler('critical') if __name__ == "__main__": MyLog.debug("This is debug message") MyLog.info("This is info message") MyLog.warning("This is warning message") MyLog.error("This is error") MyLog.critical("This is critical message")
the end.
标签:封装,log,Python,handler,time,logging,logger,MyLog 来源: https://www.cnblogs.com/mingfan/p/12865660.html