Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/logging/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 2.7 删除样板记录设置_Python 2.7_Logging_Python Decorators - Fatal编程技术网

Python 2.7 删除样板记录设置

Python 2.7 删除样板记录设置,python-2.7,logging,python-decorators,Python 2.7,Logging,Python Decorators,我看到了我用来设置日志记录的非常常见的代码 def has_host_running(self): log = CustomLogger.action_logger(name=sys._getframe().f_code.co_name, **self.menvargs) result = self.bash_query.check_is_server_available(log) self.results[sys._getframe().f_c

我看到了我用来设置日志记录的非常常见的代码

 def has_host_running(self):
        log = CustomLogger.action_logger(name=sys._getframe().f_code.co_name, **self.menvargs)
        result = self.bash_query.check_is_server_available(log)
        self.results[sys._getframe().f_code.co_name] = result
        log.debug('result: {}'.format(result))
        return result
正在寻找实现此行为的简单方法。 关键是我需要能够从函数和任何子函数调用中引用/调用中的日志语句

******************************编辑2*******************************

我能找到的最优雅、最草率的解决方案。 大致改编自:

主要基于 类操作日志: def初始化(自身): 通过

def __call__(self, f):
    log = self.get_actionlogger(name=f.func_name)

    def newf(log, *args, **kwds):
        # pre-function call actions:
        log.debug('Start.')
        log.debug('    info: params= {args}, {kwds}'.format(args=args, kwds=kwds))

        # function call
        f_result = f(log, *args, **kwds)

        # post-function call actions:
        log.debug('    info: result= {result}'.format(result=f_result))
        log.debug('Complete.')
        return f_result

    # changes to be made to returned function
    newf.__doc__ = f.__doc__
    return newf(log)

def get_actionlogger(self, name, **kwargs):
    import logging
    import ast
    from Helper import ConfigManager

    logname = 'action.{func_name}'.format(func_name=name)
    logger = logging.getLogger(logname)

    # value stored in ini file.
    # either DEBUG or ERROR right now.
    # todo: store actual logging_level
    # todo: store an array/dict for log_name in .ini
    #       this will allow multiple parameters to be stored within the single entry.
    #       ex:
    #       action.check_stuff:    logging_level=DEBUG,handler_stream=TRUE,handler_file=stuff.log,formatter='{name} - {message}
    conf_logging_level = ConfigManager('config.ini').get_section_dict('CustomLogging_Level').get(logname, 'DEBUG')
    logging_level = logging.DEBUG
    if conf_logging_level == 'DEBUG':
        logging_level = logging.DEBUG
    if conf_logging_level == 'ERROR':
        logging_level = logging.ERROR

    logger.setLevel(logging_level)

    # very hacky
    # while logging.getLogger is a singleton, adding the handler is not.
    # without this check, this code will result in duplicate handlers added.
    # currently will not edit/replace the existing handler.
    # currently will not allow another handler to be added after the first.
    # main issue here is that I can't figure out how to determine labels/names within logger.handlers
    # todo: properly label handler
    # todo: check for existing labels & types (file, stream, etc)
    if len(logger.handlers) == 0:
        ch = logging.StreamHandler()
        ch.setLevel(logging_level)
        ch.set_name = logname

        # create formatter
        formatter = logging.Formatter(' %(name)s - %(message)s')
        ch.setFormatter(formatter)
        logger.addHandler(ch)

    return logger


@ActionLog()
def检查内容(日志,*args,**kwds):
结果=真
调试('info:text call from in function')
返回结果

如果检查内容: 打印“检查内容是否真实。”

因此,它使用传递到类中的一个参数“log”。如果类没有log参数,则不起作用。我不知道如何处理,如果有进一步的参数。。。可能使用*args或**kwargs,但此解决方案无法处理此问题

对代码格式设置表示歉意。。。我似乎无法将类装饰器与修饰的func和func调用放在同一个块中

*v3.0* v2有多个参数的问题。解决了这个问题,并对v3进行了相当多的简化

def ActionLog(wrapped):
def _wrapper(*args, **kwargs):

    log = CustomLogger.action_logger(wrapped.func_name)
    newargs = list()
    for a in args:
        newargs.append(a)
    newargs.append(log)

    f = wrapped(*newargs, **kwargs)

    if f is None:
        f = ''
    else:
        f = '\tResult: {}'.format(f)

    log.debug('Complete.{}'.format(f))
    return f
return _wrapper
这工作得更好,并且已经取代了我的大多数样板记录调用,用于采取单个参数的操作


仍然存在命名args与kwargs的问题。我只想传递args并将我的自定义项添加到kwargs,但这有一些问题

有点像。它是有效的。。。但我确定它不是优化的或优雅的。好的,只适用于静态函数。需要在decorator中的类函数中处理对self的第一个引用。不知道如何抓取并将其与原木、args和kwargs一起传递。