configparser logging

configparser模块        # 该模块适用于配置文件的格式与windows ini文件类似,可以包含一个或多个节(section),每个节可以有多个参数(键=值)。
import configparser
config = configparser.ConfigParser()
config['bitbucket.org'] = {'User':'hg'}
config['topsecret.server.com'] = {'Host Port':'50022','ForwardX11':'no'}
with open('example.ini', 'w') as configfile:config.write(configfile)
#---------------------------查找文件内容,基于字典的形式
config = configparser.ConfigParser()
config.read('example.ini')                            
print(config.sections())
print('bytebong.com' in config)                     # False
print(config['bitbucket.org']["user"])              # hg
for key in config['bitbucket.org']:print(key)        # 注意,有default会默认default的键
print(config.options('bitbucket.org'))              # 同for循环,找到'bitbucket.org'下所有键
print(config.items('bitbucket.org'))                # 找到'bitbucket.org'下所有键值对
print(config.get('bitbucket.org','compression'))    # yes    get方法Section下的key对应的value
#---------------------------增删改
config = configparser.ConfigParser()
config.read('example.ini')
config.add_section('yuan')                                    # 增加section
config.remove_section('bitbucket.org')                        # 删除一个section
config.remove_option('topsecret.server.com',"forwardx11")    # 删除一个配置项
config.set('topsecret.server.com','k1','11111')
config.set('yuan','k2','22222')
config.write(open('new2.ini', "w"))


import logging
# logging.basicConfig(level=logging.WARNING,
#                     format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
#                     datefmt='%a, %d %b %Y %H:%M:%S')
# logging.debug('debug message')        # 低级别的 # 排错信息
# logging.info('info message')            # 正常信息
# logging.warning('warning message')    # 警告信息
# logging.error('error message')        # 错误信息
# logging.critical('critical message')    # 高级别的 # 严重错误信息
# # basicconfig 简单 能做的事情相对少    # 中文的乱码问题    # 不能同时往文件和屏幕上输出
# 
# 配置log对象 稍微有点复杂 能做的事情相对多
import logging
logger = logging.getLogger()        #logger.setLevel(logging.DEBUG)
fh = logging.FileHandler('log.log',encoding='utf-8')    # 创建一个文件控制对象
sh = logging.StreamHandler()                            # 创建一个屏幕控制对象
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
formatter2 = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s [line:%(lineno)d] : %(message)s')
# 文件操作符 和 格式关联
fh.setFormatter(formatter)
sh.setFormatter(formatter2)
# logger 对象 和 文件操作符 关联
logger.addHandler(fh)
logger.addHandler(sh)
logging.debug('debug message')    # 低级别的 # 排错信息
logging.info('info message')    # 正常信息
logging.warning('警告错误')        # 警告信息
logging.error('error message')    # 错误信息
logging.critical('critical message')    # 高级别的 # 严重错误信息
 

 

posted @ 2018-08-26 12:29  ming-yuan  阅读(199)  评论(0编辑  收藏  举报