python3 logging模块实操备忘

#!/usr/bin/env python3
import logging
'''
log_format = "%(asctime)s - %(levelname)s - %(message)s"
DATE_FORMAT = "%m/%d/%Y %H:%M:%S %p"

logging.basicConfig(filename = "my.log", level = logging.DEBUG, format = log_format, datefmt = DATE_FORMAT,filemode = "a")

logging.debug("debug information")
logging.info("info informationg")
logging.warning("warning information")
logging.error("error informationg")
logging.critical("critical.information")
'''
# 制作日志对象函数。方便后面引用---更高级的日志函数!
def log(a):
    logger = logging.getLogger(a)    # 返回一个日志器
    logger.setLevel(logging.INFO)      # 设置日志器将会处理的日志消息的最低严重级别
    fl = logging.FileHandler("example.log", encoding = "utf-8")     # 将日志消息发送到文件的日志对象
    sl = logging.StreamHandler()        # 将日志消息发送到输出到Stream(屏幕)的日志对象
    fl.setLevel(logging.DEBUG)   # 局部与全局之间。即以最高严重级别设置为主
    sl.setLevel(logging.INFO)
    formatter = logging.Formatter("%(name)s-%(asctime)s-%(levelname)s:%(message)s",datefmt = "%Y-%m-%d %H:%M:%S")   # 获得formatter对象
    fl.setFormatter(formatter)  # 绑定日志器fl和formatter对象
    sl.setFormatter(formatter)
    logger.addHandler(fl)   # 把日志器fl添加到大日志器logger上
    logger.addHandler(sl)
    # 以下对大日志器logger操作,即是对fl和sl操作:
    return logger
#    print(logger)
logger1 = log("a")  # 引用日志对象
logger1.info("INFO information")
logger1.debug("debug information")
logger1.warning("warning information")
logger1.error("error informationg")
logger1.critical("critical.information")



   

posted @ 2019-01-14 09:04  挖坑达人  阅读(4)  评论(0编辑  收藏  举报