1.日志级别
级别顺序从高到低
critical>error>warning>info>debug
- debug: 打印全部的日志,详细的信息,通常只出现在诊断问题上
- info: 打印info,warning,error,critical级别的日志,确认一切按预期运行
- warning: 打印warning,error,critical级别的日志,一个迹象表明,一些意想不到的事情发生了,或表明一些问题在不久的将来(例如。磁盘空间低”),这个软件还能按预期工作
- error: 打印error,critical级别的日志,更严重的问题,软件没能执行一些功能
- critical: 打印critical级别,一个严重的错误,这表明程序本身可能无法继续运行
日志格式变量:
- %(levelno)s: 打印日志级别的数值%(levelname)s: 打印日志级别名称
- %(pathname)s: 打印当前执行程序的路径,其实就是sys.argv[0]
- %(filename)s: 打印当前执行程序名
- %(funcName)s: 打印日志的当前函数
- %(lineno)d: 打印日志的当前行号
- %(asctime)s: 打印日志的时间
- %(thread)d: 打印线程ID
- %(threadName)s: 打印线程名称
- %(process)d: 打印进程ID
- %(message)s: 打印日志信息
import logging# logging.basicConfig(level=logging.DEBUG)logging.debug("i am is debug log")logging.info("i am is info log")logging.warning("i am is warning log!!")logging.error("i am is error log!!!")logging.critical("i am is critical log!!!!")

默认日志级别是warning,所以不显示debug跟info级别的日志
如果要显示开启注释,logging.basicConfig(level=logging.DEBUG)
2.日志输出到控制台
import logginglogging.basicConfig(level=logging.DEBUG,format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')logging.debug("i am is debug log")logging.info("i am is info log")logging.warning("i am is warning log!!")logging.error("i am is error log!!!")logging.critical("i am is critical log!!!!")
3.将日志写入文件
import loggingimport os.pathimport time# 第一步,创建一个loggerlogger = logging.getLogger()logger.setLevel(logging.INFO) # Log等级总开关# 第二步,创建一个handler,用于写入日志文件rq = time.strftime('%Y%m%d%H%M', time.localtime(time.time()))log_path = os.path.dirname(os.getcwd()) + '/Logs/'if not os.path.exists(log_path):os.mkdir(log_path)log_name = log_path + rq + '.log'logfile = log_namefh = logging.FileHandler(logfile, mode='w')fh.setLevel(logging.DEBUG) # 输出到file的log等级的开关# 第三步,定义handler的输出格式formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")fh.setFormatter(formatter)# 第四步,将logger添加到handler里面logger.addHandler(fh)# 日志logging.debug("i am is debug log")logging.info("i am is info log")logging.warning("i am is warning log!!")logging.error("i am is error log!!!")logging.critical("i am is critical log!!!!")
4.同时将日志输出到控制台及写入文件
import loggingimport osimport time# 第一步,创建一个loggerlogger = logging.getLogger()logger.setLevel(logging.INFO) # Log等级总开关# 第二步,创建一个handler,用于写入日志文件rq = "app"log_path = os.path.dirname(os.getcwd()) + '/Logs/'if not os.path.exists(log_path):os.mkdir(log_path)log_name = log_path + rq + '.log'logfile = log_namefh = logging.FileHandler(logfile, mode='w')fh.setLevel(logging.DEBUG) # 输出到file的log等级的开关#控制台的handlerch = logging.StreamHandler()#设置控制台输入的日志为warning级别以上的ch.setLevel(logging.WARNING)# 第三步,定义handler的输出格式formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")fh.setFormatter(formatter)ch.setFormatter(formatter)# 第四步,将logger添加到handler里面logger.addHandler(fh)logger.addHandler(ch)# 日志logging.debug("i am is debug log")logging.info("i am is info log")logging.warning("i am is warning log!!")logging.error("i am is error log!!!")logging.critical("i am is critical log!!!!")
5.日志按天切割
import osimport loggingimport refrom logging.handlers import TimedRotatingFileHandlerdef setup_log(log_name):# 创建logger对象。传入logger名字logger = logging.getLogger(log_name)log_path = os.path.dirname(os.getcwd()) + '/Logs/'if not os.path.exists(log_path):os.mkdir(log_path)log_path = os.path.join(log_path,log_name)# 设置日志记录等级logger.setLevel(logging.DEBUG)# interval 滚动周期,# when="MIDNIGHT", interval=1 表示每天0点为更新点,每天生成一个文件# backupCount 表示日志保存个数file_handler = TimedRotatingFileHandler(filename=log_path, when="MIDNIGHT", interval=1, backupCount=30,encoding="utf-8")# filename="app" suffix设置,会生成文件名为mylog.2020-02-25.logfile_handler.suffix = "%Y-%m-%d.log"# extMatch是编译好正则表达式,用于匹配日志文件名后缀# 需要注意的是suffix和extMatch一定要匹配的上,如果不匹配,过期日志不会被删除。file_handler.extMatch = re.compile(r"^\d{4}-\d{2}-\d{2}.log$")# 定义日志输出格式file_handler.setFormatter(logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s"))logger.addHandler(file_handler)return loggerif __name__ == "__main__":logger = setup_log("app")logger.info("this is info message")logger.warning("this is a warning message")try:int("aaaaa")except Exception as e:logger.error("强行转int失败",exc_info=e)

