2017-01-30 1 views
0

로깅을 수행하는 유틸리티 메소드가 있습니다.로깅에서 "funcName"덮어 쓰기

유틸리티 메서드의 이름이 아니라 로그에서 호출하는 메서드 이름을보고 싶습니다.

테스트를 위해 (나중에 inspect 모듈을 통해 호출자로부터 "bar"를 얻고 싶습니다.)

2017-01-30 15:00:24 loghelper.helper 

내가 싶습니다 :

def helper(...): 
    logger.info('foo', extra=dict(funcName='bar')) 

그러나이 작동하지 않습니다 : (나는 "추가"를 전달하려고하지 않는 경우) 다음

File "/usr/lib/python2.7/logging/__init__.py", line 1167, in info 
    self._log(INFO, msg, args, **kwargs) 
    File "/usr/lib/python2.7/logging/__init__.py", line 1285, in _log 
    record = self.makeRecord(self.name, level, fn, lno, msg, args, exc_info, func, extra) 
    File "/usr/lib/python2.7/logging/__init__.py", line 1263, in makeRecord 
    raise KeyError("Attempt to overwrite %r in LogRecord" % key) 
KeyError: "Attempt to overwrite 'funcName' in LogRecord" 

는 출력 발신자보기 :

2017-01-30 15:00:24 calling_module.calling_method 

이자형?

업데이트는

방법-이름과 다른 데이터 로깅 포맷 장치를 통해 출력됩니다 :

logging.Formatter('%(asctime)s %(name)s.%(funcName)s +%(lineno)s: %(levelname)-8s [%(process)d] %(message)s', 
            '%Y-%m-%d %H:%M:%S') 

답변

0

당신은 더 logging 메소드를 호출 중간 방법을 추가 할 수 있습니다.

def autolog(message): 
    "Automatically log the current function details." 
    import inspect, logging 
    # Get the previous frame in the stack, otherwise it would 
    # be this function!!! 
    func = inspect.currentframe().f_back.f_code 
    # Dump the message + the name of this function to the log. 
    logging.debug("%s: %s in %s:%i" % (
     message, 
     func.co_name, 
     func.co_filename, 
     func.co_firstlineno 
    )) 
+0

inspect를 통해 메소드 이름을 얻는 방법을 조사해 주셔서 감사합니다. 문제는 로깅 출력에이 이름을 지정하는 것입니다 (인쇄가 아닌 로깅을 통해). – guettli

+0

로깅 func의 스 니펫을 표시 할 수 있습니까? 또는 inbuilt 모듈을 사용하고 있습니까? – harshil9968

+0

func-name은 로깅 Formater (우리 코드가 아님)를 통해 출력됩니다. 나는 그 질문을 갱신했다. 나는 로깅 기능의 스 니펫 (snippet)을 보여주는 것이 더 이상 의미가 없다고 생각한다. 어떻게 생각해? – guettli

관련 문제