2016-09-27 51 views
1

我正在使用Python3.4和Falcon1.0.0,并且正在使用apache2为我的猎鹰应用程序提供服务。现在,我想在我的猎鹰应用程序中保留日志。如何在Falcon中维护日志

回答

3

您可以使用下面的方法,即商店按照文件“logger.py”功能:那么现在,每当你想记录什么,就调用这个函数存在并记录任何你想登录

import logging 
import logging.handlers 
import os 
from datetime import datetime 
import sys 

# Logging Levels 
# https://docs.python.org/3/library/logging.html#logging-levels 
# CRITICAL 50 
# ERROR 40 
# WARNING 30 
# INFO 20 
# DEBUG 10 
# NOTSET 0 


def set_up_logging(): 
    file_path = sys.modules[__name__].__file__ 
    project_path = os.path.dirname(os.path.dirname(os.path.dirname(file_path))) 
    log_location = project_path + '/logs/' 
    if not os.path.exists(log_location): 
     os.makedirs(log_location) 

    current_time = datetime.now() 
    current_date = current_time.strftime("%Y-%m-%d") 
    file_name = current_date + '.log' 
    file_location = log_location + file_name 
    with open(file_location, 'a+'): 
     pass 

    logger = logging.getLogger(__name__) 
    format = '[%(asctime)s] [%(levelname)s] [%(message)s] [--> %(pathname)s [%(process)d]:]' 
    # To store in file 
    logging.basicConfig(format=format, filemode='a+', filename=file_location, level=logging.DEBUG) 
    # To print only 
    # logging.basicConfig(format=format, level=logging.DEBUG) 
    return logger 

让我们以此为例子:

import falcon 
import base64 
import json 
from logger import set_up_logging 
logger = set_up_logging() 

app = falcon.API() 
app.add_route("/rec/", GetImage()) 

class GetImage: 

    def on_post(self, req, res): 

     json_data = json.loads(req.stream.read().decode('utf8')) 
     image_url = json_data['image_name'] 
     base64encoded_image = json_data['image_data'] 
     with open(image_url, "wb") as fh: 
      fh.write(base64.b64decode(base64encoded_image)) 

     res.status = falcon.HTTP_203 
     res.body = json.dumps({'status': 1, 'message': 'success'}) 
     logger.info("Image Server with image name : {}".format(image_name)) 

我希望这会帮助你。

0

Falcon在这方面没有特别的内置。其实这就是与其他框架不同的地方;与猎鹰你可以自由地使用任何你想要的图书馆。

对于我的大部分项目来说,标准的python模块logging已经足够好了。

+1

但是在哪里把代码存储日志?例如。如果我的代码在on_get()方法中断,如何为其存储日志。 – pikkupr