N.Singh
N.Singh

Reputation: 55

python/django logging with decorators

I want to place a decorator on every function to log everything happening in the function. i have made a wrapper function and decorator to log the function with decorator.

views.py

def func_detail(func):
   @wraps(func)
     def func_wrapper(*args, **kwargs):
         r = func(*args, **kwargs)
         logging.getLogger(__name__)
         logging.basicConfig(filename='test.log', filemode='a',
                             format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
                              datefmt='%H:%M:%S',
                              level=logging.DEBUG)
         return r
     return func_wrapper

class UsersViewSet(viewsets.ViewSet):
    @func_detail
    def list(self, request):
        queryset = Mytable.objects.all()
        if request.GET.get('name'):
            queryset = queryset.filter(name=request.GET.get('name'))
        serializer = CheckSerializer(queryset, many=True)
        logging.info("GET request and returned response")
        return Response(serializer.data)

The problem is log file is not created in this code. Also, it got created on a different project but didnot print anything in log file(empty log file). I want to print a message in log file for everything that is happening, but this doesn't seem to work. Plz help.

Upvotes: 2

Views: 1803

Answers (1)

Raja Simon
Raja Simon

Reputation: 10315

The decorator inner function should return outer function with args and kwargs and your decorator problem will solve but another problem is Django can't able to stdr the console output of this decorated view function.

def func_detail(func):
    @wraps(func)
    def func_wrapper(*args, **kwargs):
        logging.getLogger(__name__)
        ----
        return func(*args, **kwargs)
    return func_wrapper

Upvotes: 3

Related Questions