flask带日志的微服务封装

flask的具体实例用法

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
# @Time    : 2020-05-18 16:11:10
# @Author  : Bakuya Liu
# @File    : getCourtInformation_flask.py

Description:

"""
from flask import Flask, render_template, request, Response, jsonify
from flask_cors import CORS
from flask import request
import datetime
import time
import pytz
import os
import sys
import json
sys.path.append("/home/release/court_nlp_release/courtInformationExtractor")
from service.getInfoCombination import getCombination
import logging
from logging.handlers import RotatingFileHandler
import warnings


warnings.filterwarnings("ignore")
app = Flask(__name__)
CORS(app, supports_credentials=True)

@app.before_request
def before_request():
    # import face_interface
    ip = request.remote_addr
    url = request.url
    app.logger.info('ip: %s, url: %s user is accessing!', ip, url)

@app.route('/CourtInformation',methods=["get"])
def getCourtInformation():
    try:
        data = json.loads(request.get_data())
        print("1")
        result = getCombination(data)
        file = "./log_CourtInformation.txt"
        # 鍒ゆ柇鏂囦欢鏄惁瀛樺湪锛屼笉瀛樺湪鍒欏垱寤?
        if not os.path.exists(file):
            os.mknod(file)
        with open(r'./log_CourtInformation.txt', 'a+') as f_log:
            now_time = datetime.datetime.fromtimestamp(int(time.time()), pytz.timezone('Asia/Shanghai')).strftime('%Y-%m-%d %H:%M:%S')
            data = now_time + ',' + 'getCourtInformation' + ',' + 'running success.\n'
            f_log.writelines(data)
        app.logger.info('The algorithm called successfully!')
        return jsonify(result)
    except Exception as e:
        logging.exception(e)
        raise

# 鍙戦€佺姸鎬?
@app.route('/heartbeat', methods=['POST'])
def heartbeat():
    try:
        PID = os.getpid()
        with open('./data.json', encoding='utf-8', errors='ignore') as f:
            data = json.load(f)
        result = getCombination(data)
        if len(result) != 0:
            algorithm_status = 'running'
        else:
            algorithm_status = 'stopped'

        if not os.path.exists('./log_CourtInformation.txt'):
            return "The algorithm has not been called!"
        with open('./log_CourtInformation.txt', 'r') as f:
            lines = f.readlines()
            last_line = lines[-1].split(',')
            last_call_time = last_line[0]
            name = last_line[1]
            call_count = len(lines)

        response = {
            "response_getCourtInformation":{
                'name': name,
                'status': algorithm_status,
                'call_count': call_count,
                'last_call_time': last_call_time,
                'pid': PID
            }
        }
        return jsonify(response)
    except Exception as e:
        logging.exception(e)
        return ''


if __name__ == '__main__':
    # 鐢熸垚鏃ュ織鏂囦欢
    app.debug = True
    logging.basicConfig(level=logging.DEBUG)
    formatter = logging.Formatter(
        "[%(asctime)s][%(filename)s:%(lineno)d][%(levelname)s][%(thread)d] - %(message)s")
    handler = RotatingFileHandler("flask.log", maxBytes=102400, backupCount=10)
    logging.getLogger().addHandler(handler)
    handler.setFormatter(formatter)
    app.run(host='0.0.0.0', port=5000, debug=True)

上一篇:logging模块(日志配置)


下一篇:python的log模块