Django 1.2尺度日志模块出现奇怪行为时的办理方案

打印 上一主题 下一主题

主题 836|帖子 836|积分 2508

在 Django 1.2 中,尺度日志模块偶然会出现意想不到的行为,比方日志消息未按预期记录、日志级别未正确应用或日志格式错乱等。这些标题可能源于日志设置不当、日志模块被多次初始化、或日志模块被其他包覆盖等原因。下面是一些常见标题的排查方法和办理方案。

1、标题配景
在 Django 1.2 中,使用尺度日志模块记录信息时碰到了一个奇怪的标题。偶然候它可以正常工作,而偶然候它却无法记录信息。
2、办理方案
为了办理这个标题,我们采取了以下步调:

  • 首先,我们查抄了代码结构。代码结构如下:
  1. /mysite/ (Django root)
  2.     my_logging.py (logging configuration)
  3.     settings.py
  4.     views.py (global views)
  5.     data_objects.py (objects only containing data, similar to POJO)
  6.     uploader/ (application)
  7.         views.py (uploader views) --> This is where I have problems
复制代码

  • 接着,我们查抄了 my_logging.py 的代码:
  1. import logging
  2. import logging.handlers
  3. from django.conf import settings
  4. is_initialized = False
  5. def init_logger():
  6.     """
  7.     Initializes the logging for the application. Configure the root
  8.     logger and creates the handlers following the settings. This function should
  9.     not be used directly from outside the module and called only once.
  10.     """
  11.     # Create the logger
  12.     server_logger = logging.getLogger()
  13.     server_logger.setLevel(logging.DEBUG)
  14.      # Set the logging format for files
  15.     files_formatter = logging.Formatter(settings.LOGGING_FORMAT_FILE)
  16.      # Rotating file handler for errors
  17.     error_handler = logging.handlers.RotatingFileHandler(
  18.         settings.LOGGING_ERROR_FILE,
  19.         maxBytes=settings.LOGGING_ERROR_FILE_SIZE,
  20.         backupCount=settings.LOGGING_ERROR_FILE_COUNT,
  21.     )
  22.     error_handler.setLevel(logging.WARNING)
  23.     error_handler.setFormatter(files_formatter)
  24.     # Rotating file handler for info
  25.     info_handler = logging.handlers.RotatingFileHandler(
  26.         settings.LOGGING_INFO_FILE,
  27.         maxBytes=settings.LOGGING_INFO_FILE_SIZE,
  28.         backupCount=settings.LOGGING_INFO_FILE_COUNT,
  29.     )
  30.     info_handler.setLevel(logging.INFO)
  31.     info_handler.setFormatter(files_formatter)
  32.     # Add the handlers to the logger
  33.     server_logger.addHandler(info_handler)
  34.     server_logger.addHandler(error_handler)
  35. # Init once at first import
  36. if not is_initialized:
  37.     init_logger()
  38.     is_initialized = True
复制代码

  • 然后,我们查抄了 uploader/views.py 中的部分代码:
  1. #...
  2. import mysite.my_logging
  3. import logging
  4. #...
  5. # The messages in the following view are written correctly :
  6. @login_required
  7. def delete(request, file_id):
  8.     """
  9.     Delete the file corresponding to the given ID and confirm the deletion to
  10.     the user.
  11.     @param request: the HTTP request object
  12.     @type request: django.http.HttpRequest
  13.     @return: django.http.HttpResponse - the response to the client (html)
  14.     """
  15.     # Get the file object form the database and raise a 404 if not found
  16.     f = get_object_or_404(VideoFile, pk=file_id)
  17.     # TODO: check if the deletion is successful
  18.     # Get the video directory
  19.     dir_path = os.path.dirname(f.file.path)
  20.     # Delete the file
  21.     f.delete()
  22.     try:
  23.         # Delete the video directory recursively
  24.         shutil.rmtree(dir_path)
  25.         logging.info("File "%(file)s" and its directory have been deleted by %(username)s",{'file': f.title,'username': request.user.username})
  26.         messages.success(request, _('The video file "%s" has been successfully deleted.') % f.title)
  27.     except OSError:
  28.         logging.warning("File "%(id)d" directory cannot be completely deleted. Some files may still be there.",{'id': f.id,})
  29.         messages.warning(request, _("The video file "%s" has been successfully deleted, but not its directory. There should not be any problem but useless disk usage.") % f.title)
  30.     return HttpResponseRedirect(reverse('mysite.uploader.views.list'))
  31. #...
  32. # The messages in the following view are NOT written at all:
  33. @csrf_exempt
  34. def get_thumblist(request,file_id):
  35.     """
  36.     This view can be called only by POST and with the id of a video
  37.     file ready for the scene editor.
  38.     @param request: the HTTP request object. Must have POST as method.
  39.     @type request: django.http.HttpRequest
  40.     @return: django.http.HttpResponse - the response to the client (json)
  41.     """
  42.     #TODO: Security, TEST
  43.     logging.info("Demand of metadata for file %(id)d received.",{'id': file_id,})
  44.     if request.method == 'POST':
  45.         if file_id:
  46.             # Get the video file object form the database and raise a 404 if not found
  47.             vid = get_object_or_404(VideoFile, pk=file_id)
  48.                 # ...
  49.                 try:
  50.                     # ... file operations
  51.                 except IOError:
  52.                     logging.error("Error when trying to read index file for file %(id)d !",{'id': file_id,})
  53.                 except TypeError:
  54.                     logging.error("Error when trying to parse index file JSON for file %(id)d !",{'id': file_id,})
  55.                 # ...
  56.                 logging.info("Returning metadata for file %(id)d.",{'id': file_id,})
  57.                 return HttpResponse(json,content_type="application/json")
  58.             else:
  59.                 logging.warning("File %(id)d is not ready",{'id': file_id,})
  60.                 return HttpResponseBadRequest('file_not_ready')
  61.         else:
  62.             logging.warning("bad POST parameters")
  63.             return HttpResponseBadRequest('bad_parameters')
  64.     else:
  65.         logging.warning("The GET method is not allowed")
  66.         return HttpResponseNotAllowed(['POST'])
复制代码

  • 最后,我们查抄了 settings.py 中的部分代码:
  1. # ---------------------------------------
  2. # Logging settings
  3. # ---------------------------------------
  4. #: Minimum level for logging messages. If logging.NOTSET, logging is disabled
  5. LOGGING_MIN_LEVEL = logging.DEBUG
  6. #: Error logging file path. Can be relative to the root of the project or absolute.
  7. LOGGING_ERROR_FILE = os.path.join(DIRNAME,"log/error.log")
  8. #: Size (in bytes) of the error files
  9. LOGGING_ERROR_FILE_SIZE = 10485760 # 10 MiB
  10. #: Number of backup error logging files
  11. LOGGING_ERROR_FILE_COUNT = 5
  12. #: Info logging file path. Can be relative to the root of the project or absolute.
  13. LOGGING_INFO_FILE = os.path.join(DIRNAME,"log/info.log")
  14. #: Size (in bytes) of the info files
  15. LOGGING_INFO_FILE_SIZE = 10485760 # 10 MiB
  16. #: Number of backup error info files
  17. LOGGING_INFO_FILE_COUNT = 5
  18. #: Format for the log files
  19. LOGGING_FORMAT_FILE = "%(asctime)s:%(name)s:%(levelname)s:%(message)s"
复制代码

  • 通过对以上代码的查抄,我们发现标题出现在 uploader/views.py 中的 get_thumblist 函数中。该函数中使用 logging.info('Demand of metadata for file %(id)d received.') 语句记录信息,但由于没有使用 logger 对象,导致信息没有被记录下来。
  • 为了办理这个标题,我们将 get_thumblist 函数中的 logging.info('Demand of metadata for file %(id)d received.') 语句改为 logger.info('Demand of metadata for file %(id)d received.'),此中 logger 是一个 logging.getLogger() 函数返回的日志对象。
  • 修改后的代码如下:
  1. #...
  2. import mysite.my_logging
  3. import logging
  4. logger = logging.getLogger('MySite.views')
  5. #...
  6. # The messages in the following view are written correctly :
  7. @login_required
  8. def delete(request, file_id):
  9.     """
  10.     Delete the file corresponding to the given ID and confirm the deletion to
  11.     the user.
  12.     @param request: the HTTP request object
  13.     @type request: django.http.HttpRequest
  14.     @return: django.http.HttpResponse - the response to the client (html)
  15.     """
  16.     # Get the file object form the database and raise a 404 if not found
  17.     f = get_object_or_404(VideoFile, pk=file_id)
  18.     # TODO: check if the deletion is successful
  19.     # Get the video directory
  20.     dir_path = os.path.dirname(f.file
复制代码
以上方法可以资助办理 Django 1.2 中尺度日志模块的异常行为标题。通过公道设置和调整日志模块,可以确保日志记录功能稳固、可靠地运行。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

魏晓东

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表