日志(模块logging)

日志(模块logging)

快速使用

import logging

logging.basicConfig(filename="cmdb.text",
                    format = "%(asctime)s-%(name)s-%(levename)s-%(module)s-(message)s",
                    datefmt = "%Y-%m-%d %H:%S:%p"
                    level=logging.ERROR)

logging.log(20,"日志内容")
logging.debug("1")
logging.info("2")
logging.warning("3")
logging.error("4")
logging.critical("5")

#注意:多次配置无效

应用场景:对于异常处理捕获到的内容,使用日志模块将其保留到日志文件

import logging

logging.basicConfig(filename="li.text",
                    format = "%(asctime)s-%(name)s-%(levelname)s-%(module)s:(message)s",
                    datefmt = "%Y-%m-%d %H:%S:%p",
                    level=logging.ERROR)
try:
    print(yang)
except Exception as e:
    print("杨子良")
    msg = str(e)
    logging.error(msg,exc_info=True)  #exc_info=True打印出错的位置

日志的本质

import logging

file_handler = logging.FileHandler("zi.log","w",encoding="utf-8")   #先创建一个文件对象
fmt = logging.Formatter(fmt = "%(asctime)s-%(name)s-%(levelname)s-%(module)s:%(message)s") #抽取的格式
file_handler.setFormatter(fmt) #将两个对象进行关联

logger = logging.Logger("xxxxx",level = logging.ERROR) #如果达到这个水平的错误,便报错内容xxxxx

logger.addHandler(file_handler)
#反正我也没弄出来,不知道问题出在哪,愁人!

推荐用法

import logging

file_handler = logging.FileHandler("mo.log","a",encoding="utf-8")   #先创建一个文件对象
logging.basicConfig(
                   format = "%(asctime)s-%(name)s-%(levelname)s-%(module)s:(message)s",
                   datefmt = "%Y-%m-%d %H:%M:%S:%p",
                   handlers = [file_handler,],
                   level=logging.ERROR)

logging.error("你好")
#我也是服了,“你好”无法输出

日志分割

import time
from logging import handlers

file_handler = handlers.TimedRotatingFileHandler(filename = "x3.log", when='s', interval=5, encoding="utf-8",)
logging.basicConfig(
                   format = "%(asctime)s-%(name)s-%(levelname)s-%(module)s:(message)s",
                   datefmt = "%Y-%m-%d %H:%M:%S:%p",
                   handlers = [file_handler,],
                   level=logging.ERROR)

for i in range(1,1000):
    time.sleep(1)
    logging.error((str(i)))
posted @ 2021-06-11 14:41  小杨的冥想课  阅读(52)  评论(0编辑  收藏  举报