python 日志模塊 logging
FileHandler:
以“a”(追加)的方式將日志輸出到文件,如果文件不存在,則自動(dòng)創(chuàng)建該文件。
StreamHandler:
將日志輸出到Stream,比如sys.stderr、sys.stdour、文件流等。
RotatingFileHandler:
將日志輸出到文件,可以通過(guò)設(shè)置文件大小,文件達(dá)到上限后自動(dòng)創(chuàng)建一個(gè)新的文件來(lái)繼續(xù)輸出文件。
class logging.handlers.RotatingFileHandler(filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=0)
參數(shù)maxBytes和backupCount允許日志文件在達(dá)到maxBytes時(shí)rollover.當(dāng)文件大小達(dá)到或者超過(guò)maxBytes時(shí),就會(huì)新創(chuàng)建一個(gè)日志文件。上述的這兩個(gè)參數(shù)任一一個(gè)為0時(shí),rollover都不會(huì)發(fā)生。也就是就文件沒(méi)有maxBytes限制。backupcount是備份數(shù)目,也就是最多能有多少個(gè)備份。命名會(huì)在日志的base_name后面加上.0-.n的后綴,如example.log.1,example.log.1,…,example.log.10。當(dāng)前使用的日志文件為base_name.log。
TimedRotatingFileHandler:
將日志輸出到文件,可以通過(guò)設(shè)置時(shí)間,使日志根據(jù)不同的時(shí)間自動(dòng)創(chuàng)建并輸出到不同的文件中。
class logging.handlers.TimedRotatingFileHandler(filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False)
參數(shù)when決定了時(shí)間間隔的類(lèi)型,參數(shù)interval決定了多少的時(shí)間間隔。如when=‘D’,interval=2,就是指兩天的時(shí)間間隔,backupCount決定了能留幾個(gè)日志文件。超過(guò)數(shù)量就會(huì)丟棄掉老的日志文件。
Example
class Log:
def __init__(
self,
logger_name=os.path.basename(
sys.argv[0])):
"""
By default module name is used as the logger name; if no output directory is provided, file_handler will not
be used.
:param logger_name:
:param log_dir:
"""
print('log init')
self.start_time = None
self.end_time = None
self.log_path = None
self.logger = logging.getLogger(logger_name)
self.logger.setLevel(logging.DEBUG)
self.formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s',
"%Y-%m-%d %H:%M:%S")
def set_print(self):
"""
decide whether to print log
設(shè)置日志是否打印
:return:
"""
self.stream_handler = logging.StreamHandler()
self.stream_handler.setLevel(logging.DEBUG)
self.stream_handler.setFormatter(self.formatter)
self.logger.addHandler(self.stream_handler)
def set_path(self, log_path):
"""
dicide whether to save log to path
設(shè)置日志是否保存到文件夾
:param log_path:
:return:
"""
self.log_path = log_path
if self.log_path is not None:
p = Path(self.log_path)
if not os.path.exists(str(p.parent)):
print(
"Creating logging directory {}".format(p.parent))
os.makedirs(str(p.parent))
# fname = datetime.strftime(datetime.now(), "%Y%m%d_%H:%M:%S")
# log_filename = os.path.join(log_dir, fname)
self.file_handler = logging.FileHandler(self.log_path)
self.file_handler.setLevel(logging.INFO)
self.file_handler.setFormatter(self.formatter)
self.logger.addHandler(self.file_handler)