如何维护猎鹰中的日志 [英] How to maintain logs in Falcon

查看:91
本文介绍了如何维护猎鹰中的日志的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using Python3.4 and Falcon1.0.0 and I'm serving my falcon application using apache2. Now, I want to maintain logs in my falcon application.

推荐答案

您可以使用以下方式,即将以下函数存储在文件"logger.py"中:

You can use following way, i.e. Store following function in file "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

因此,现在无论何时要记录任何内容,只需在此调用此函数并记录任何要记录的内容即可.

So now whenever you want to log anything, just call this function there and log whatever you want to log.

以这个为例:

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))

我希望这会对您有所帮助.

I hope this will help you.

这篇关于如何维护猎鹰中的日志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆