main.py
import logging
from mylib import my_func
def main():
"""
logger = logging.Logger(name="logger", level=logging.DEBUG)
若使用该方式,可将 logger 作为参数传入 my_func 函数
"""
logger = logging.getLogger(name="logger")
logger.setLevel(level=logging.DEBUG)
f_hdlr = logging.FileHandler(filename="log.log", mode="w", )
f_hdlr.setLevel(level=logging.DEBUG)
c_hdlr = logging.StreamHandler()
c_hdlr.setLevel(level=logging.INFO)
fmt = logging.Formatter(fmt="%(asctime)-21s"
"%(levelname)-10s"
"%(name)-16s "
"%(filename)-12s"
"%(funcName)-12s"
"Line: %(lineno)-6s"
"Msg: %(message)s",
datefmt="%Y-%m-%d %H:%M:%S")
f_hdlr.setFormatter(fmt)
c_hdlr.setFormatter(fmt)
logger.addHandler(hdlr=f_hdlr)
logger.addHandler(hdlr=c_hdlr)
logger.debug("debug msg")
logger.info("info msg")
logger.warning("warning msg")
logger.error("error msg")
logger.critical("critical msg")
my_func()
if __name__ == "__main__":
main()
mylib.py
def my_func():
logger = logging.getLogger(name="logger.mylib")
logger.debug("[my_func] debug msg")
logger.info("[my_func] info msg")
logger.warning("[my_func] warning msg")
logger.error("[my_func] error msg")
logger.critical("[my_func] critical msg")