程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

python--log processing logging.handlers.TimedRotatingFileHandler

編輯:Python

文章目錄

  • 一、日志模塊
  • 二、生成日志腳本
  • 三、Generate log ideas


一、日志模塊

使用模塊之前,先進行導入

import logging

during development,The log files are needed to help us locate the problem,This requires a good distinction between the daily logs,TimedRotatingFileHandler The class can implement daily log file updates.

TimedRotatingFileHandler 類位於 logging.handlers 模塊,It supports disk log file rotation based on specific time intervals,need to be imported before use

from logging.handlers import TimedRotatingFileHandler

二、生成日志腳本

代碼如下(示例):

import os
import logging
from logging.handlers import TimedRotatingFileHandler
import time
log_path = "logs"
def get_logger(name):
logger = logging.getLogger(name)
#判斷目錄是否存在,存在不創建,不存在則創建log目錄
if os.path.exists(log_path):
pass
else:
os.mkdir(log_path)
# Set the log base level
logger.setLevel(logging.DEBUG)
# 日志格式
formatter = '[%(asctime)s] [%(threadName)s] [line:%(lineno)d] %(levelname)s: %(message)s'
log_formatter = logging.Formatter(formatter)
# 控制台日志
console_handler = logging.StreamHandler()
console_handler.setFormatter(log_formatter)
# info日志文件名
info_file_name = 'info-' + time.strftime(
'%Y-%m-%d', time.localtime(time.time())) + '.log'
"""
#實例化TimedRotatingFileHandler
# filename:日志文件名
# when:Log files are divided by what.'S'-秒;'M'-分鐘;'H'-小時;'D'-天;'W'-周
# 這裡需要注意,如果選擇 D-天,那麼這個不是嚴格意義上的'天',是從你
# 項目啟動開始,過了24小時,A new log file will be recreated,如果項目重啟,
# 這個時間就會重置.選擇'MIDNIGHT'-It means it's past the morning12點,就會創建新的日志
# interval是時間間隔
# backupCount:是保留日志個數.默認的0是不會自動刪除掉日志.如果超過這個個數,就會自動刪除 
"""
info_handler = TimedRotatingFileHandler(filename='logs/' +
info_file_name,
when='MIDNIGHT',
interval=1,
backupCount=3,
encoding='utf-8')
# 設置文件裡寫入的格式
info_handler.setFormatter(log_formatter)
info_handler.setLevel(logging.INFO)
# 添加日志處理器
logger.addHandler(info_handler)
logger.addHandler(console_handler)
return logger
get_logger(name="test")

三、Generate log ideas

1、Set the storage log directory,不存在則創建目錄
2、設置日志的級別'DEBUG','INFO', 'WARNING','ERROR','CRITICAL'
3、Sets the format for writing the log '[%(asctime)s] [%(threadName)s] [line:%(lineno)d] %(levelname)s: %(message)s'
4、設置控制台輸出
5、設置日志文件名
6、Make sure to generate different log files daily,And can distinguish the log generation time,可用logging.handlers.TimedRotatingFileHandler進行處理,使用之前先進行導入
7、Add the log object to logger裡
8、進行調用即可 get_logger(name="test")

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved