简体   繁体   English

用装饰器记录python / django

[英]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 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. 装饰器内部函数应返回带有args和kwargs的外部函数,您的装饰器问题将解决,但另一个问题是Django无法stdr此装饰视图函数的控制台输出。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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