fix: ログ改行混入対策とrun_queue内未処理例外の安全終了を追加

コードレビュー指摘対応。
- ログ備考欄に改行(スタックトレース等)が混入すると1行フォーマットが崩れるため、改行を空白に平坦化
- run_queue内でファイルコピー・移動が例外を投げた場合に未処理例外でクラッシュしていた問題を修正。main()側でrun_queue呼び出しをtry/exceptし、ログ記録の上でロックを解放して安全終了する

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Kenichiro NOGI 2026-08-02 10:24:40 +09:00
parent 099a40d476
commit ce6f25f656
3 changed files with 40 additions and 12 deletions

View File

@ -283,17 +283,24 @@ def main() -> None:
stable_wait_sec = float(config["ファイル安定待ち秒"])
stable_retries = int(config["ファイル安定待ちリトライ回数"])
run_queue(
folders["スキャンフォルダ"],
folders["アウトプットフォルダ"],
folders["成功フォルダ"],
folders["失敗フォルダ"],
folders["ログフォルダ"],
boxes,
margin,
stable_wait_sec,
stable_retries,
)
try:
run_queue(
folders["スキャンフォルダ"],
folders["アウトプットフォルダ"],
folders["成功フォルダ"],
folders["失敗フォルダ"],
folders["ログフォルダ"],
boxes,
margin,
stable_wait_sec,
stable_retries,
)
except Exception as e:
append_log(
folders["ログフォルダ"], "エラー", "-", None, None,
f"予期しないエラーで処理を中断しました: {type(e).__name__}: {e}",
)
print(f"予期しないエラーが発生しました: {e}")
finally:
release_lock(lock_path)

View File

@ -26,10 +26,11 @@ def append_log(
) -> None:
log_dir.mkdir(parents=True, exist_ok=True)
now = now_func()
flat_note = note.replace("\r\n", " ").replace("\n", " ").replace("\r", " ")
line = (
f"[{now.strftime('%Y-%m-%d %H:%M:%S')}] "
f"結果={result} | 元ファイル={original_filename} | "
f"氏名={name or ''} | 日付={date or ''} | 備考={note}\n"
f"氏名={name or ''} | 日付={date or ''} | 備考={flat_note}\n"
)
path = log_path_for_today(log_dir, now_func)
with open(path, "a", encoding=LOG_ENCODING) as f:

View File

@ -55,6 +55,26 @@ def test_append_log_handles_none_name_and_date(tmp_path):
assert "備考=抽出不十分" in content
def test_append_log_flattens_multiline_note(tmp_path):
log_dir = tmp_path / "ログ"
append_log(
log_dir,
result="エラー",
original_filename="scan003.pdf",
name=None,
date=None,
note="RuntimeError: OCRエラー\nTraceback (most recent call last):\n line 1",
now_func=fixed_now,
)
content = (log_dir / "2026-08-02.log").read_text(encoding=LOG_ENCODING)
lines = content.splitlines()
assert len(lines) == 1
assert "\n" not in lines[0]
assert "RuntimeError: OCRエラー" in lines[0]
def test_append_log_appends_multiple_lines(tmp_path):
log_dir = tmp_path / "ログ"