Python Logging
๊ฐ๋ฐ์ ํ๋ค๋ณด๋ฉด ๋ณธ ๊ฐ๋ฐ๋งํผ ์ค์ํ๊ณ ๋น์ค์๋ ์์ ์ด ๋ฐ๋ก ๋ก๊ทธ ์์ ์ด๋ค.
python์์๋ logging์ด๋ผ๋ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ฅผ ํตํ์ฌ ํจ์จ์ ์ผ๋ก ๋ก๊ทธ ์์ ์ ํ ์ ์๋ค.
์ผํ๋ฉด์ ๋ด๊ฐ ๊ฐ์ธ์ ์ผ๋ก ์ฌ์ฉํ๋ ๋ก๊ทธ ๊ด๋ จ ํ์ผ์ด๋ค.
import os
import logging
import logging.config
from datetime import datetime
def logger(logs_dir, maintain_log_days=7):
os.makedirs(logs_dir, exist_ok=True)
filename = f"log_{datetime.now().strftime('%Y%m%d')}.log"
file_path = os.path.join(logs_dir, filename)
# logging ์ค์
config_log = {
"version": 1,
"formatters": {
"basic": {
"format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
}
},
"handlers": {
"console": {
"class": "logging.StreamHandler",
"level": "INFO",
"formatter": "basic",
"stream": "ext://sys.stdout"
},
"file_handler": {
"class": "logging.FileHandler",
"level": "DEBUG",
"formatter": "basic",
"filename": file_path,
"encoding": "utf-8"
}
},
"root": {
"level": "INFO",
"handlers": ["console", "file_handler"]
}
}
logging.config.dictConfig(config_log)
logger = logging.getLogger()
delete_old_files(logs_dir, maintain_log_days, logger)
return logger
# ์ค๋๋ ํ์ผ ์ญ์
def delete_old_files(path_target, days_elapsed, logger):
for f in os.listdir(path_target):
f = os.path.join(path_target, f)
if os.path.isfile(f):
timestamp_now = datetime.now().timestamp() # ํ์์คํฌํ(๋จ์:์ด)
# st_mtime(๋ง์ง๋ง์ผ๋ก ์์ ๋ ์๊ฐ)๊ธฐ์ค X์ผ ๊ฒฝ๊ณผ ์ฌ๋ถ
is_old = os.stat(f).st_mtime < timestamp_now - (days_elapsed * 24 * 60 * 60)
if is_old: # X์ผ ๊ฒฝ๊ณผํ๋ค๋ฉด
try:
os.remove(f) # ํ์ผ์ ์ง์ด๋ค
logger.info(f'{f} is deleted') # ์ญ์ ์๋ฃ ๋ก๊น
except OSError: # Device or resource busy (๋ค๋ฅธ ํ๋ก์ธ์ค๊ฐ ์ฌ์ฉ ์ค)๋ฑ์ ์ด์
logger.error(f'{f} can not delete') # ์ญ์ ๋ถ๊ฐ ๋ก๊น
Leave a comment