gpt4 book ai didi

python - 如何在 Falcon 中维护日志

转载 作者:行者123 更新时间:2023-11-28 22:33:39 24 4
gpt4 key购买 nike

我正在使用 Python3.4 和 Falcon1.0.0,并使用 apache2 为我的 falcon 应用程序提供服务。现在,我想在我的 falcon 应用程序中维护日志。

最佳答案

您可以使用以下方式,即将以下功能存储在文件“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))

希望对您有所帮助。

关于python - 如何在 Falcon 中维护日志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39718868/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com