diff --git a/Dockerfile b/Dockerfile index 03b8436..f1440b0 100644 --- a/Dockerfile +++ b/Dockerfile @@ -69,7 +69,9 @@ RUN apt-get update \ ENV HOST="0.0.0.0" \ PORT=12345 \ WORKERS=1 \ - LOG_LEVEL="info" \ + APP_ENV="production" \ + LOG_LEVEL="warning" \ + ACCESS_LOG="false" \ FORWARDED_ALLOW_IPS="" EXPOSE 12345 @@ -77,4 +79,4 @@ EXPOSE 12345 # 生产环境启动命令 # FORWARDED_ALLOW_IPS 默认为空:仅信任直连 IP,避免任意客户端伪造 X-Forwarded-*。 # 若前面有反向代理,请显式设置为代理网段,例如 "10.0.0.0/8,172.16.0.0/12"。 -CMD ["sh", "-c", "exec uvicorn main:app --host \"$HOST\" --port \"$PORT\" --workers \"$WORKERS\" --log-level \"$LOG_LEVEL\" --proxy-headers --forwarded-allow-ips \"${FORWARDED_ALLOW_IPS:-}\""] +CMD ["sh", "-c", "access_log_arg=--no-access-log; if [ \"${APP_ENV:-development}\" != \"production\" ] || [ \"${ACCESS_LOG:-false}\" = \"true\" ]; then access_log_arg=--access-log; fi; exec uvicorn main:app --host \"$HOST\" --port \"$PORT\" --workers \"$WORKERS\" --log-level \"$LOG_LEVEL\" \"$access_log_arg\" --proxy-headers --forwarded-allow-ips \"${FORWARDED_ALLOW_IPS:-}\""] diff --git a/core/logger.py b/core/logger.py index 101413b..95b738e 100644 --- a/core/logger.py +++ b/core/logger.py @@ -1,26 +1,60 @@ import logging +import os import sys +PRODUCTION_ENVIRONMENTS = {"production", "prod"} +LOG_LEVELS = { + "debug": logging.DEBUG, + "info": logging.INFO, + "warning": logging.WARNING, + "error": logging.ERROR, + "critical": logging.CRITICAL, +} + + +def is_production_environment() -> bool: + environment = os.getenv("APP_ENV", "development").strip().lower() + return environment in PRODUCTION_ENVIRONMENTS + + +def get_log_level_name() -> str: + configured_level = os.getenv("LOG_LEVEL", "").strip().lower() + if configured_level in LOG_LEVELS: + return configured_level + return "warning" if is_production_environment() else "info" + + +def get_log_level() -> int: + return LOG_LEVELS[get_log_level_name()] + + +def is_access_log_enabled() -> bool: + configured_value = os.getenv("ACCESS_LOG") + if configured_value is not None: + return configured_value.strip().lower() in {"1", "true", "yes", "on"} + return not is_production_environment() + + def setup_logger(): - # 创建logger对象 - _logger = logging.getLogger('FileCodeBox') - _logger.setLevel(logging.INFO) + _logger = logging.getLogger("FileCodeBox") + level = get_log_level() + _logger.setLevel(level) + _logger.propagate = False - # 创建控制台处理器 - console_handler = logging.StreamHandler(sys.stdout) - console_handler.setLevel(logging.INFO) + if not _logger.handlers: + console_handler = logging.StreamHandler(sys.stdout) + _logger.addHandler(console_handler) + else: + console_handler = _logger.handlers[0] + console_handler.setLevel(level) - # 设置日志格式 formatter = logging.Formatter( - '%(asctime)s - %(name)s - %(levelname)s - %(message)s', - datefmt='%Y-%m-%d %H:%M:%S' + "%(asctime)s - %(name)s - %(levelname)s - %(message)s", + datefmt="%Y-%m-%d %H:%M:%S", ) console_handler.setFormatter(formatter) - # 添加处理器到logger - _logger.addHandler(console_handler) - return _logger diff --git a/core/storage.py b/core/storage.py index 16630dd..daf14a7 100644 --- a/core/storage.py +++ b/core/storage.py @@ -259,14 +259,14 @@ class SystemFileStorage(FileStorageInterface): try: shutil.rmtree(chunk_dir) except Exception as e: - logger.info(f"清理本地分片目录失败: {e}") + logger.warning(f"清理本地分片目录失败: {e}") # 清理父级 chunks 目录(如果为空) chunks_parent = chunk_dir.parent if chunks_parent.exists() and not any(chunks_parent.iterdir()): try: chunks_parent.rmdir() except Exception as e: - logger.info(f"清理 chunks 父目录失败: {e}") + logger.warning(f"清理 chunks 父目录失败: {e}") async def file_exists(self, save_path: str) -> bool: """ @@ -537,7 +537,7 @@ class S3FileStorage(FileStorageInterface): Delete={'Objects': delete_objects} ) except Exception as e: - logger.info(f"清理 S3 分片数据时出错: {e}") + logger.warning(f"清理 S3 分片数据时出错: {e}") async def generate_presigned_upload_url(self, save_path: str, expires_in: int = 900) -> Optional[str]: """ @@ -865,7 +865,7 @@ class OneDriveFileStorage(FileStorageInterface): try: await asyncio.to_thread(self._delete_chunk_dir, chunk_dir) except Exception as e: - logger.info(f"清理 OneDrive 分片时出错: {e}") + logger.warning(f"清理 OneDrive 分片时出错: {e}") def _file_exists(self, save_path: str) -> bool: """同步检查文件是否存在""" @@ -1023,7 +1023,7 @@ class OpenDALFileStorage(FileStorageInterface): # OpenDAL 支持递归删除 await self.operator.remove_all(chunk_dir) except Exception as e: - logger.info(f"清理 OpenDAL 分片时出错: {e}") + logger.warning(f"清理 OpenDAL 分片时出错: {e}") async def file_exists(self, save_path: str) -> bool: """ @@ -1334,16 +1334,16 @@ class WebDAVFileStorage(FileStorageInterface): file_url = self._build_url(file_path) async with session.delete(file_url) as delete_resp: if delete_resp.status not in (200, 204, 404): - logger.info(f"删除分片文件失败: {file_path}") + logger.warning(f"删除分片文件失败: {file_path}") # 删除分片目录 async with session.delete(chunk_dir_url) as delete_resp: if delete_resp.status not in (200, 204, 404): - logger.info(f"删除分片目录失败: {chunk_dir_url}") + logger.warning(f"删除分片目录失败: {chunk_dir_url}") else: logger.info(f"分片目录不存在: {chunk_dir_url}") except Exception as e: - logger.info(f"清理 WebDAV 分片时出错: {e}") + logger.warning(f"清理 WebDAV 分片时出错: {e}") async def file_exists(self, save_path: str) -> bool: """ diff --git a/core/tasks.py b/core/tasks.py index f3da97f..bb57d5f 100644 --- a/core/tasks.py +++ b/core/tasks.py @@ -4,7 +4,6 @@ # @Software: PyCharm import asyncio import datetime -import logging import os from tortoise.expressions import Q @@ -17,6 +16,7 @@ from apps.base.models import ( ) from apps.base.utils import ip_limit, get_chunk_file_path_name from core.config import refresh_settings +from core.logger import logger from core.settings import settings, data_root from core.storage import FileStorageInterface, storages from core.utils import get_now @@ -43,13 +43,13 @@ async def delete_expire_files(): try: await file_storage.delete_file(exp) except Exception as e: - logging.error(f"删除过期文件失败 code={exp.code}: {e}") + logger.error(f"删除过期文件失败 code={exp.code}: {e}") try: await exp.delete() except Exception as e: - logging.error(f"删除记录失败 code={exp.code}: {e}") + logger.error(f"删除记录失败 code={exp.code}: {e}") except Exception as e: - logging.error(e) + logger.error(e) finally: await asyncio.sleep(600) @@ -75,7 +75,7 @@ async def clean_incomplete_uploads(): ) await file_storage.clean_chunks(session.upload_id, save_path) except Exception as e: - logging.error( + logger.error( f"清理分片文件失败 upload_id={session.upload_id}: {e}" ) @@ -84,14 +84,14 @@ async def clean_incomplete_uploads(): await StorageReservation.filter( token=f"chunk:{session.upload_id}" ).delete() - logging.info(f"已清理过期上传会话 upload_id={session.upload_id}") + logger.info(f"已清理过期上传会话 upload_id={session.upload_id}") except Exception as e: - logging.error( + logger.error( f"删除分片记录失败 upload_id={session.upload_id}: {e}" ) except Exception as e: - logging.error(f"清理未完成上传任务异常: {e}") + logger.error(f"清理未完成上传任务异常: {e}") finally: await asyncio.sleep(3600) @@ -116,7 +116,7 @@ async def clean_expired_presign_sessions(): ) ) except Exception as e: - logging.error( + logger.error( "清理过期直传文件失败 " f"upload_id={session.upload_id}: {e}" ) @@ -125,6 +125,6 @@ async def clean_expired_presign_sessions(): ).delete() await session.delete() except Exception as e: - logging.error(f"清理过期预签名会话异常: {e}") + logger.error(f"清理过期预签名会话异常: {e}") finally: await asyncio.sleep(900) diff --git a/docker-compose.yml b/docker-compose.yml index 7a7e9ec..858b3a9 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -7,6 +7,16 @@ services: restart: unless-stopped ports: - "12345:12345" + environment: + - APP_ENV=production + - LOG_LEVEL=warning + - ACCESS_LOG=false + - WORKERS=1 + logging: + driver: json-file + options: + max-size: "10m" + max-file: "3" volumes: fcb-data: external: false diff --git a/docs/en/guide/getting-started.md b/docs/en/guide/getting-started.md index 7c23548..2c04e90 100644 --- a/docs/en/guide/getting-started.md +++ b/docs/en/guide/getting-started.md @@ -21,6 +21,10 @@ FileCodeBox is a simple and efficient file sharing tool that supports temporary docker run -d --restart unless-stopped \ -p 12345:12345 \ -v fcb-data:/app/data \ + -e APP_ENV=production \ + -e LOG_LEVEL=warning \ + --log-opt max-size=10m \ + --log-opt max-file=3 \ --name filecodebox \ lanol/filecodebox:latest ``` @@ -32,7 +36,11 @@ The named volume persists configuration and uploaded files across container upgr | `HOST` | `0.0.0.0` | Service listening address | | `PORT` | `12345` | Service port | | `WORKERS` | `1` | Worker count; keep one worker for SQLite deployments | -| `LOG_LEVEL` | `info` | `debug`, `info`, `warning`, or `error` | +| `APP_ENV` | `production` (Docker) | Runtime environment; production disables HTTP access logs by default | +| `LOG_LEVEL` | `warning` (Docker) | `debug`, `info`, `warning`, or `error` | +| `ACCESS_LOG` | `false` (production) | Enable HTTP access logs; set to `true` when debugging requests | + +Production deployments output only warning, error, and other key events by default. Docker retains at most three 10 MB log files. ### Manual Deployment diff --git a/docs/en/guide/introduction.md b/docs/en/guide/introduction.md index 4808f33..e2a2779 100644 --- a/docs/en/guide/introduction.md +++ b/docs/en/guide/introduction.md @@ -136,7 +136,15 @@ Command-line download ### Docker Deployment ```bash -docker run -d --restart unless-stopped -p 12345:12345 -v fcb-data:/app/data --name filecodebox lanol/filecodebox:latest +docker run -d --restart unless-stopped \ + -p 12345:12345 \ + -v fcb-data:/app/data \ + -e APP_ENV=production \ + -e LOG_LEVEL=warning \ + --log-opt max-size=10m \ + --log-opt max-file=3 \ + --name filecodebox \ + lanol/filecodebox:latest ``` ### Manual Deployment diff --git a/docs/en/index.md b/docs/en/index.md index 7999b1a..d193bd4 100644 --- a/docs/en/index.md +++ b/docs/en/index.md @@ -37,6 +37,10 @@ features: docker run -d --restart unless-stopped \ -p 12345:12345 \ -v ./data:/app/data \ + -e APP_ENV=production \ + -e LOG_LEVEL=warning \ + --log-opt max-size=10m \ + --log-opt max-file=3 \ --name filecodebox \ lanol/filecodebox:2.5.5 # x-release-please-version ``` diff --git a/docs/guide/getting-started.md b/docs/guide/getting-started.md index e7eb7e9..7d40d96 100644 --- a/docs/guide/getting-started.md +++ b/docs/guide/getting-started.md @@ -23,6 +23,10 @@ FileCodeBox 是一个简单高效的文件分享工具,支持文件临时中 docker run -d --restart unless-stopped \ -p 12345:12345 \ -v fcb-data:/app/data \ + -e APP_ENV=production \ + -e LOG_LEVEL=warning \ + --log-opt max-size=10m \ + --log-opt max-file=3 \ --name filecodebox \ lanol/filecodebox:latest ``` @@ -40,8 +44,15 @@ services: ports: - "12345:12345" environment: + - APP_ENV=production - WORKERS=1 - - LOG_LEVEL=info + - LOG_LEVEL=warning + - ACCESS_LOG=false + logging: + driver: json-file + options: + max-size: "10m" + max-file: "3" volumes: fcb-data: external: false @@ -54,7 +65,11 @@ volumes: | `HOST` | `0.0.0.0` | 服务监听地址 | | `PORT` | `12345` | 服务端口 | | `WORKERS` | `1` | 工作进程数;SQLite 部署建议保持单进程 | -| `LOG_LEVEL` | `info` | 日志级别:debug/info/warning/error | +| `APP_ENV` | `production`(Docker) | 运行环境;生产环境默认关闭 HTTP 访问日志 | +| `LOG_LEVEL` | `warning`(Docker) | 日志级别:debug/info/warning/error | +| `ACCESS_LOG` | `false`(生产环境) | 是否启用 HTTP 访问日志;调试请求时可设为 `true` | + +生产环境默认只输出 warning、error 等关键日志,并限制 Docker 日志最多保留 3 个 10 MB 文件。 #### 自定义配置示例 @@ -63,8 +78,11 @@ docker run -d --restart=always \ -p 12345:12345 \ -v fcb-data:/app/data \ -e WORKERS=1 \ + -e APP_ENV=production \ -e LOG_LEVEL=warning \ --name filecodebox \ + --log-opt max-size=10m \ + --log-opt max-file=3 \ lanol/filecodebox:latest ``` diff --git a/docs/guide/introduction.md b/docs/guide/introduction.md index 9b9e157..cda9cf9 100644 --- a/docs/guide/introduction.md +++ b/docs/guide/introduction.md @@ -150,7 +150,15 @@ FileCodeBox 是一个基于 FastAPI + Vue3 开发的轻量级文件分享工具 ### Docker 部署 ```bash -docker run -d --restart unless-stopped -p 12345:12345 -v fcb-data:/app/data --name filecodebox lanol/filecodebox:latest +docker run -d --restart unless-stopped \ + -p 12345:12345 \ + -v fcb-data:/app/data \ + -e APP_ENV=production \ + -e LOG_LEVEL=warning \ + --log-opt max-size=10m \ + --log-opt max-file=3 \ + --name filecodebox \ + lanol/filecodebox:latest ``` ### 手动部署 diff --git a/docs/index.md b/docs/index.md index 8d1f39d..f7d2221 100644 --- a/docs/index.md +++ b/docs/index.md @@ -37,6 +37,10 @@ features: docker run -d --restart unless-stopped \ -p 12345:12345 \ -v ./data:/app/data \ + -e APP_ENV=production \ + -e LOG_LEVEL=warning \ + --log-opt max-size=10m \ + --log-opt max-file=3 \ --name filecodebox \ lanol/filecodebox:2.5.5 # x-release-please-version ``` diff --git a/main.py b/main.py index aa0c120..f916683 100644 --- a/main.py +++ b/main.py @@ -26,7 +26,7 @@ from core.config import ( refresh_settings, ) from core.database import db_startup_lock, get_db_config, init_db -from core.logger import logger +from core.logger import get_log_level_name, is_access_log_enabled, logger from core.response import APIResponse from core.settings import settings, BASE_DIR, DEFAULT_CONFIG from core.tasks import ( @@ -933,4 +933,6 @@ if __name__ == "__main__": port=settings.serverPort, reload=False, workers=settings.serverWorkers, + log_level=get_log_level_name(), + access_log=is_access_log_enabled(), ) diff --git a/readme.md b/readme.md index 4dd734f..4853bef 100644 --- a/readme.md +++ b/readme.md @@ -24,7 +24,15 @@ ## 一条命令开始 ```bash -docker run -d --restart unless-stopped -p 12345:12345 -v ./data:/app/data --name filecodebox lanol/filecodebox:2.5.5 # x-release-please-version +docker run -d --restart unless-stopped \ + -p 12345:12345 \ + -v ./data:/app/data \ + -e APP_ENV=production \ + -e LOG_LEVEL=warning \ + --log-opt max-size=10m \ + --log-opt max-file=3 \ + --name filecodebox \ + lanol/filecodebox:2.5.5 # x-release-please-version ``` 访问 `http://localhost:12345`,完成首次初始化。生产环境建议固定版本号;`latest` 指向最新正式版。 diff --git a/readme_en.md b/readme_en.md index cb100eb..dc8e1b5 100644 --- a/readme_en.md +++ b/readme_en.md @@ -24,7 +24,15 @@ A lightweight, modern, self-hosted file sharing service. No account required—u ## Start with one command ```bash -docker run -d --restart unless-stopped -p 12345:12345 -v ./data:/app/data --name filecodebox lanol/filecodebox:2.5.5 # x-release-please-version +docker run -d --restart unless-stopped \ + -p 12345:12345 \ + -v ./data:/app/data \ + -e APP_ENV=production \ + -e LOG_LEVEL=warning \ + --log-opt max-size=10m \ + --log-opt max-file=3 \ + --name filecodebox \ + lanol/filecodebox:2.5.5 # x-release-please-version ``` Open `http://localhost:12345` and complete first-run setup. Pin a version in production; `latest` tracks the newest stable release. diff --git a/tests/test_logging.py b/tests/test_logging.py new file mode 100644 index 0000000..d058fc1 --- /dev/null +++ b/tests/test_logging.py @@ -0,0 +1,60 @@ +import importlib +import logging +import os +import unittest +from pathlib import Path +from unittest.mock import patch + +import core.logger as logger_module + + +class LoggingConfigurationTests(unittest.TestCase): + def setUp(self): + self.environment_patch = None + + def tearDown(self): + if self.environment_patch is not None: + self.environment_patch.stop() + importlib.reload(logger_module) + + def reload_with_environment(self, values): + self.environment_patch = patch.dict(os.environ, values, clear=True) + self.environment_patch.start() + return importlib.reload(logger_module) + + def test_production_defaults_to_warning_and_disables_access_logs(self): + module = self.reload_with_environment({"APP_ENV": "production"}) + + self.assertEqual(module.get_log_level_name(), "warning") + self.assertEqual(module.logger.level, logging.WARNING) + self.assertFalse(module.is_access_log_enabled()) + + def test_development_defaults_to_info_and_keeps_access_logs(self): + module = self.reload_with_environment({"APP_ENV": "development"}) + + self.assertEqual(module.get_log_level_name(), "info") + self.assertEqual(module.logger.level, logging.INFO) + self.assertTrue(module.is_access_log_enabled()) + + def test_explicit_log_and_access_settings_override_environment_defaults(self): + module = self.reload_with_environment( + {"APP_ENV": "production", "LOG_LEVEL": "error", "ACCESS_LOG": "true"} + ) + + self.assertEqual(module.get_log_level_name(), "error") + self.assertEqual(module.logger.level, logging.ERROR) + self.assertTrue(module.is_access_log_enabled()) + + def test_log_file_configuration_is_bounded_in_docker_compose(self): + compose = Path("docker-compose.yml").read_text(encoding="utf-8") + dockerfile = Path("Dockerfile").read_text(encoding="utf-8") + + self.assertIn('max-size: "10m"', compose) + self.assertIn('max-file: "3"', compose) + self.assertIn('APP_ENV="production"', dockerfile) + self.assertIn('LOG_LEVEL="warning"', dockerfile) + self.assertIn("--no-access-log", dockerfile) + + +if __name__ == "__main__": + unittest.main()