分两种,一种打印到终端,一种打印到文件。
1.打印到终端
2.打印到文件
3.两者同时
1.打印到终端:
#打印到终端
import logging
logging.basicConfig(level=logging.WARNING,format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')
logging.debug('这是 logging debug message')
logging.info('这是 logging info message')
logging.warning('这是 logging warning message') #打印
logging.error('这是 logging error message') #打印
logging.critical('这是 logging critical message') #打印
2.打印到日志文件
#打印到文件
import logging
logging.basicConfig(level=logging.WARNING,
filename='./log.txt',
filemode='a',
format='%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')
logging.debug('这是 logging debug message')
logging.info('这是 logging info message')
logging.warning('这是 logging warning message')
logging.error('这是 logging warning message')
logging.critical('这是 logging critical message')
3.同时打印到终端和文件
#打印到文件也打印到控制台
import logging
#1.创建一个logger
logger =logging.getLogger()
logger.setLevel(logger.INFO)
#2.创建一个hanndler 日志输出
logfile='./log.txt'
fh=logging.FileHandler(logfile,mode='a')
fh.setLevel(logging.WARNING)
#3.创建一个hanndler 控制台
ch=logging.StreamHandler()
ch.setLevel(logging.WARNING)
#4.定义handler输出格式
formatter=logging.Formatter('%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)
#5.添加到handler里
logger.addHandler(fh)
logger.addHandler(ch)
logger.debug('这是 logging debug message')
logger.info('这是 logging info message')
logger.warning('这是 logging warning message')
logger.error('这是 logging warning message')
logger.critical('这是 logging critical message')