python笔记(配置文件模块和配置日志模块)

一、配置文件模块:configparser
1、写入配置文件

import configparser
config = configparser.ConfigParser()
config["名字"] = {'xiaoxiao':'18',
                'dada':'19',
                'xiaohuang':'12'
                  }
config['爱好'] = {'name':'打球'}
with open('config.ini','w',encoding='utf-8') as f:
    config.write(f)

生成文件的内容:

[名字]
xiaoxiao = 18
dada = 19
xiaohuang = 12
[爱好]
name = 打球

二、logging:日志
1、用来记录用户行为或者代码执行过程
logging
(1)能够’一键’控制
(2)排错的时候需要打印很多细节来帮助排错
(3)严重的错误记录下来
(4)有一些用户行为有没有错都要记录下来

import logging
logging.debug('debug message') #低级别的:排错信息
logging.info('debug message') #正常信息
logging.warning('warning message')#警告信息
logging.error('error message') #错误信息
logging.critical('critical message') #高级别的  : 严重错误信息

输出结果:

WARNING:root:warning message
ERROR:root:error message
CRITICAL:root:critical message

2、配置logging
(1) basicconfig 简单 能做的事少,不能同时往文件和屏幕上输出

import logging
logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(filename)s[line:%(lineno)d]%(levelname)s %(message)s',
                    datefmt='%a,%d %b %Y %H:%M:%S',
                    filename='test.log',
                    filemode='a'
                   )
logging.debug('debug message') #低级别的:排错信息
logging.info('debug message') #正常信息
logging.warning('warning message')#警告信息
logging.error('error message') #错误信息
logging.critical('critical message') #高级别的  : 严重错误信息

生成文件的内容:

Sat,24 Nov 2018 15:13:53 GUI.py[line:1844]DEBUGdebug message
Sat,24 Nov 2018 15:13:53 GUI.py[line:1845]INFOdebug message
Sat,24 Nov 2018 15:13:53 GUI.py[line:1846]WARNINGwarning message
Sat,24 Nov 2018 15:13:53 GUI.py[line:1847]ERRORerror message
Sat,24 Nov 2018 15:13:53 GUI.py[line:1848]CRITICALcritical message

@配置log对象 稍微有点复杂 能做事情相对多,让程序变得高可定制

import logging
logger = logging.getLogger()
fh = logging.FileHandler('log.log',encoding='utf-8')
sh = logging.StreamHandler()  #屏幕打印
formatter = logging.Formatter('%(asctime)s-%(name)s-%(levelname)s-%(message)s')
formatter1 = logging.Formatter('%(asctime)s-%(name)s-[line:%(lineno)d]-%(levelname)s-%(message)s')

#文件操作符和格式关联
fh.setFormatter(formatter)
sh.setFormatter(formatter1)
#logger对象和文件操作符关联
logger.addHandler(fh)
logger.addHandler(sh)

logging.debug('debug message') #低级别的:排错信息
logging.info('debug message') #正常信息
logging.warning('warning message')#警告信息
logging.error('error message') #错误信息
logging.critical('critical message') #高级别的  : 严重错误信息

输出结果:

2018-11-24 16:10:52,516-root-[line:1875]-WARNING-warning message
2018-11-24 16:10:52,543-root-[line:1876]-ERROR-error message
2018-11-24 16:10:52,544-root-[line:1877]-CRITICAL-critical message

生成文件的内容:

2018-11-24 16:10:52,516-root-WARNING-warning message
2018-11-24 16:10:52,543-root-ERROR-error message
2018-11-24 16:10:52,544-root-CRITICAL-critical message

猜你喜欢

转载自blog.csdn.net/qq_41433183/article/details/84451894