瀏覽代碼

Merge pull request #108 from kaelthasmanu/update-log-format-handling-for-legacy-compatibility-and-improve-automatic-detection

Update log format handling for legacy compatibility and improve automatic detection
Manuel Gorrin 3 月之前
父節點
當前提交
49ae1a0058

+ 0 - 1
README.md

@@ -410,7 +410,6 @@ If the command returns the installed version, SquidStats is ready to use.
    SQUID_CACHE_LOG="/var/log/squid/cache.log"
    SQUID_CONFIG_PATH="/etc/squid/squid.conf"
    ACL_FILES_DIR="/etc/squid/acls"
-   LOG_FORMAT="DETAILED"  # Options: DETAILED or DEFAULT
    
    # Database Configuration
    DATABASE_TYPE="SQLITE"  # Options: SQLITE or MARIADB

+ 0 - 1
README_es.md

@@ -409,7 +409,6 @@ Si el comando devuelve la versión instalada, SquidStats está listo para utiliz
    SQUID_CACHE_LOG="/var/log/squid/cache.log"
    SQUID_CONFIG_PATH="/etc/squid/squid.conf"
    ACL_FILES_DIR="/etc/squid/acls"
-   LOG_FORMAT="DETAILED"  # Opciones: DETAILED o DEFAULT
    
    # Configuración de Base de Datos
    DATABASE_TYPE="SQLITE"  # Opciones: SQLITE o MARIADB

+ 63 - 0
alembic/versions/011_remove_log_format.py

@@ -0,0 +1,63 @@
+"""Remove obsolete log_format from squid_config.
+
+Revision ID: 011_remove_log_format
+Revises: 010_add_squid_config
+Create Date: 2026-08-20 00:00:00.000000
+"""
+
+from collections.abc import Sequence
+
+import sqlalchemy as sa
+from sqlalchemy import inspect
+
+from alembic import op
+
+# revision identifiers, used by Alembic.
+revision: str = "011_remove_log_format"
+down_revision: str | None = "010_add_squid_config"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+
+def _has_log_format_column() -> bool:
+    inspector = inspect(op.get_bind())
+    return inspector.has_table("squid_config") and any(
+        column["name"] == "log_format"
+        for column in inspector.get_columns("squid_config")
+    )
+
+
+def upgrade() -> None:
+    """Drop only the obsolete configuration column."""
+    if not _has_log_format_column():
+        return
+
+    if op.get_bind().dialect.name == "sqlite":
+        with op.batch_alter_table("squid_config", recreate="always") as batch_op:
+            batch_op.drop_column("log_format")
+    else:
+        op.drop_column("squid_config", "log_format")
+
+
+def downgrade() -> None:
+    """Restore the legacy column for explicit migration rollback."""
+    if op.get_bind().dialect.name == "sqlite":
+        with op.batch_alter_table("squid_config", recreate="always") as batch_op:
+            batch_op.add_column(
+                sa.Column(
+                    "log_format",
+                    sa.String(length=50),
+                    nullable=False,
+                    server_default="DEFAULT",
+                )
+            )
+    else:
+        op.add_column(
+            "squid_config",
+            sa.Column(
+                "log_format",
+                sa.String(length=50),
+                nullable=False,
+                server_default="DEFAULT",
+            ),
+        )

+ 0 - 3
config.py

@@ -122,9 +122,6 @@ class Config:
         "LISTEN_PORT", safe_get_env("FLASK_PORT", 5000, var_type=int), var_type=int
     )
 
-    # Log parsing mode: 'DETAILED' (current behavior) or 'DEFAULT' (classic Squid format)
-    LOG_FORMAT = safe_get_env("LOG_FORMAT", "DETAILED").upper()
-
     # Application version
     VERSION = safe_get_env("VERSION", "2.5.2")
 

+ 0 - 1
database/models/models.py

@@ -241,7 +241,6 @@ class SquidConfig(Base):
     squid_host = Column(String(255), nullable=False, default="127.0.0.1")
     squid_port = Column(Integer, nullable=False, default=3128)
     squid_hosts = Column(String(512), nullable=False, default="")
-    log_format = Column(String(50), nullable=False, default="DEFAULT")
     squid_log = Column(String(512), nullable=False, default="/var/log/squid/access.log")
     squid_cache_log = Column(
         String(512), nullable=False, default="/var/log/squid/cache.log"

+ 0 - 1
debian/postinst

@@ -41,7 +41,6 @@ SQUID_PORT=3128
 # When set, overrides SQUID_HOST/SQUID_PORT for the active-connections page.
 # Example: SQUID_HOSTS="192.168.0.10:3128,192.168.0.11:3128"
 SQUID_HOSTS=
-LOG_FORMAT=DETAILED
 FLASK_DEBUG=True
 DATABASE_TYPE="SQLITE"
 SQUID_LOG="/var/log/squid/access.log"

+ 0 - 2
example.env

@@ -5,7 +5,6 @@ SQUID_PORT=3128
 # When set, overrides SQUID_HOST/SQUID_PORT for the active-connections page.
 # Example: SQUID_HOSTS="192.168.0.10:3128,192.168.0.11:3128"
 SQUID_HOSTS=
-LOG_FORMAT=DETAILED
 FLASK_DEBUG=True
 DATABASE_TYPE="SQLITE"
 SQUID_LOG="/var/log/squid/access.log"
@@ -23,4 +22,3 @@ FIRST_PASSWORD="mipasswordsegura"
 JWT_EXPIRY_HOURS=24
 MAX_LOGIN_ATTEMPTS=5
 LOCKOUT_DURATION_MINUTES=15
-

+ 0 - 1
install.sh

@@ -400,7 +400,6 @@ VERSION=2.5.2
 SQUID_HOST=127.0.0.1
 SQUID_PORT=3128
 SQUID_HOSTS=
-LOG_FORMAT=DETAILED
 FLASK_DEBUG=True
 DATABASE_TYPE=SQLITE
 SQUID_LOG=/var/log/squid/access.log

+ 0 - 2
manage_db.py

@@ -224,7 +224,6 @@ def migrate_env_squid_config(auto_confirm: bool = False):
     raw_keys = {
         "SQUID_HOST": "squid_host",
         "SQUID_PORT": "squid_port",
-        "LOG_FORMAT": "log_format",
         "SQUID_LOG": "squid_log",
         "SQUID_CACHE_LOG": "squid_cache_log",
         "SQUID_CONFIG_PATH": "squid_config_path",
@@ -288,7 +287,6 @@ def migrate_env_squid_config(auto_confirm: bool = False):
         row = SquidConfig(
             squid_host=env_values.get("squid_host", "127.0.0.1"),
             squid_port=env_values.get("squid_port", 3128),
-            log_format=env_values.get("log_format", "DEFAULT"),
             squid_log=env_values.get("squid_log", "/var/log/squid/access.log"),
             squid_cache_log=env_values.get(
                 "squid_cache_log", "/var/log/squid/cache.log"

+ 251 - 115
parsers/log.py

@@ -1,11 +1,11 @@
 import os
+import re
 import time
 from datetime import datetime
 
 from loguru import logger
 from sqlalchemy.exc import IntegrityError, OperationalError, SQLAlchemyError
 
-from config import Config
 from database.database import (
     Base,
     DeniedLog,
@@ -45,8 +45,33 @@ class DatabaseManager:
 BATCH_SIZE = 500
 MAX_RETRIES = 3
 
-# Log parsing mode controlled by .env LOG_FORMAT: 'DETAILED' or 'DEFAULT'
-LOG_FORMAT = getattr(Config, "LOG_FORMAT", "DETAILED").upper()
+# Supported Squid access-log families.  Detection is automatic; these names
+# are also used as parser hints after sampling a file.
+FORMAT_AUTO = "AUTO"
+FORMAT_DEFAULT = "DEFAULT"
+FORMAT_DETAILED = "DETAILED"
+
+HTTP_METHODS = frozenset(
+    {
+        "CONNECT",
+        "DELETE",
+        "GET",
+        "HEAD",
+        "OPTIONS",
+        "PATCH",
+        "POST",
+        "PUT",
+        "TRACE",
+        "NONE",
+    }
+)
+
+DETAILED_REQUEST_RE = re.compile(
+    r"^\S+\s+(?P<ip>\S+)\s+(?P<identity>\S+)\s+(?P<username>\S+)\s+"
+    r"\[[^\]]*\]\s+"
+    r'"(?P<method>\S+)\s+(?P<url>.*?)\s+HTTP/(?P<http_version>[^"]+)"\s+'
+    r"(?P<status>\S+)\s+(?P<bytes>\S+)(?:\s+.*)?$"
+)
 
 
 def find_last_parent_proxy(log_file: str, lines_to_check: int = 5000) -> str | None:
@@ -102,109 +127,193 @@ def get_file_inode(filepath):
         raise
 
 
-def parse_log_line(line):
-    # Universal ignore for specific squid error entries (apply regardless of LOG_FORMAT)
+def _is_number(value: str) -> bool:
     try:
-        line_lower = line.lower() if isinstance(line, str) else ""
-        if (
-            "error:transaction-end-before-headers" in line_lower
-            or "error:invalid-request" in line_lower
-        ):
-            return None
-    except Exception as e:
-        logger.debug("Unexpected error pre-filtering log line: %s", e)
+        float(value)
+        return True
+    except (TypeError, ValueError):
+        return False
+
+
+def _is_integer(value: str) -> bool:
+    return value.isdigit()
+
+
+def _response_code(status: str) -> int:
+    code = status.rsplit("/", 1)[-1]
+    return int(code) if code.isdigit() else 0
+
+
+def _bytes_transmitted(value: str) -> int:
+    return int(value) if _is_integer(value) else 0
+
+
+def _is_default_line(parts: list[str]) -> bool:
+    """Recognize Squid's native access.log layout without parsing it twice."""
+    return bool(
+        len(parts) >= 7
+        and _is_number(parts[0])
+        and _is_number(parts[1])
+        and "/" in parts[3]
+        and _is_integer(parts[3].rsplit("/", 1)[-1])
+        and (parts[4] == "-" or _is_integer(parts[4]))
+        and parts[5].upper() in HTTP_METHODS
+    )
+
+
+def _is_pipe_line(line: str) -> bool:
+    parts = line.strip().split("|")
+    return bool(
+        len(parts) >= 14
+        and _is_number(parts[0])
+        and _is_integer(parts[8])
+        and _is_integer(parts[9])
+        and parts[5].upper() in HTTP_METHODS
+    )
+
+
+def _is_space_detailed_line(parts: list[str]) -> bool:
+    """Recognize the legacy whitespace-separated DETAILED layout."""
+    return bool(
+        len(parts) >= 11
+        and _is_number(parts[0])
+        and parts[5].upper() in HTTP_METHODS
+        and _is_integer(parts[9])
+        and _is_integer(parts[10])
+    )
+
+
+def _is_quoted_detailed_line(line: str):
+    match = DETAILED_REQUEST_RE.match(line.strip())
+    return bool(match and match.group("method").upper() in HTTP_METHODS)
 
-    if LOG_FORMAT == "DEFAULT":
-        return parse_log_line_default(line)
 
-    # DETAILED (current behavior)
-    if "cache_object://" in line:
+def _detect_line_format(line: str) -> str | None:
+    if not isinstance(line, str) or not line.strip():
         return None
-    if "|" in line:
-        return parse_log_line_pipe_format(line)
+
+    if _is_pipe_line(line):
+        return FORMAT_DETAILED
+
     parts = line.split()
-    # Classic Squid format: timestamp elapsed ip code/status bytes method url rfc931 peerstatus/peerhost type
-    if len(parts) >= 10 and (
-        len(parts) > 5
-        and parts[5]
-        in (
-            "CONNECT",
-            "GET",
-            "POST",
-            "HEAD",
-            "PUT",
-            "DELETE",
-            "OPTIONS",
-            "TRACE",
-            "PATCH",
-        )
-    ):
-        try:
-            return {
-                "ip": parts[2],
-                # Keep current behavior: if '-', set None
-                "username": parts[2] if parts[2] != "-" else None,
-                "url": parts[6],
-                "response": int(parts[3].split("/")[-1])
-                if "/" in parts[3] and parts[3].split("/")[-1].isdigit()
-                else 0,
-                "data_transmitted": int(parts[4]) if parts[4].isdigit() else 0,
-                "method": parts[5],
-                "status": parts[3],
-                "is_denied": "TCP_DENIED" in parts[3],
-            }
-        except Exception as e:
-            logger.error(f"Error parsing classic squid log line: {line.strip()} - {e}")
+    if _is_default_line(parts):
+        return FORMAT_DEFAULT
+
+    if _is_quoted_detailed_line(line) or _is_space_detailed_line(parts):
+        return FORMAT_DETAILED
+
+    return None
+
+
+def _ignore_log_line(line: str) -> bool:
+    line_lower = line.lower()
+    return (
+        "cache_object://" in line_lower
+        or "error:transaction-end-before-headers" in line_lower
+        or "error:invalid-request" in line_lower
+    )
+
+
+def parse_log_line(line: str, format_hint: str = FORMAT_AUTO):
+    """Parse one line using a detected format or safe per-line detection."""
+    if not isinstance(line, str) or not line.strip():
+        return None
+
+    try:
+        if _ignore_log_line(line):
             return None
-    # If not classic, try the space format
-    return parse_log_line_space_format(line)
+    except Exception as error:
+        logger.debug("Unexpected error pre-filtering log line: {}", error)
+        return None
+
+    normalized_hint = (format_hint or FORMAT_AUTO).upper()
+    if normalized_hint == FORMAT_DEFAULT:
+        return parse_log_line_default(line)
+    if normalized_hint == FORMAT_DETAILED:
+        return parse_log_line_detailed(line)
+
+    detected_format = _detect_line_format(line)
+    if detected_format == FORMAT_DEFAULT:
+        return parse_log_line_default(line)
+    if detected_format == FORMAT_DETAILED:
+        return parse_log_line_detailed(line)
+    return None
 
 
 def parse_log_line_default(line: str):
+    """Parse Squid's standard format.
+
+    ``timestamp elapsed client_ip result/status bytes method url user
+    hierarchy content-type``
+    """
     try:
-        parts = line.split()
-        # Must have at least 10 fields; skip internal cache_object lines
-        if len(parts) < 7:
+        if _ignore_log_line(line):
             return None
-        # Locate URL (may contain spaces only in rare cases; assume standard)
-        # In the typical format, url is at parts[6]
-        url = parts[6] if len(parts) > 6 else None
-        if not url or "cache_object://" in url:
+        parts = line.split()
+        if not _is_default_line(parts):
             return None
 
-        ip = parts[2] if len(parts) > 2 else None
-        status = parts[3] if len(parts) > 3 else ""
-        bytes_str = parts[4] if len(parts) > 4 else "0"
-        method = parts[5] if len(parts) > 5 else ""
-        # User field is usually at parts[7]; if '-', use IP as username
+        status = parts[3]
+        ip = parts[2]
         user_field = parts[7] if len(parts) > 7 else "-"
-        username = user_field if user_field != "-" else (ip or "-")
-
-        response = 0
-        if "/" in status:
-            code = status.split("/")[-1]
-            response = int(code) if code.isdigit() else 0
-
-        data_transmitted = int(bytes_str) if bytes_str.isdigit() else 0
-
+        username = user_field if user_field != "-" else ip
         return {
             "ip": ip,
-            "username": username,
-            "url": url,
-            "response": response,
-            "data_transmitted": data_transmitted,
-            "method": method,
+            "username": username if username != "-" else None,
+            "url": parts[6],
+            "response": _response_code(status),
+            "data_transmitted": _bytes_transmitted(parts[4]),
+            "method": parts[5].upper(),
             "status": status,
             "is_denied": "TCP_DENIED" in status,
         }
-    except Exception as e:
-        logger.error(f"Error parsing DEFAULT format line: {line.strip()} - {e}")
+    except (IndexError, TypeError, ValueError) as error:
+        logger.debug("Unable to parse DEFAULT log line: {} ({})", line.strip(), error)
+        return None
+
+
+def parse_log_line_detailed(line: str):
+    """Parse the supported legacy DETAILED variants."""
+    if _ignore_log_line(line):
         return None
+    if _is_pipe_line(line):
+        return parse_log_line_pipe_format(line)
+
+    quoted_match = DETAILED_REQUEST_RE.match(line.strip())
+    if quoted_match:
+        try:
+            identity = quoted_match.group("identity")
+            username = quoted_match.group("username")
+            ip = quoted_match.group("ip")
+            if username == "-":
+                username = identity if identity != "-" else ip
+            if username == "-":
+                username = None
+            status = quoted_match.group("status")
+            return {
+                "ip": ip,
+                "username": username,
+                "url": quoted_match.group("url"),
+                "response": _response_code(status),
+                "data_transmitted": _bytes_transmitted(quoted_match.group("bytes")),
+                "method": quoted_match.group("method").upper(),
+                "status": status,
+                "is_denied": "TCP_DENIED" in line,
+            }
+        except (IndexError, TypeError, ValueError) as error:
+            logger.debug(
+                "Unable to parse quoted DETAILED log line: {} ({})",
+                line.strip(),
+                error,
+            )
+            return None
+
+    return parse_log_line_space_format(line)
 
 
 def parse_log_line_pipe_format(line):
     parts = line.strip().split("|")
-    if len(parts) < 14:
+    if not _is_pipe_line(line):
         return None
     try:
         username = parts[3]
@@ -216,58 +325,80 @@ def parse_log_line_pipe_format(line):
             "url": parts[6],
             "response": int(parts[8]),
             "data_transmitted": int(parts[9]),
-            "method": parts[5],
+            "method": parts[5].upper(),
             "status": parts[13],
             "is_denied": "TCP_DENIED" in parts[13],
         }
-    except Exception as e:
-        logger.error(f"Error parsing line with pipe format: {line.strip()} - {e}")
+    except (IndexError, TypeError, ValueError) as error:
+        logger.debug("Unable to parse pipe log line: {} ({})", line.strip(), error)
         return None
 
 
 def parse_log_line_space_format(line):
+    """Parse the legacy whitespace-separated DETAILED variant."""
     try:
         parts = line.split()
-        if len(parts) < 11 or parts[3] == "-":
+        if not _is_space_detailed_line(parts) or parts[3] == "-":
             return None
+        status = parts[4]
         return {
             "ip": parts[1],
             "username": parts[3],
-            "url": parts[7],
-            "response": int(parts[9]) if parts[9].isdigit() else 0,
-            "data_transmitted": int(parts[10]) if parts[10].isdigit() else 0,
-            "method": parts[5] if len(parts) > 5 else "",
-            "status": parts[6] if len(parts) > 6 else "",
+            "url": parts[6],
+            "response": int(parts[9]),
+            "data_transmitted": int(parts[10]),
+            "method": parts[5].upper(),
+            "status": status,
             "is_denied": "TCP_DENIED" in line,
         }
-    except (IndexError, ValueError) as e:
-        logger.error(f"Error parsing line with space format: {line.strip()} - {e}")
+    except (IndexError, TypeError, ValueError) as error:
+        logger.debug(
+            "Unable to parse space DETAILED line: {} ({})", line.strip(), error
+        )
         return None
 
 
-def detect_log_format(log_file, sample_lines=10):
+def detect_log_format(log_file, sample_lines=32, start_position=0):
+    """Detect DEFAULT or DETAILED by validating a small sample of lines."""
     try:
-        with open(log_file, encoding="utf-8", errors="replace") as f:
-            pipe_count = 0
-            space_count = 0
-
-            for i, line in enumerate(f):
-                if i >= sample_lines:
+        with open(log_file, encoding="utf-8", errors="replace") as file:
+            if start_position:
+                file.seek(start_position)
+
+            counts = {FORMAT_DEFAULT: 0, FORMAT_DETAILED: 0}
+            for _ in range(sample_lines):
+                line = file.readline()
+                if not line:
                     break
-
-                if (
-                    "|" in line and line.count("|") > 5
-                ):  # Pipe format typically has many |
-                    pipe_count += 1
-                elif len(line.split()) > 10:  # Space format typically has many fields
-                    space_count += 1
-
-            format_detected = "pipe" if pipe_count > space_count else "space"
-            return format_detected
-
-    except Exception as e:
-        logger.warning(f"Error detecting format, using line detection: {e}")
-        return "auto"  # Fallback to automatic per-line detection
+                detected = _detect_line_format(line)
+                if detected:
+                    counts[detected] += 1
+
+            # A tail containing only malformed/ignored lines should not force
+            # a wrong format.  Retry from the beginning in that case.
+            if not any(counts.values()) and start_position:
+                file.seek(0)
+                for _ in range(sample_lines):
+                    line = file.readline()
+                    if not line:
+                        break
+                    detected = _detect_line_format(line)
+                    if detected:
+                        counts[detected] += 1
+
+            if not any(counts.values()):
+                return FORMAT_AUTO
+
+            if counts[FORMAT_DEFAULT] > counts[FORMAT_DETAILED]:
+                return FORMAT_DEFAULT
+            if counts[FORMAT_DETAILED] > counts[FORMAT_DEFAULT]:
+                return FORMAT_DETAILED
+            return FORMAT_AUTO
+    except OSError as error:
+        logger.warning(
+            "Unable to detect log format; using per-line detection: {}", error
+        )
+        return FORMAT_AUTO
 
 
 def process_logs(log_file):
@@ -305,6 +436,11 @@ def process_logs(log_file):
                         f"File truncated (size: {file_size} < position: {last_position})"
                     )
                     last_position = 0
+            detected_format = detect_log_format(log_file, start_position=last_position)
+            logger.info(
+                "Detected Squid log format: {}",
+                detected_format,
+            )
             # logger.info(f"Reading from position: {last_position}")
             user_cache = {}
             logs_to_insert, new_users_to_insert, denied_to_insert = [], [], []
@@ -369,7 +505,7 @@ def process_logs(log_file):
                 for line in f:
                     processed_lines += 1
                     current_position += len(line.encode("utf-8"))
-                    log_data = parse_log_line(line)
+                    log_data = parse_log_line(line, format_hint=detected_format)
                     if not log_data:
                         continue
                     if log_data["is_denied"]:

+ 0 - 3
services/squid/squid_config_db_service.py

@@ -5,7 +5,6 @@ SQUID_ENV_KEYS = {
     "SQUID_HOST",
     "SQUID_PORT",
     "SQUID_HOSTS",
-    "LOG_FORMAT",
     "SQUID_LOG",
     "SQUID_CACHE_LOG",
     "SQUID_CONFIG_PATH",
@@ -16,7 +15,6 @@ SQUID_ENV_TO_DB_FIELD = {
     "SQUID_HOST": "squid_host",
     "SQUID_PORT": "squid_port",
     "SQUID_HOSTS": "squid_hosts",
-    "LOG_FORMAT": "log_format",
     "SQUID_LOG": "squid_log",
     "SQUID_CACHE_LOG": "squid_cache_log",
     "SQUID_CONFIG_PATH": "squid_config_path",
@@ -81,7 +79,6 @@ def load_squid_config_from_db() -> dict[str, str]:
             "SQUID_HOST": str(row.squid_host or ""),
             "SQUID_PORT": str(row.squid_port or ""),
             "SQUID_HOSTS": str(row.squid_hosts or ""),
-            "LOG_FORMAT": str(row.log_format or ""),
             "SQUID_LOG": str(row.squid_log or ""),
             "SQUID_CACHE_LOG": str(row.squid_cache_log or ""),
             "SQUID_CONFIG_PATH": str(row.squid_config_path or ""),

+ 2 - 2
templates/admin/config.html

@@ -85,7 +85,7 @@
         <form method="POST" action="{{ url_for('admin.save_env') }}" x-show="editing" class="grid grid-cols-1 md:grid-cols-2 gap-6">
             <input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
             {% set sensitive_vars = ['VERSION', 'JWT_SECRET_KEY', 'FIRST_PASSWORD', 'DATABASE_STRING_CONNECTION'] %}
-            {% for key in ['SQUID_HOST', 'SQUID_PORT', 'SQUID_HOSTS', 'LOG_FORMAT', 'SQUID_LOG', 'SQUID_CACHE_LOG', 'SQUID_CONFIG_PATH', 'ACL_FILES_DIR'] %}
+            {% for key in ['SQUID_HOST', 'SQUID_PORT', 'SQUID_HOSTS', 'SQUID_LOG', 'SQUID_CACHE_LOG', 'SQUID_CONFIG_PATH', 'ACL_FILES_DIR'] %}
             {% set value = env_vars.get(key, '') %}
             <div class="bg-gray-50 p-4 rounded-lg border border-gray-200">
                 <label class="block text-sm font-semibold text-gray-700 mb-2">{{ key }}</label>
@@ -101,7 +101,7 @@
         </form>
         
         <div x-show="!editing" class="bg-gray-900 rounded-lg p-4 overflow-x-auto">
-            <pre class="text-green-400 text-sm font-mono whitespace-pre-wrap">{% for key in ['SQUID_HOST', 'SQUID_PORT', 'SQUID_HOSTS', 'LOG_FORMAT', 'SQUID_LOG', 'SQUID_CACHE_LOG', 'SQUID_CONFIG_PATH', 'ACL_FILES_DIR'] %}{{ key }}="{{ env_vars.get(key, '') }}"
+            <pre class="text-green-400 text-sm font-mono whitespace-pre-wrap">{% for key in ['SQUID_HOST', 'SQUID_PORT', 'SQUID_HOSTS', 'SQUID_LOG', 'SQUID_CACHE_LOG', 'SQUID_CONFIG_PATH', 'ACL_FILES_DIR'] %}{{ key }}="{{ env_vars.get(key, '') }}"
 {% endfor %}</pre>
         </div>
     </div>

+ 50 - 0
tests/test_parsers_log.py

@@ -3,6 +3,10 @@ Tests for log line parsers (parsers/log.py).
 """
 
 from parsers.log import (
+    FORMAT_AUTO,
+    FORMAT_DEFAULT,
+    FORMAT_DETAILED,
+    detect_log_format,
     parse_log_line,
     parse_log_line_default,
     parse_log_line_pipe_format,
@@ -125,3 +129,49 @@ class TestDefaultFormat:
         )
         result = parse_log_line_default(line)
         assert result is None
+
+
+class TestAutomaticFormatDetection:
+    def test_detects_default_file_format(self, tmp_path):
+        log_file = tmp_path / "access.log"
+        log_file.write_text(
+            "1609459200.000 1 192.168.1.100 TCP_MISS/200 1234 "
+            "GET http://example.com/page user1 HIER_DIRECT/- text/html\n",
+            encoding="utf-8",
+        )
+
+        assert detect_log_format(log_file) == FORMAT_DEFAULT
+
+    def test_detects_detailed_file_format(self, tmp_path):
+        log_file = tmp_path / "access.log"
+        log_file.write_text(
+            "1609459200.000 192.168.1.100 - user1 "
+            "[20/Aug/2026:14:00:00 -0400] "
+            '"GET http://example.com/page HTTP/1.1" 200 1234 '
+            "GET http://example.com/page 192.168.1.100 text/html "
+            "- TCP_MISS/200 1234\n",
+            encoding="utf-8",
+        )
+
+        assert detect_log_format(log_file) == FORMAT_DETAILED
+
+        result = parse_log_line(
+            log_file.read_text(encoding="utf-8").strip(),
+            format_hint=FORMAT_DETAILED,
+        )
+        assert result == {
+            "ip": "192.168.1.100",
+            "username": "user1",
+            "url": "http://example.com/page",
+            "response": 200,
+            "data_transmitted": 1234,
+            "method": "GET",
+            "status": "200",
+            "is_denied": False,
+        }
+
+    def test_unknown_file_falls_back_to_per_line_detection(self, tmp_path):
+        log_file = tmp_path / "access.log"
+        log_file.write_text("not a Squid access log\n", encoding="utf-8")
+
+        assert detect_log_format(log_file) == FORMAT_AUTO

+ 81 - 0
tests/test_squid_config_migration.py

@@ -0,0 +1,81 @@
+"""Regression tests for removing the obsolete Squid log format setting."""
+
+from alembic.config import Config as AlembicConfig
+from sqlalchemy import (
+    Column,
+    DateTime,
+    Integer,
+    MetaData,
+    String,
+    Table,
+    create_engine,
+    inspect,
+    text,
+)
+
+from alembic import command
+from config import Config
+
+
+def test_remove_log_format_migration_preserves_squid_config(tmp_path, monkeypatch):
+    database_path = tmp_path / "squidstats.db"
+    engine = create_engine(f"sqlite:///{database_path}", future=True)
+    metadata = MetaData()
+    Table(
+        "squid_config",
+        metadata,
+        Column("id", Integer, primary_key=True),
+        Column("squid_host", String(255), nullable=False),
+        Column("squid_port", Integer, nullable=False),
+        Column("squid_hosts", String(512), nullable=False),
+        Column("log_format", String(50), nullable=False),
+        Column("squid_log", String(512), nullable=False),
+        Column("squid_cache_log", String(512), nullable=False),
+        Column("squid_config_path", String(512), nullable=False),
+        Column("acl_files_dir", String(512), nullable=False),
+        Column("created_at", DateTime, nullable=False),
+        Column("updated_at", DateTime),
+    )
+    metadata.create_all(engine)
+
+    with engine.begin() as connection:
+        connection.execute(
+            text(
+                "INSERT INTO squid_config "
+                "(id, squid_host, squid_port, squid_hosts, log_format, squid_log, "
+                "squid_cache_log, squid_config_path, acl_files_dir, created_at) "
+                "VALUES (1, '127.0.0.1', 3128, '', 'DETAILED', '/var/log/squid/access.log', "
+                "'/var/log/squid/cache.log', '/etc/squid/squid.conf', '', CURRENT_TIMESTAMP)"
+            )
+        )
+        connection.execute(
+            text("CREATE TABLE alembic_version (version_num VARCHAR(32) NOT NULL)")
+        )
+        connection.execute(
+            text(
+                "INSERT INTO alembic_version (version_num) VALUES ('010_add_squid_config')"
+            )
+        )
+
+    old_database_type = Config.DATABASE_TYPE
+    old_connection = Config.DATABASE_STRING_CONNECTION
+    monkeypatch.setattr(Config, "DATABASE_TYPE", "SQLITE")
+    monkeypatch.setattr(Config, "DATABASE_STRING_CONNECTION", str(database_path))
+
+    try:
+        alembic_config = AlembicConfig("alembic.ini")
+        command.upgrade(alembic_config, "head")
+    finally:
+        Config.DATABASE_TYPE = old_database_type
+        Config.DATABASE_STRING_CONNECTION = old_connection
+
+    columns = {column["name"] for column in inspect(engine).get_columns("squid_config")}
+    assert "log_format" not in columns
+    assert {"squid_host", "squid_port", "squid_log"}.issubset(columns)
+
+    with engine.connect() as connection:
+        assert (
+            connection.execute(text("SELECT COUNT(*) FROM squid_config")).scalar() == 1
+        )
+
+    engine.dispose()