跳转到: 导航, 搜索

增强上下文日志记录器

蓝图设计 for (增强上下文日志记录器)

问题陈述

目前,日志记录器没有提供任何机制让驱动程序或消费者添加除了已经内置到日志记录器中的额外上下文信息,例如 instanceId。该蓝图将为日志记录器添加灵活性,以便如果需要,日志记录器的使用者可以添加一些上下文数据,这些数据随后可以在日志中显示,而无需更改代码中的单个日志语句。

建议设计

想法是引入一个用于子上下文信息的占位符。逻辑将基于此占位符的存在而运行。在此过程中将要增强的类是 openstack.common.log.ContextAdapteropenstack.common.log.ContextFormatter

建议对 ContextAdapter 的修改

在“extra”中添加一个名为“sub_context”的占位符,如果找到,则将其展开到“extra”中,如下所示

       extra.update({"version": self.version})
       if extra.get('sub_context', None):
           sub_context = extra.get('sub_context', None)
           for k in sub_context:
               extra.update({k:sub_context[k]})
       extra['extra'] = extra.copy()


建议对 ContextFormatter 的修改

       self._fmt += " " + CONF.logging_debug_format_suffix
       if record.__dict__.get('sub_context', None):
           sub_context = record.__dict__.get('sub_context', None)
           for k in sub_context:
               self._fmt += " [" + k + ":%(" + k + ")s]"


此增强型日志记录器的建议用法

在驱动程序代码中,可以根据要添加到日志记录器中的信息,在适当的位置添加以下内容

   def _enhance_context(self, func):
       "This decorator enhances the context with a module specific contextual information"
       argnames = func.func_code.co_varnames[:func.func_code.co_argcount]
   
       def enhance_process(*args,**kwargs):
           if 'kwargs' in argnames:
               pkwargs = args[argnames.index('kwargs')]
               if 'extra' not in pkwargs:
                   pkwargs['extra'] = {}
               extra = pkwargs['extra']
               if 'sub_context' not in extra:
                   extra['sub_context'] = {}
               sub_context = extra['sub_context']            
               sub_context.update({"my_context": self._my_context_value})
           return func(*args, **kwargs)
 
       return enhance_process
 
   def _enhancelogger(self):
       setattr(logging.ContextAdapter, 'process', self._enhance_context(logging.ContextAdapter.process))


修改后的日志可能如下所示
2014-01-17 13:09:06.815 DEBUG nova.compute.manager [-] [my_context: my_context_value] [instance: c0efa837-3a21-4b08-91f9-995e2ee2adb9] 从 (pid=11649) 更新实例的 info_cache _heal_instance_info_cache /opt/stack/nova/nova/compute/manager.py:4437