How to maintain logs in Falcon

2019-07-17 01:42发布

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.

2条回答
唯我独甜
2楼-- · 2019-07-17 02:17

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.

查看更多
Deceive 欺骗
3楼-- · 2019-07-17 02:24

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.

查看更多
登录 后发表回答