python之logging

1.简单使用

# CRITICAL, ERROR, WARNING, INFO, DEBUG)     cewid
import logging
logging.basicConfig(level=logging.DEBUG)  #filename='log_debug.txt',    console和文件输出二选一。。。
logger = logging.getLogger('%s %s'%(os.path.split(__file__)[1], __name__))  #脚本文件名字
    # 放在类里面
    # logger = logging.getLogger(__name__)
    # 放在类的函数里面
    # ##self.logger = logging.getLogger(self.__class__.__name__)
    # self.logger.debug('xxx')
# 放在函数内部
logger.debug('%s: %s'%(sys._getframe().f_code.co_name, 'abcde'))  #函数名字

2.console输出并保存到文件

(1)参考

python logging 日志输出 学习笔记 时间格式化

python标准日志模块logging的使用方法

第二个链接还没好好利用!

(2)更新代码


import logging
def print_save_log(logFilename):  
    ''''' Output log to file and console '''  
    # Define a Handler and set a format which output to file  
    logging.basicConfig(  
                    level    = logging.DEBUG,                                                             
                    format   = '%(asctime)s  %(filename)s : %(levelname)s  %(message)s', 
                    # 默认 2017-08-02 12:35:38,956
                    # 设置 2017-08-02 Wednesday 12:36:26
                    datefmt  = '%Y-%m-%d %A %H:%M:%S', 
                    filename = logFilename,              
                    filemode = 'a')
                    
    # Define a Handler and set a format which output to console  
    console = logging.StreamHandler()
    console.setLevel(logging.INFO)   #可以与记录文件不同级别
    formatter = logging.Formatter('%(asctime)s  %(filename)s : %(levelname)s  %(message)s')
    console.setFormatter(formatter) 
    
    # Create an instance 
    logger = logging.getLogger()
    logger.addHandler(console)   # 实例化添加handler  
    return logger

    
logger = print_save_log('logging.log')  
logger.debug('logger debug message')       
logger.info('logger info message')  
logger.warning('logger warning message')  
logger.error('logger error message')  
logger.critical('logger critical message')     

3. cookielib.py

debug = True # set to True to enable debugging via the logging module
logger = None

def _debug(*args):
    if not debug:
        return
    global logger
    if not logger:
        import logging
        logger = logging.getLogger("cookielib")
    return logger.debug(*args)   #实际只支持单个参数?!
原文地址:https://www.cnblogs.com/my8100/p/7273315.html