Accessing the API logger in Flask-Restful's resources

I know the answer has been chosen already, but there is a slightly different approach that also works.

First, import

from flask import current_app as app

in the resource file, and when calling the logger, do:

app.logger.info("This is an info message")


You need to define constructor of Resource. Here an example:

import logging


class SomeEndpoint(Resource):

    def __init__(self, **kwargs):
        self.logger = kwargs.get('logger')

    def get(self):
        # self.logger - 'logger' from resource_class_kwargs
        return self.logger.name  

api.add_resource(SomeEndpoint, '/', resource_class_kwargs={
    # any logger here...
    'logger': logging.getLogger('my_custom_logger')
})

Open your endpoint. You will see my_custom_logger. Hope this helps.

Tags:

Python

Rest

Flask