from datetime import datetime import pytz from db import user_token_in_db_func moscow_tz = pytz.timezone('Europe/Moscow') async def log(session, user_token, message): user_token_db = await user_token_in_db_func(session, user_token) log_message = f"{[datetime.now(moscow_tz).strftime('%Y-%m-%d %H:%M %Z')]} {message}" user_token_db.logs = await append_line_with_limit(user_token_db.logs, log_message) session.add(user_token_db) await session.commit() await session.refresh(user_token_db) async def append_line_with_limit(text, new_line, max_lines = 5000) -> str: """ Append a new line to the text and maintain a maximum number of lines. When exceeding the limit, the oldest line is removed. Args: text: The existing text new_line: The line to append max_lines: Maximum number of lines to keep Returns: Updated text with the new line appended """ # Split text into lines lines = text.splitlines() if text else [] # Append the new line lines.append(new_line) # If we exceed the maximum lines, remove the oldest (first) line if len(lines) > max_lines: lines.pop(0) # Join lines back together with newlines return '\n'.join(lines)