zoukankan      html  css  js  c++  java
  • logging 模块

    import logging
      
      
    logging.basicConfig(filename='log.log',
                        format='%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S %p',
                        level=logging.WARNING)
      
    logging.debug('debug')
    logging.info('info')
    logging.warning('warning')
    logging.error('error')
    logging.critical('critical')
    logging.log(10,'log')
    

    日志等级:

    CRITICAL = 50
    FATAL = CRITICAL
    ERROR = 40
    WARNING = 30
    WARN = WARNING
    INFO = 20
    DEBUG = 10
    NOTSET = 0

    Logger.exception(msg[, *args]) 

    以ERROR级别记录日志消息,异常跟踪信息将被自动添加到日志消息里。Logger.exception通过用在异常处理块中,如:

    复制代码
    import logging
    import os
    logging.basicConfig(format="%(levelname)s,%(message)s",filename=os.path.join(os.getcwd(),'log.txt'),level=logging.DEBUG)
    log = logging.getLogger('root')   #Logger对象
    try:
        raise Exception,u'错误异常'
    except:
        log.exception('exception')  #异常信息被自动添加到日志消息中  
    打开文件,显示如下:
    '''ERROR,exception Traceback (most recent call last): File "E:projectpysrclog3.py", line 12, in <module> raise Exception,u'错误异常' Exception: 错误异常 '''

     

    例: 自定义错误类型并利用 logging 记录登录成功失败信息

    import logging
    from datetime import datetime
    
    '''
    try:
        pass
    except 自定义错误类:
        logging.exception()
    
    '''
    
    
    logging.basicConfig(filename='log.log',
                        format='%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S %p',
                        level=logging.INFO)
    
    #自定义错误类
    class login_sucess(Exception):
        pass
    
    class login_fail(Exception):
        pass
    
    
    
    def login():
        username = input('please input username:')
        passwd = input('please input passwd:')
        if username == 'yang' and passwd == '123':
            try:
                #主动抛出异常
                raise login_sucess('login sucess username: %s  time:%s'% (username, datetime.now()))
            #利用 logging 记录日志  
            except Exception as e:
                logging.info(e)
            finally:
                print('welcome back!')
        else:
            try:
                raise login_sucess('login fail username: %s  time:%s' % (username, datetime.now()))
            except Exception as e:
                logging.error(e)
            finally:
                print('username or passwd is fail!')
    
    
    if __name__ == '__main__':
        login()
    

      

  • 相关阅读:
    Eclipse中的快捷键
    xml文件头文件生成策略以及导入约束条件
    HTTP协议状态代码和错误状态含义的解释
    水了一个前端面试 记下问的东西
    整理的一些PHP面试题目
    Magic Index 寻找数组中A[i]=i的位置(原题转自微信号待字闺中)
    【经典算法】寻找最长01字串(转自待字闺中)
    PHP中不用第三个变量交换两个变量的值
    已知一个数组a[N]来构造数组b[N]的有趣算法题
    MySQL安装后默认自带数据库的作用
  • 原文地址:https://www.cnblogs.com/yangxiaolan/p/5651977.html
Copyright © 2011-2022 走看看