python logging将日志同时输出到文件和终端
2021-06-07 09:03
标签:format hand tle log mat ogg now() asi dha 1.logging模块输出日志 2.将日志同时输出到文件和终端 python logging将日志同时输出到文件和终端 标签:format hand tle log mat ogg now() asi dha 原文地址:https://www.cnblogs.com/pfeiliu/p/14587422.htmlimport logging as logger
import time
import datetime
print(time.localtime(),datetime.datetime.now())
print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
print("---------->>>",time.strftime("%Y-%m-%d %H:%M:%S",time.localtime()))
logger.basicConfig(level=logger.DEBUG,format=‘%(asctime)s %(lineno)s -%(levelname)s- -%(filename)s - %(message)s‘,
datefmt="%Y-%m-%d %H:%M:%S")
logger.debug("This is debug")
logger.info("This is info")
logger.warning("This is warning")
print("{:.^30}".format("ok"))
import logging
logger = logging.getLogger(__file__)
logger.setLevel(logging.DEBUG)
# 建立一个filehandler来把日志记录在文件里,级别为debug以上
fh = logging.FileHandler("log.log")
fh.setLevel(logging.DEBUG)
# 建立一个streamhandler来把日志打在CMD窗口上,级别为error以上
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
# 设置日志格式
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(lineno)s %(message)s",datefmt="%Y-%m-%d %H:%M:%S")
ch.setFormatter(formatter)
fh.setFormatter(formatter)
#将相应的handler添加在logger对象中
logger.addHandler(ch)
logger.addHandler(fh)
# 开始打日志
logger.debug("debug message")
logger.info("info message")
logger.warn("warn message")
logger.error("error message")
logger.critical("critical message")
文章标题:python logging将日志同时输出到文件和终端
文章链接:http://soscw.com/index.php/essay/91674.html