【Flask项目2】多进程下的日志文件(2)
生活随笔
收集整理的這篇文章主要介紹了
【Flask项目2】多进程下的日志文件(2)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
comment—utils—financial_logging.py
import logging import logging.handlers from flask import request import os''' 定義日志的格式和日志輸出的目標 ''' class RequestShoppingFormatter(logging.Formatter):'''自定義的日志輸出格式'''def format(self, record):record.url=request.url #需要在日志中記錄請求地址record.remote_addr=request.remote_addr #需要在日志中記錄客戶端的地址return super().format(record)#創建一個個性化的logger對象 def create_logger(app):'''設置日志的配置:param app:Flask中app對象:return:'''logging_file_dir=app.config['LOGGING_FILE_DIR'] #日志文件所在的目錄logging_file_max_bytes=app.config['LOGGING_FILE_MAX_BYTES'] #日志文件的最大的大小logging_file_backup=app.config['LOGGING_FILE_BACKUP'] #保留備份的日志文件個數logging_level=app.config['LOGGING_LEVEL'] #默認的日志級別#設置日志輸出的格式(針對文件)request_formatter=RequestShoppingFormatter('[%(asctime)s] %(remote_addr)s 請求 %(url)s \t %(levelname)s 在 %(module)s %(lineno)d : %(message)s')#檢查如果目錄不存在,則創建目錄if os.path.isdir(logging_file_dir):passelse:os.mkdir(logging_file_dir) #如果目錄不存在,創建目錄#自定義一個目錄和日志文件,RotatingFileHandler:安裝指定文件大小來規定日志文件的生產規則# flask_file_handler=logging.handlers.RotatingFileHandler(filename=os.path.join(logging_file_dir,'financial.log'),# maxBytes=logging_file_max_bytes,# backupCount=logging_file_backup)#為了讓一個進程操作一個文件,文件名的命名:加上當前進程的ID#TimedRotatingFileHandler:根據時間來規定日志文件的生成規則。flask_file_handler = logging.handlers.TimedRotatingFileHandler(filename=os.path.join(logging_file_dir, 'financial'+'_'+str(os.getpid())+'.log'),when='D',interval=1,backupCount=logging_file_backup)#給當前的handler設置格式flask_file_handler.setFormatter(request_formatter)#todo 得到一個logger對象,根據包(financial)的名字,用其他的包名不符合邏輯flask_logger=logging.getLogger('financial')flask_logger.addHandler(flask_file_handler)flask_logger.setLevel(logging_level)#整個項目需要兩個handle:文件。控制臺flask_console_handler=logging.StreamHandler()flask_console_handler.setFormatter(logging.Formatter('[%(asctime)s] %(levelname)s %(module)s %(lineno)d : %(message)s'))#當項目運行環境是debug模式,才用控制臺輸出if app.debug:flask_logger.addHandler(flask_console_handler)main.py中初始化日志處理的工具
from comment.utils.financial_logging import create_loggercreate_logger(app)總結
以上是生活随笔為你收集整理的【Flask项目2】多进程下的日志文件(2)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Flask项目2】项目基本架构配置(1
- 下一篇: unittest单元测试框架—基本实例