Last active
July 23, 2018 13:13
-
-
Save pypeach/eeefeec93eac6b7f6e48eb8c3a98e4f3 to your computer and use it in GitHub Desktop.
ログファイルのローテーションを行うサンプル
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding:utf-8 | |
import datetime | |
import glob | |
import logging | |
import os | |
from app.util import app_config, date_helper | |
""" | |
ログファイルをローテーション(バックアップと過去ファイル削除)するサンプルアプリケーションです | |
""" | |
__author__ = "t.ebinuma" | |
__version__ = "1.0" | |
__date__ = "28 April 2018" | |
class RotateLogFile: | |
def __init__(self): | |
# ログファイルパス | |
self.log_file = app_config.get_log_file_path() | |
# バックアップファイルパス | |
self.backup_log_file = os.path.join(app_config.get_value("log_path"), app_config.get_value("backup_log_file")) | |
# ログファイル廃棄期間 | |
self.delete_days = app_config.get_value('delete_days_log_file') | |
# 削除対象ログファイルパス。削除対象ファイルの検索で使用する | |
self.find_file = os.path.join(app_config.get_value("log_path"), app_config.get_value("find_delete_log_file")) | |
def rotate_file(self): | |
""" | |
ログファイルのローテーションを行う | |
""" | |
try: | |
# 現在年月日を取得する | |
today_dt = date_helper.get_today_dt('%02d-%02d-%02d') | |
# ログファイルの存在チェックを行う | |
if os.path.isfile(self.log_file): | |
# バックアップするログファイルに年月日を付与する | |
backup_log_file = self.backup_log_file.replace('{$today_dt}', str(today_dt)) | |
# バックアップするログファイルが存在する場合はファイルを削除する | |
if os.path.isfile(backup_log_file): | |
os.remove(backup_log_file) | |
# ログファイルをバックアップする | |
os.rename(self.log_file, backup_log_file) | |
print("backup_log_file={}".format(backup_log_file)) | |
# 削除年月日を取得する | |
delete_dt = date_helper.get_past_dt(self.delete_days, '%02d%02d%02d') | |
# 削除年月日を過ぎたログファイルを削除する | |
# 削除年月日はシステム日付で判定します | |
for log_file_item in glob.glob(self.find_file): | |
log_file_dt = datetime.datetime.fromtimestamp(os.stat(log_file_item).st_mtime).strftime('%Y%m%d') | |
if int(delete_dt) > int(log_file_dt): | |
os.remove(log_file_item) | |
print("remove_log_file={}".format(log_file_item)) | |
except Exception as e: | |
logging.debug(e) | |
def main(): | |
app_class = RotateLogFile() | |
app_class.rotate_file() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment