[运维]使用flask映射前后端系统日志到指定端口,不影响nginx配置

为了不影响复杂的nginx转发配置,使用flask映射日志

#/home/ops/log_web_viewer/log_server.py
from flask import Flask, render_template, request
import os

app = Flask(__name__)

LOG_FILES = {
    "backend": "/var/log/backend.log",
    "backend-error": "/var/log/backend.err.log",
    "frontend": "/var/log/frontend.log",
    "frontend-error": "/var/log/frontend.err.log",
}

def tail_file(filepath, lines=500):
    try:
        with open(filepath, 'rb') as f:
            f.seek(0, os.SEEK_END)
            end = f.tell()
            buffer = bytearray()
            count = 0
            while end > 0 and count < lines:
                end -= 1
                f.seek(end)
                byte = f.read(1)
                buffer.extend(byte)
                if byte == b'\n':
                    count += 1
            return buffer[::-1].decode('utf-8', errors='replace')
    except Exception as e:
        return f"Error reading file: {str(e)}"

@app.route('/')
def index():
    log_type = request.args.get("log", "backend")
    lines = int(request.args.get("lines", 500))
    if log_type not in LOG_FILES:
        return f"Invalid log type: {log_type}", 404
    content = tail_file(LOG_FILES[log_type], lines)
    return render_template("index.html", log_types=LOG_FILES.keys(), selected=log_type, log_content=content)

if __name__ == '__main__':
    app.run(host="0.0.0.0", port=18000)

/home/ops/log_web_viewer/templates/index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Log Viewer</title>
    <style>
        body {
            font-family: monospace;
            background-color: #1e1e1e;
            color: #f8f8f2;
            margin: 2em;
        }

        select {
            font-size: 1em;
            margin-bottom: 1em;
        }

        pre {
            background-color: #2d2d2d;
            color: #f1f1f1;
            padding: 1em;
            overflow-x: auto;
            white-space: pre-wrap;
            border-radius: 8px;
            box-shadow: 0 0 4px rgba(255,255,255,0.1);
        }

        .highlight-ok { color: #00cc66; font-weight: bold; }
        .highlight-error { color: #ff5555; font-weight: bold; }
        .highlight-info { color: #66d9ef; }
    </style>

    <!-- 自动刷新 -->
    <script>
        setInterval(() => {
            const params = new URLSearchParams(window.location.search);
            params.set('ts', Date.now());  // 防止缓存
            window.location.search = params.toString();
        }, 10000);  // 每10秒刷新一次
    </script>
</head>
<body>
    <h2>Log Viewer</h2>
    <form method="get">
        <label>Log File:
            <select name="log" onchange="this.form.submit()">
                {% for key in log_types %}
                    <option value="{{ key }}" {% if key == selected %}selected{% endif %}>{{ key }}</option>
                {% endfor %}
            </select>
        </label>
    </form>

    <pre>
{{ log_content | replace("OK", "<span class='highlight-ok'>OK</span>")
               | replace("error", "<span class='highlight-error'>error</span>")
               | replace("INFO", "<span class='highlight-info'>INFO</span>") | safe }}
    </pre>
</body>
</html>

posted @ 2025-04-23 15:33  夜歌乘年少  阅读(16)  评论(0)    收藏  举报