人生苦短,我用python。
一、logging模块
1、基本使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
logging.basicConfig(level=logging.DEBUG, format='%(asctime)s- %(filename)s(%(lineno)d)- %(levelname)s- %(message)s')
logger = logging.getLogger(name=__name__)
logger.debug('DEBUG log') logger.info('INFO log') logger.warning('WARNING log') logger.error('ERROR log') logger.critical('CRITICAL log')
|
2、将日志写入到文件和输出到屏幕
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
|
logger = logging.getLogger() logger.setLevel(logging.DEBUG)
file_handler = logging.FileHandler(r'E:\test.log', 'a', encoding='utf-8') file_handler.setLevel(logging.INFO) file_handler.setFormatter(logging.Formatter('%(asctime)s - %(filename)s(%(lineno)d) - %(levelname)s - %(message)s'))
console_handler = logging.StreamHandler() console_handler.setLevel(logging.INFO) console_handler.setFormatter(logging.Formatter('%(asctime)s - %(filename)s(%(lineno)d) - %(levelname)s - %(message)s'))
rollback_handler = RotatingFileHandler(r'E:\rollback.log', maxBytes = 1*1024, backupCount=3) rollback_handler.setLevel(logging.INFO) rollback_handler.setFormatter(logging.Formatter('%(asctime)s - %(filename)s(%(lineno)d) - %(levelname)s - %(message)s'))
logger.addHandler(file_handler) logger.addHandler(console_handler) logger.addHandler(rollback_handler)
try: open(r'E:\NoSuchFile.txt','r') except (SystemExit, KeyboardInterrupt): raise except Exception: logger.error("Faild to open NoSuchFile.txt from logger.error", exc_info = True)
logger.debug('DEBUG log') logger.info('INFO log') logger.warning('WARNING log') logger.error('ERROR log') logger.critical('CRITICAL log')
|
3、利用互斥锁保证将项目日志保存到同一个日志文件中共享数据操作的完整性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| class Log: pass class MyLog: """单独启用线程写入日志信息"""
log = None mutex = threading.Lock()
@staticmethod def mylog(): """ 利用互斥锁来保证共享数据操作的完整性 :return: 日志logger """ if MyLog.log is None: MyLog.mutex.acquire() MyLog.log = Log() MyLog.mutex.release() return MyLog.log.logger
|
持续更新…