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