Skip to content

Commit

Permalink
优化logging功能
Browse files Browse the repository at this point in the history
  • Loading branch information
alisen39 committed May 29, 2020
1 parent c04830b commit ade2eaa
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 40 deletions.
8 changes: 5 additions & 3 deletions backend/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,16 @@
BASE_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_PATH)

from backend.webInterface import tr_run
from backend.webInterface import tr_index
import tornado.web
import tornado.httpserver
import tornado.ioloop
from tornado.web import StaticFileHandler
from backend.tools.get_host_ip import host_ip
from backend.webInterface import tr_run
from backend.webInterface import tr_index
from backend.tools import log
import logging
logger = logging.getLogger(log.LOGGER_ROOT_NAME+'.'+__name__)

current_path = os.path.dirname(__file__)
settings = dict(
Expand All @@ -34,7 +37,6 @@ def make_app():


if __name__ == "__main__":
BASE_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

port = 8089
app = make_app()
Expand Down
36 changes: 36 additions & 0 deletions backend/tools/log.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
#!/usr/bin/env python
# encoding: utf-8
# author:alisen
# time: 2020/5/29 10:48

import logging
from logging.handlers import RotatingFileHandler
import os
import datetime

BASE_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

LOGGER_ROOT_NAME = 'TrWebOCRLog'
logger = logging.getLogger(LOGGER_ROOT_NAME)
logger.setLevel(logging.INFO)
# Formatter
formatter = logging.Formatter('%(asctime)s - %(name)s - [%(levelname)s] | %(message)s',
datefmt='%Y/%m/%d %H:%M:%S')

logfile_name = datetime.date.today().__format__('%Y-%m-%d.log')
logfile_path = os.path.join(BASE_PATH, f'logs/')
if not os.path.exists(logfile_path):
os.mkdir(logfile_path)

handler_logfile = RotatingFileHandler(logfile_path + logfile_name,
maxBytes=1 * 1024 * 1024,
backupCount=3)
handler_logfile.setLevel(logging.INFO)
handler_logfile.setFormatter(formatter)

console_output = logging.StreamHandler()
console_output.setLevel(logging.INFO)
console_output.setFormatter(formatter)

logger.addHandler(handler_logfile)
logger.addHandler(console_output)
46 changes: 9 additions & 37 deletions backend/webInterface/tr_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,52 +2,34 @@
# encoding: utf-8
# author:alisen
# time: 2020/4/29 10:47
# import json
import time

import time
import tr
import tornado.web
import tornado.gen
import tornado.httpserver

import base64
from PIL import Image, ImageDraw
from io import BytesIO
import datetime
import logging
from logging.handlers import RotatingFileHandler

import json
from backend.tools.np_encoder import NpEncoder
import os

BASE_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if not os.path.exists('./logs'):
os.mkdir('./logs')
from backend.tools.np_encoder import NpEncoder
from backend.tools import log
import logging

logger = logging.getLogger(__name__)
logger.setLevel(level=logging.INFO)
rHandler = RotatingFileHandler(os.path.join(BASE_PATH, 'logs/log.log'), maxBytes=1 * 1024 * 1024, backupCount=3)
rHandler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
rHandler.setFormatter(formatter)
console = logging.StreamHandler()
console.setLevel(logging.INFO)
console.setFormatter(formatter)
logger = logging.getLogger(log.LOGGER_ROOT_NAME + '.' +__name__)

logger.addHandler(rHandler)
logger.addHandler(console)


class TrRun(tornado.web.RequestHandler):
'''
使用 tr 的 run 方法
'''

# TODO 图片过大会爆内存而退出; 增大 swap 空间

def get(self):
self.write("Error Request")
self.set_status(404)
self.write("404 : Please use POST")

@tornado.gen.coroutine
def post(self):
Expand Down Expand Up @@ -94,7 +76,7 @@ def post(self):
img = img.rotate(90, expand=True)
except Exception as ex:
error_log = json.dumps({'code': 400, 'msg': '产生了一点错误,请检查日志', 'err': str(ex)}, cls=NpEncoder)
logger.error(error_log)
logger.error(error_log, exc_info=True)
self.finish(error_log)
return
img = img.convert("RGB")
Expand All @@ -109,6 +91,7 @@ def post(self):
try:
compress_size = int(compress_size)
except ValueError as ex:
logger.error(exc_info=True)
self.finish(json.dumps({'code': 400, 'msg': 'compress参数类型有误,只能是int类型'}, cls=NpEncoder))
return

Expand All @@ -117,16 +100,6 @@ def post(self):
else:
MAX_SIZE = compress_size

# elif :
# if compress_size < 1:
# self.finish(json.dump({'code': 400, 'msg': 'compress值不能小于0哦'}, cls=NpEncoder))
# return
# else:
# MAX_SIZE = compress_size
# else:
# self.finish(json.dumps({'code': 400, 'msg': 'compress参数类型有误,只能是int类型'}, cls=NpEncoder))
# return

if img.height > MAX_SIZE or img.width > MAX_SIZE:
scale = max(img.height / MAX_SIZE, img.width / MAX_SIZE)

Expand Down Expand Up @@ -157,7 +130,6 @@ def post(self):
'time': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
}
logger.info(json.dumps(log_info, cls=NpEncoder))

self.finish(json.dumps(
{'code': 200, 'msg': '成功',
'data': {'img_detected': 'data:image/jpeg;base64,' + img_detected_b64, 'raw_out': res,
Expand Down

0 comments on commit ade2eaa

Please sign in to comment.