优化日志清理策略

This commit is contained in:
sky22333
2026-04-22 00:32:31 +08:00
parent a0a8dd0e31
commit 7e06ef67e7
3 changed files with 22 additions and 9 deletions

19
app.py
View File

@@ -17,6 +17,7 @@ import hashlib
import jwt
import datetime
import logging
from logging.handlers import RotatingFileHandler
from crypto_utils import CryptoUtils, set_crypto_keys, derive_key_from_credentials
def get_client_ip():
@@ -800,7 +801,7 @@ def get_access_logs():
def cleanup_logs():
"""清理旧日志"""
db.cleanup_old_logs()
return jsonify({'message': '已清理7天前的日志'})
return jsonify({'message': '已清理3天前的访问日志和命令日志'})
def create_required_directories():
"""创建必要的目录"""
@@ -1008,10 +1009,18 @@ def execute_playbook():
if __name__ == '__main__':
create_required_directories()
logging.basicConfig(
filename='logs/app.log',
level=logging.INFO,
format='%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'
file_handler = RotatingFileHandler(
'logs/app.log',
maxBytes=1_048_576,
backupCount=3,
)
file_handler.setFormatter(logging.Formatter(
'%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'
))
root_logger = logging.getLogger()
root_logger.setLevel(logging.INFO)
root_logger.handlers.clear()
root_logger.addHandler(file_handler)
app.run(host='0.0.0.0', port=5000)

View File

@@ -248,9 +248,13 @@ class Database:
return [dict(row) for row in cursor.fetchall()]
def cleanup_old_logs(self):
"""清理7天前的日志(使用北京时间)"""
"""清理3天前的访问日志和命令日志(使用北京时间)"""
with self.get_connection() as conn:
conn.execute("""
DELETE FROM access_logs
WHERE access_time < datetime('now', '+8 hours', '-7 days')
WHERE access_time < datetime('now', '+8 hours', '-3 days')
""")
conn.execute("""
DELETE FROM command_logs
WHERE datetime(executed_at, '+8 hours') < datetime('now', '+8 hours', '-3 days')
""")

View File

@@ -318,7 +318,7 @@ function MainPage() {
};
const handleCleanupAccessLogs = async () => {
if (!confirm('确定要清理7天前的访问日志吗?')) return;
if (!confirm('确定要清理3天前的访问日志和命令日志吗?')) return;
try {
const response = await api.post('/api/access-logs/cleanup');
toast.success("成功", { description: response.data.message });
@@ -420,7 +420,7 @@ function MainPage() {
</div>
</div>
<SheetFooter>
<Button variant="outline" onClick={handleCleanupAccessLogs} className="text-black dark:text-white">7</Button>
<Button variant="outline" onClick={handleCleanupAccessLogs} className="text-black dark:text-white">3</Button>
<SheetClose asChild>
<Button variant="outline"></Button>
</SheetClose>