How to maintain logs in Falcon

旧巷老猫 提交于 2019-12-23 21:59:35

问题


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.


回答1:


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.

Let take this as the example:

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.




回答2:


There's nothing specifically built-in from Falcon on that regard. Actually that is what make it different from other frameworks; with Falcon you are free to use any library you wish.

For most of my projects, the standard python module logging is good enough.



来源:https://stackoverflow.com/questions/39718868/how-to-maintain-logs-in-falcon

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!