python 中类的重载以及logging中的level

来源:互联网 发布:龙蛇演义 知乎 编辑:程序博客网 时间:2024/05/20 17:10

由于之前深受java思想的洗礼,以至于现在学python满满的还都是抽象抽象抽象,一个简单的日志打印,轻微强迫症的我也必须 写一个通用的日志打印工具类,花费了差不多一天的时间,遇到了很多问题,当然最后都解决了:

下面将完整的代码share  to you:

#!/usr/bin/pythonimport loggingimport timeimport commands'''function:    exexte_shell(cmd)class:    logger(log_filename)'''def execute_shell(cmd):    ''' this func is simplely execute shell commands and output the execution    '''    log = logger()    (status, output) = commands.getstatusoutput(cmd)    if status == 0:        log.info('%s shell execute success'%(cmd))    else:        log.info('%s shell execute failed'%(cmd))class logger:    '''    this is a logger class due to simplely the log output and log manager  -->ok    '''    #get format current time    gCurrent_time = time.strftime('%Y-%m-%d-%H-%M-%S',time.localtime(time.time()))    def __init__(self, log_filename=None):        if log_filename == None:            logging.basicConfig(level=logging.DEBUG,                            format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',                            datefmt='%Y-$m-%d  %H:%M:%S')            print 'filename is none'            pass        else:            print 'log_filename is:', log_filename            filename =log_filename + '-' + str(self.gCurrent_time)            self.log_filename = filename            logging.basicConfig(level=logging.DEBUG,                            format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',                            datefmt='%Y-$m-%d  %H:%M:%S',                            filename=self.log_filename,                            filemode='w')            #setting for log printing in screen            console = logging.StreamHandler()            console.setLevel(logging.INFO)            format = '%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s'            formatter = logging.Formatter(format)            console.setFormatter(formatter)            logging.getLogger('').addHandler(console)    def info(self, s):        logging.info(s)    def debug(self, s):        logging.debug(s)    def warning(self, s):        logging.warning(s)
the test file is :

  1 from utils import logger  2 import utils  3  4 print utils.execute_shell('ls')  5  6 log1 = logger()  7 log1.info('no filename')  8  9 10 log2 = logger('ha') 11 log2.info('hahhhahahah')
 that's ok!

But I want to share some problems when  write  the script:

the first one:

怎样在python 中实现类的重载?即 ,构造函数可以没有参数,当然也可以有参数。

        as is shown above: use parameter ' log_filename = None'  , then judge the filename is or not None , and then do some things.

the second is :

       

    logging.basicConfig(level=logging.DEBUG) , you must set this value , if you don't set , the default is <span style="font-family: Arial, Helvetica, sans-serif;">logging.WARNING, so your debug and info level logs is missing.</span>

      

       Ok , that's all , thank you !



0 0
原创粉丝点击