2016-09-11 9 views
1

logging 모듈을 사용하는 Python 라이브러리를 사용합니다. 그러나 내 스크립트를 내부적으로 사용하는 log 함수를 만들었습니다.로깅 정보를 함수의 인수로 전달하십시오.

def log(name, content, swtch : bool = None, time = None): 
    time = time or datetime.now(pytz.timezone('US/Pacific')) 
    if swtch == True or swtch == None: 
     toPrint = '{1.RED}{2}/{3}/{4} {5}:{6}:{7}:{8} {9} {0.BRIGHT}{1.GREEN}{10} {0.RESET_ALL}{11}{0.RESET_ALL}'.format(
      Style, 
      Fore, 
      str(time.month).zfill(2), 
      str(time.day).zfill(2), 
      str(time.year)[2:], 
      str(time.hour % 12).zfill(2), 
      str(time.minute).zfill(2), 
      str(time.second).zfill(2), 
      str(int(time.microsecond/1000)).zfill(3), 
      'AM' if time.hour < 12 else 'PM', 
      name, 
      content 
     ) 

     print(toPrint) 

    log_txt = '' 

    if swtch == False or swtch == None: 
     file = open('log.txt', 'r') 
     log_txt = file.read() 
     file.close() 

     with open('log.txt', 'w') as file: 
      text = '{0}/{1}/{2} {3}:{4}:{5}:{6} {7} {8} {9}'.format(
       str(time.month).zfill(2), 
       str(time.day).zfill(2), 
       str(time.year)[2:], 
       str(time.hour % 12).zfill(2), 
       str(time.minute).zfill(2), 
       str(time.second).zfill(2), 
       str(int(time.microsecond/1000)).zfill(3), 
       'AM' if time.hour < 12 else 'PM', 
       name, 
       content 
      ) 
      file.write(log_txt + text + '\n') 

하자의 작품 some_logger라는 이름의 로거가 있다고 가정 :

여기 내가 사용하려는 로깅 기능입니다.

stdout으로 인쇄하는 대신 위치 정보 (로그 정보를 나타내는)를 다른 기능으로 전달할 수 있습니까? (명확히하기 위해 : log을 필요한 args와 함께 호출하는 함수)

+0

사용하려는 코드를 표시하십시오. –

+0

좋아, 편집합니다! 묻는 질문에 대한 Thx – Dev

답변

0

Handler과 같은 것을 사용할 수 있다는 것을 알게되었습니다. emit을 구현하는 하위 클래스를 정의해야합니다. 기본 설정은 아래 예를 참조하십시오.

import logging 

class CustomHandler(logging.Handler): 
    def emit(record): 
     log(record.levelname, record.msg) 

logging.getLogger('some_logger').addHandler(CustomHandler()) 
관련 문제