开发代码避免不了错误,为了方便查找错误,我们可以利用完整的日志模块来记录错误。
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File : user_log.py
@Time : 2019/06/27 12:27:08
@Author : Crisimple
@Version : 1.0
@Contact : Crisimple@foxmail.com
@License : (C)Copyright 2016-2019, Micro-Circle
@Desc : 控制台输出日志
'''
# here put the import lib
import logging
import os
from datetime import datetime
class UserLog(object):
def __init__(self):
self.logger = logging.getLogger()
self.logger.setLevel(logging.DEBUG)
# # Console Output
# console = logging.StreamHandler()
# # put console stream to logger
# logger.addHandler(console)
# logger.debug("test logging")
# # Finish operator, close console
# console.close()
# # Close console stream to logger
# logger.removeHandler(console)
# Get current file is abspath path
base_dir = os.path.dirname(os.path.abspath(__file__))
print(base_dir)
log_dir = os.path.join(base_dir, 'logs')
log_file = datetime.now().strftime("%Y - %m - %d") + '.log'
log_file_name = log_dir + "/" + log_file
print(log_file_name)
# Write log to file
self.file_handle = logging.FileHandler(log_file_name, 'a', encoding='utf-8')
# Custom file format
formatter = logging.Formatter('%(asctime)s %(filename)s %(funcName)s %(levelno)s: [%(levelname)s] ---> %(message)s')
self.file_handle.setFormatter(formatter)
self.logger.addHandler(self.file_handle)
# self.logger.debug(u"写入user_log.log文件的内容")
def get_log(self):
return self.logger
def close_handle(self):
self.logger.removeHandler(self.file_handle)
self.file_handle.close()
if __name__ == "__main__":
user_logger = UserLog()
log = user_logger.get_log()
log.debug("test......")
user_logger.close_handle()