Webアプリケーションの定期実行による動作確認の自動化とモニタリングの実践ガイド

Webアプリケーションの定期実行による動作確認の自動化とモニタリングの実践ガイド

今日のデジタル時代において、Webアプリケーションの安定性と信頼性は非常に重要です。本記事では、Ubuntuサーバー上でPythonスクリプトを使用してWebアプリケーションの定期的な動作確認を自動化する方法を詳しく解説します。この手法を実装することで、アプリケーションの問題を迅速に検出し、ユーザー体験を向上させることができます。

なぜWebアプリケーションの定期確認が重要なのか?

Webアプリケーションの定期的な動作確認は以下の理由から重要です。

  • 問題の早期発見:小さな問題が大きな障害に発展する前に検出できます。
  • ダウンタイムの最小化:迅速な問題対応により、サービス停止時間を減らせます。

それでは、具体的な実装方法を見ていきましょう。

実装環境

本ガイドでは、以下の環境を使用します。

  • サーバーOS:Ubuntu 24.04 LTS
  • プログラミング言語:Python 3
  • 主要ライブラリ:Selenium、Requests

環境構築手順

Ubuntuサーバー上で以下の手順に従って環境を構築します。

1. Python仮想環境の準備

まず、venvを使用してPython専用の仮想環境を作成します。これにより、プロジェクト固有の依存関係を他のプロジェクトから分離できます。

# 仮想環境の作成
python3 -m venv .venv

# 仮想環境の有効化
source .venv/bin/activate

2. 必要なライブラリのインストール

仮想環境を有効にした後、以下のコマンドで必要なライブラリをインストールします。

pip install selenium
pip install chromedriver-autoinstaller
pip install requests

3. 日本語環境の追加

Chromedriverで日本語を正しく表示するために、以下のコマンドで日本語フォントをインストールします。

sudo apt update
sudo apt install fonts-noto-cjk
fc-cache -fv

自動化スクリプトの実装

以下に、Webアプリケーションの自動ログインテストを行い、結果をDiscordに通知するPythonスクリプトの主要部分を示します。

import os
import requests
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import chromedriver_autoinstaller
import time
from datetime import datetime
import logging

# ロギングの設定
logging.basicConfig(filename='login_test.log', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

# Discord Webhook URL
webhook_url = 'https://discord.com/api/webhooks/xxxxxxx/xxxxxxxxxxxxxxxxxx'

# テスト対象のWebアプリケーションURL
url = "https://example.com/login"

# ログイン情報
username = 'testuser'
userpassword = 'testpassword'

# ChromeDriverの設定
chromedriver_autoinstaller.install()
chrome_options = Options()
chrome_options.add_argument("--headless")

def send_discord_notification(message, screenshot_filename=None):
    # Discordへの通知処理

try:
    driver = webdriver.Chrome(service=Service(), options=chrome_options)
    driver.set_window_size(1920, 1080)
    
    # ログインページにアクセス
    driver.get(url)
    
    # ログイン処理
    WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.NAME, "username")))
    driver.find_element(By.NAME, "username").send_keys(username)
    driver.find_element(By.NAME, "password").send_keys(userpassword)
    driver.find_element(By.XPATH, '//button[contains(text(), "ログイン")]').click()
    
    # スクリーンショットの取得
    time.sleep(5)
    now = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
    screenshot_filename = f"{now}_mypage.png"
    driver.save_screenshot(screenshot_filename)
    
    # ログイン結果の確認と通知
    login_result = "ログイン成功" if "マイページ" in driver.title else "ログイン失敗"
    send_discord_notification(f"ログインテスト結果: {login_result}", screenshot_filename)

except Exception as e:
    logging.error(f"エラーが発生しました: {str(e)}")
    send_discord_notification(f"ログインテスト中にエラーが発生しました: {str(e)}")

finally:
    if 'driver' in locals():
        driver.quit()

スクリプトの定期実行設定

このスクリプトを定期的に実行するには、crontabを使用します。以下のコマンドでcrontabを編集し、スクリプトの実行スケジュールを設定します。

crontab -e

例えば、毎日午前9時に実行する場合は、以下の行を追加します:

0 9 * * * /path/to/your/venv/bin/python /path/to/your/script.py

まとめ

本記事では、Webアプリケーションの定期的な動作確認を自動化する方法について解説しました。定期的な動作確認は、現代のWebアプリケーション運用において不可欠な要素です。本ガイドを参考に、皆様のプロジェクトにも自動化されたモニタリングシステムを導入し、より安定したサービス提供を実現してください。

追記

Q. seleniumがインストールできない

pipでインストールしようとすると以下のエラーが表示される。

$ pip3 install selenium
error: externally-managed-environment

× This environment is externally managed
╰─> To install Python packages system-wide, try apt install
    python3-xyz, where xyz is the package you are trying to
    install.
    
    If you wish to install a non-Debian-packaged Python package,
    create a virtual environment using python3 -m venv path/to/venv.
    Then use path/to/venv/bin/python and path/to/venv/bin/pip. Make
    sure you have python3-full installed.
    
    If you wish to install a non-Debian packaged Python application,
    it may be easiest to use pipx install xyz, which will manage a
    virtual environment for you. Make sure you have pipx installed.
    
    See /usr/share/doc/python3.12/README.venv for more information.

note: If you believe this is a mistake, please contact your Python installation or OS distribution provider. You can override this, at the risk of breaking your Python installation or OS, by passing --break-system-packages.
hint: See PEP 668 for the detailed specification.

A. Pythonの仮想環境が有効になっていない

以下のコマンドで仮想環境を有効にする必要がある

$ source .venv/bin/activate