Python 02 解析配置文件和日志库的使用

[log]
path = /tmp/td_pay.log
quiet = False
debug_info = 1

[pay]
app_id = 223
app_key = c01f 

[database]
host = 1192.168.1.101
db_name = test 
user = test
passwd = no

 解析配置文件

import os
import ConfigParser
import logging
import sys
    
config_path = "/config.cfg"
config_path = os.path.abspath(os.path.expanduser(config_path))
if not os.path.exists(config_path):
    print "Please Configure Your config.cfg "
    sys.exit(0)
config = ConfigParser.RawConfigParser()
config.read(config_path)

log_file = os.path.abspath(os.path.expanduser(config.get(log, path)))
log_debug_info = config.getboolean(log, debug_info)
log_quiet = config.getboolean(log, quiet)
    
db_host = config.get(database, host)
db_name = config.get(database, db_name)
db_user = config.get(database, user)
db_passwd = config.get(database, passwd)

日志库的使用

import os
import logging
import sys
      
def log_init(log_file, log_debug_info, quiet=False):
    logger = logging.getLogger(__name__)
    if log_debug_info:
        logger.setLevel(logging.DEBUG)
    else:
        logger.setLevel(logging.INFO)

    hdlr = logging.FileHandler(log_file)
    formatter = logging.Formatter("%(process)s %(asctime)s %(pathname)s:%(lineno)d %(levelname)s %(message)s")
    hdlr.setFormatter(formatter)
    logger.addHandler(hdlr)
    if not quiet:
        hdlr = logging.StreamHandler()
        hdlr.setFormatter(formatter)
        logger.addHandler(hdlr)
    return logger

LOG = log_init(log_file, log_debug_info, log_quiet)

LOG.warn("Not This ss, ff is %s", ss)
LOG.debug("charge success")
LOG.error("Error %d: %s" % (e.args[0], e.args[1]))

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。