코드 실행중에 어떤 설정값들은 프로그램을 재기동하지 않고 설정 파일만 변경해서 동적으로 변경하고 싶은 경우가 발생했습니다. 그런경우 N초마다 설정파일을 읽어도 되겠지만 파일이 변경됐을 때 언제 바뀌었는지 로그를 남기고 읽어오고 싶었습니다.
파이썬에서 watchdog 라이브러리를 사용하면 어떤 디렉토리, 파일 등이 변경됐을 때 확인이 가능합니다.
yaml파일이 변경됐을 때 해당 설정값을 읽고 로그를 출력하는 단순한 형태의 코드 예제입니다.
# dynamic_load.py
import sys
import time
import logging
import yaml
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from datetime import datetime, timedelta
class ConfigFileHandler(FileSystemEventHandler):
def __init__(self, file_path):
self.file_path = file_path
self.last_modified = None
self.load_config()
def on_modified(self, event):
if event.src_path.endswith(self.file_path):
now = datetime.now()
if self.last_modified is None or now - self.last_modified > timedelta(seconds=1):
self.last_modified = now
logging.info(f"Detected change in file: {event.src_path}")
self.load_config()
def load_config(self):
try:
with open(self.file_path, 'r') as file:
config = yaml.safe_load(file)
logging.info(f"Loaded configuration: {config}")
except Exception as e:
logging.error(f"Failed to load configuration: {e}")
if __name__ == '__main__':
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(process)d - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
file_path = 'dynamic.yaml'
event_handler = ConfigFileHandler(file_path)
observer = Observer()
observer.schedule(event_handler, path='.', recursive=False)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
변경 전 dynamic.yaml

변경후 dynamic.yaml

결과
