我有views.py
日志的自定义配置,如下所示:
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
# Handlers
log_handlers = {
"terminal": logging.StreamHandler(),
"file_debug": logging.FileHandler("/var/log/eshot-api/{name}-{level}.log".format(name=__name__, level="DEBUG"), mode="w"),
"file_error": logging.FileHandler("/var/log/eshot-api/{name}-{level}.log".format(name=__name__, level="ERROR"), mode="w")
}
log_handlers["terminal"].setLevel(logging.INFO)
log_handlers["file_debug"].setLevel(logging.DEBUG)
log_handlers["file_error"].setLevel(logging.ERROR)
# Formatters
log_formatters = {
"terminal": logging.Formatter("[%(name)s]::[%(levelname)s]@[%(asctime)s]: %(message)s"),
"file_debug": logging.Formatter("[%(levelname)s]@[%(asctime)s]: %(message)s"),
"file_error": logging.Formatter("[%(asctime)s]: %(message)s")
}
for k, v in log_formatters.items():
log_handlers[k].setFormatter(v)
我创建了一个名为/var/log/eshot-api
的目录,并将chmod 777
的权限授予该目录,这样就不会出现编写问题。
我还创建了如下功能:
def initial_log(request, method):
logger.debug("{ip} requested {path} with {kwargs} in {method} method".format(ip=ipaddr(request), path=request.get_full_path(), kwargs=str(dict(request.GET)), method=method))
method
参数是一个要传递的字符串" GET"或" POST"这个功能。
我在get
的{{1}}函数的开头就把它放在了开头。但是,当我运行并刷新页面几次以生成一些日志并查看我的日志文件时,它们都是空的。
而且,我想提一下,这是我自己计算机中的开发服务器。
答案 0 :(得分:2)
检查您的settings.py是否有LOGGING = {...}
设置,并确保disable_existing_loggers
设置为False
:
LOGGING = {
...
'disable_existing_loggers': False,
..
}
或完全删除LOGGING设置。并将处理程序添加到记录器:
logger.addHandler(log_handlers["file_debug"])
我也喜欢advise you to configure LOGGING in your settings.py。
完整的工作示例
urls.py
:
from django.conf.urls import url
from .views import IndexView
urlpatterns = [
url(r'^$', IndexView.as_view()),
]
views.py
:
import logging
from django.http import HttpResponse
from django.views.generic import View
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
# Handlers
log_handlers = {
"terminal": logging.StreamHandler(),
"file_debug": logging.FileHandler("/var/log/eshot-api/{name}-{level}.log".format(name=__name__, level="DEBUG"), mode="w"),
"file_error": logging.FileHandler("/var/log/eshot-api/{name}-{level}.log".format(name=__name__, level="ERROR"), mode="w")
}
log_handlers["terminal"].setLevel(logging.INFO)
log_handlers["file_debug"].setLevel(logging.DEBUG)
log_handlers["file_error"].setLevel(logging.ERROR)
# Formatters
log_formatters = {
"terminal": logging.Formatter("[%(name)s]::[%(levelname)s]@[%(asctime)s]: %(message)s"),
"file_debug": logging.Formatter("[%(levelname)s]@[%(asctime)s]: %(message)s"),
"file_error": logging.Formatter("[%(asctime)s]: %(message)s")
}
for k, v in log_formatters.items():
log_handlers[k].setFormatter(v)
logger.addHandler(log_handlers['file_debug'])
class IndexView(View):
def get(self, request):
logger.debug("requested {path} with {kwargs} in method".format(path=request.get_full_path(), kwargs=str(dict(request.GET))))
return HttpResponse('app:index')
settings.py
LOGGING = {
'disable_existing_loggers': False,
}