Python logging.configlogger의 환경 파일 읽기 오류 발생 (KeyError: ‘formatters’)

공유하기

  • Add this entry to Hatena Bookmark
  • 0

logging.configlogger에 대해서 다음과 같은 에러가 발생했다면 프로그램에서 지정한 환경 파일을 위치가 정확한지 확인을 해야할 필요가 있습니다. 아래의 에러 출력 정보만 가지고는 환경 파일(loggertest01.ini)을 찾지 못해서 발생한 에러처럼 보이지 않기 때문에 해결을 못하고 시간만 보낼 수도 있을 것 같습니다. 이 글에서 예시를 들어 KeyError: 'formatters' 에러를 해결하는 방법을 소개하겠습니다.

D:\>py D:\loggertest\loggertest.py
Traceback (most recent call last):
  File "D:\loggertest\loggertest01.py", line 3, in <module>
    logging.config.fileConfig('./loggertest01.ini')
  File ".\Python37\lib\logging\config.py", line 71, in fileConfig
    formatters = _create_formatters(cp)
  File ".\Python37\lib\logging\config.py", line 104, in _create_formatters
    flist = cp["formatters"]["keys"]
  File ".\Python37\lib\configparser.py", line 958, in __getitem__
    raise KeyError(key)
KeyError: 'formatters'

에러가 발생한 소스

3행의 './loggertest.ini' 와 같이 loggertest01.py와 같은 장소에 있는 아래의 환경 파일을 읽어 설정하도록 되어 있습니다.

하지만 다음과 같이 현재 위치 D:\ 에서 실행했기 때문에 .\loggertest.ini의 결과는 D:\loggertest.ini 가 됩니다. 실제로는 loggertest.ini는 D:\loggertest\loggertest.ini에 존재하기 때문에 다음과 같은 에러가 발생 했습니다.

D:\>py D:\loggertest\loggertest.py
Traceback (most recent call last):
  File "D:\loggertest\loggertest01.py", line 3, in <module>
    logging.config.fileConfig('./loggertest01.ini')
  File ".\Python37\lib\logging\config.py", line 71, in fileConfig
    formatters = _create_formatters(cp)
  File ".\Python37\lib\logging\config.py", line 104, in _create_formatters
    flist = cp["formatters"]["keys"]
  File ".\Python37\lib\configparser.py", line 958, in __getitem__
    raise KeyError(key)
KeyError: 'formatters'

에러를 해결한 수정된 소스

다음 소스의 4행 os.path.abspath(__file__)은 현재 실행 파일의 전체 파일 패스를 취득하며 그 결과는 D:\loggertest\loggertest.py이 됩니다.
그리고, os.path.dirname(전체 파일 패스)은 전체 파일 패스에서 전체 디렉토리 패스를 취득하며 그 결과는 D:\loggertest이 됩니다.

5행 os.chdir(전체 디렉토리 패스)는 현재 디렉토리를 전체 디렉토리 패스 D:\loggertest로 변경합니다. 이 결과 위의 현재 위치 D:\ 대신에 현재 위치가 D:\loggertest가 되기 때문에 .\loggertest.ini의 결과는D:\loggertest\loggertest.ini가 되고 에러 없이 logger.info('Hello World!')를 화면과 파일에 출력하게 됩니다.

D:\>py D:\loggertest\loggertest02.py
[2021/04/02 16:17:32][INFO](loggertest02.py:9) Hello World!

결론

위 에러는 logging.config.fileConfig('./loggertest.ini')에서 발생했습니다 fileConfig 함수는 첫 번째 인수로 지정된 파일에서 [formatters] key정보를 취득하도록 되어있는데 파일 취득부터 실패했음에도 불구하고 파일 취득 실패 에러가 아닌 [formatters] key정보 취득 에러로 표시한 것 같습니다.

loggertest.ini의 8행에 내용 [formatters]를 지우거나 [formater]와 같이 잘못된 정보로 바꿔도 똑같은 에러가 출력됩니다.

만든 사람 취향이라 쓰는 사람은 이해가 안되겠지만 이 글 같은 정보를 통해 배울 수 밖에 없을 것 같습니다.