简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM