python 写的 logger 模块

发布时间:2020-01-25编辑:脚本学堂
python 写的 logger 模块,有需要的朋友,可以参考学习下。

python 写的 logger 模块,有需要的朋友,可以参考学习下。
 

复制代码 代码如下:

    #!/usr/bin/python
    # -*- coding: gbk -*-
    try:
        import logging
        import sys
    except ImportError, msg:
        print '*** ERROR:', msg
        sys.exit()

    #----------------------------------------------------------------
    # #
    # Usage: log(filename, loglevel, logs) #
    # LOG MODULE eg: logging.debug('msg') DEBUG-INFO-WARNING-ERROR #
    # #
    #-----------------------------------------------------------------

    def log(filename,level,msg):
        try:
            f = open(filename, 'a')
        except IOError, msg:
            print msg
            sys.exit()
        else:
            f.close

        if level not in (0, 1, 2, 3):
            print 'ERROR: Log level must in 0-3.'
            print ' 0: debug'
            print ' 1: info '
            print ' 2: warning'
            print ' 3: error'
            print ''
            print 'ModuleUsage: log(filename,level,msg)'
            print ''
            sys.exit()

        mylog = filename
        mylev = level
        mymsg = msg

        logformat = '%(asctime)s %(filename)s[line:%(lineno)d] [%(levelname)-8s]: %(message)s'
        dateformat = '%Y-%m-%d %H:%M:%S'
        cansolefmt = '**** [%(levelname)s]: %(message)s'

        logging.basicConfig(
                            level = logging.DEBUG,
                            format = logformat,
                            datefmt = dateformat,
                            filename = mylog,
                            filemode = 'a'
                           )

        console = logging.StreamHandler()
        console.setLevel(logging.INFO)
        formatter = logging.Formatter(cansolefmt)
        console.setFormatter(formatter)
        logging.getLogger('').addHandler(console)

        if mylev == 0:
            logging.debug(mymsg)
        if mylev == 1:
            logging.info(mymsg)
        if mylev == 2:
            logging.warning(mymsg)
        if mylev == 3:
            logging.error(mymsg)

        logging.getLogger('').removeHandler(console)

    if __name__ == '__main__':
        logfile = '/home/admin/test.log'
        log(logfile, 0, 'This is a test for debug!')
        log(logfile, 1, 'This is a test for info!')
        log(logfile, 2, 'This is a test for warning!')
        log(logfile, 3, 'This is a test for error!') logger.txt