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通过用在异常处理块中,如:

logging 模块-LMLPHP
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:\project\py\src\log3.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()

  

05-11 16:59