Skip to content Skip to sidebar Skip to footer

How To Maintain Logs In 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.

Solution 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    0defset_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/'ifnot 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
    withopen(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())

classGetImage:

    defon_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']
        withopen(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.

Solution 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.

Post a Comment for "How To Maintain Logs In Falcon"