From e61d0b7d03fc9a71d5d7b9304d0f134423d38392 Mon Sep 17 00:00:00 2001 From: xuehuitian45 <13069167198@163.com> Date: Mon, 29 Dec 2025 14:21:29 +0800 Subject: [PATCH 1/2] fix: unify logger to slf4j --- .../agents/agentscope/tools/ToolkitInit.java | 9 +- .../memory/service/Mem0MemoryService.java | 39 ++-- .../memory/service/RedisMemoryService.java | 7 +- .../service/SimpleEmbeddingService.java | 11 +- .../service/TableStoreMemoryService.java | 20 +- .../InMemorySessionHistoryService.java | 8 +- .../TableStoreSessionHistoryService.java | 25 ++- .../runtime/engine/shared/ServiceManager.java | 20 +- .../runtime/sandbox/box/AgentBaySandbox.java | 42 ++-- .../runtime/sandbox/box/DummySandbox.java | 13 +- .../runtime/sandbox/box/MobileSandbox.java | 7 +- .../runtime/sandbox/box/Sandbox.java | 21 +- .../sandbox/manager/SandboxManager.java | 192 +++++++++--------- .../manager/client/AgentBayClient.java | 33 +-- .../manager/client/AgentRunClient.java | 122 ++++++----- .../sandbox/manager/client/DockerClient.java | 112 +++++----- .../sandbox/manager/client/FcClient.java | 105 +++++----- .../manager/client/KubernetesClient.java | 120 ++++++----- .../collections/RedisContainerMapping.java | 31 +-- .../collections/RedisContainerQueue.java | 24 +-- .../manager/model/container/SandboxKey.java | 8 +- .../registry/SandboxAnnotationProcessor.java | 53 +++-- .../manager/registry/SandboxRegistry.java | 25 +-- .../registry/SandboxRegistryInitializer.java | 20 +- .../registry/SandboxRegistryService.java | 25 +-- .../manager/remote/RemoteHttpClient.java | 25 +-- .../sandbox/manager/util/PortManager.java | 20 +- .../manager/util/RedisClientWrapper.java | 9 +- .../manager/util/SandboxHttpClient.java | 20 +- .../sandbox/manager/util/StorageManager.java | 61 +++--- .../manager/util/TrainingSandboxClient.java | 90 ++++---- .../runtime/sandbox/tools/MCPTool.java | 12 +- .../sandbox/tools/McpConfigConverter.java | 19 +- .../sandbox/tools/base/RunPythonTool.java | 11 +- .../tools/base/RunShellCommandTool.java | 14 +- .../sandbox/tools/browser/ClickTool.java | 8 +- .../sandbox/tools/browser/CloseTool.java | 8 +- .../tools/browser/ConsoleMessagesTool.java | 8 +- .../sandbox/tools/browser/DragTool.java | 8 +- .../sandbox/tools/browser/FileUploadTool.java | 11 +- .../tools/browser/HandleDialogTool.java | 11 +- .../sandbox/tools/browser/HoverTool.java | 8 +- .../tools/browser/NavigateBackTool.java | 8 +- .../tools/browser/NavigateForwardTool.java | 8 +- .../sandbox/tools/browser/NavigateTool.java | 11 +- .../tools/browser/NetworkRequestsTool.java | 8 +- .../sandbox/tools/browser/PdfSaveTool.java | 8 +- .../sandbox/tools/browser/PressKeyTool.java | 11 +- .../sandbox/tools/browser/ResizeTool.java | 8 +- .../tools/browser/SelectOptionTool.java | 8 +- .../sandbox/tools/browser/SnapshotTool.java | 8 +- .../sandbox/tools/browser/TabCloseTool.java | 8 +- .../sandbox/tools/browser/TabListTool.java | 8 +- .../sandbox/tools/browser/TabNewTool.java | 8 +- .../sandbox/tools/browser/TabSelectTool.java | 11 +- .../tools/browser/TakeScreenshotTool.java | 8 +- .../sandbox/tools/browser/TypeTool.java | 8 +- .../sandbox/tools/browser/WaitForTool.java | 8 +- .../sandbox/tools/fs/CreateDirectoryTool.java | 11 +- .../sandbox/tools/fs/DirectoryTreeTool.java | 11 +- .../sandbox/tools/fs/EditFileTool.java | 8 +- .../sandbox/tools/fs/GetFileInfoTool.java | 11 +- .../tools/fs/ListAllowedDirectoriesTool.java | 8 +- .../sandbox/tools/fs/ListDirectoryTool.java | 11 +- .../sandbox/tools/fs/MoveFileTool.java | 8 +- .../sandbox/tools/fs/ReadFileTool.java | 11 +- .../tools/fs/ReadMultipleFilesTool.java | 11 +- .../sandbox/tools/fs/SearchFilesTool.java | 8 +- .../sandbox/tools/fs/WriteFileTool.java | 8 +- .../runtime/LocalDeployManager.java | 12 +- .../controller/SandboxManagerController.java | 27 ++- .../protocol/a2a/GraphAgentExecutor.java | 27 +-- .../a2a/controller/A2aController.java | 9 +- .../responseapi/ResponseApiHandler.java | 14 +- .../controller/ResponseApiController.java | 6 +- 75 files changed, 875 insertions(+), 898 deletions(-) diff --git a/agents/agentscope/src/main/java/io/agentscope/runtime/engine/agents/agentscope/tools/ToolkitInit.java b/agents/agentscope/src/main/java/io/agentscope/runtime/engine/agents/agentscope/tools/ToolkitInit.java index b6c267a1..cf79c9ba 100644 --- a/agents/agentscope/src/main/java/io/agentscope/runtime/engine/agents/agentscope/tools/ToolkitInit.java +++ b/agents/agentscope/src/main/java/io/agentscope/runtime/engine/agents/agentscope/tools/ToolkitInit.java @@ -27,15 +27,16 @@ import io.agentscope.runtime.sandbox.manager.model.container.SandboxType; import io.agentscope.runtime.sandbox.tools.MCPTool; import io.agentscope.runtime.sandbox.tools.McpConfigConverter; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; -import java.util.logging.Logger; public class ToolkitInit { - private static final Logger logger = Logger.getLogger(ToolkitInit.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(ToolkitInit.class); public static List getAllTools(Sandbox sandbox) { return List.of( @@ -421,10 +422,10 @@ private static List buildMcpAgentTools(McpConfigConverter converter) agentTools.add(new AsMCPTool(mcpTool)); } - logger.info(String.format("Created %d MCP tools", agentTools.size())); + logger.info("Created {} MCP tools", agentTools.size()); return agentTools; } catch (Exception e) { - logger.severe("Failed to create MCP tools: " + e.getMessage()); + logger.error("Failed to create MCP tools: {}", e.getMessage()); throw new RuntimeException("Failed to create MCP tools", e); } } diff --git a/core/src/main/java/io/agentscope/runtime/engine/services/memory/persistence/memory/service/Mem0MemoryService.java b/core/src/main/java/io/agentscope/runtime/engine/services/memory/persistence/memory/service/Mem0MemoryService.java index 00b60dbf..b2c39bdb 100755 --- a/core/src/main/java/io/agentscope/runtime/engine/services/memory/persistence/memory/service/Mem0MemoryService.java +++ b/core/src/main/java/io/agentscope/runtime/engine/services/memory/persistence/memory/service/Mem0MemoryService.java @@ -25,7 +25,6 @@ import java.util.Optional; import java.util.Set; import java.util.concurrent.CompletableFuture; -import java.util.logging.Logger; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; @@ -45,6 +44,8 @@ import org.apache.hc.core5.http.ContentType; import org.apache.hc.core5.http.io.entity.EntityUtils; import org.apache.hc.core5.http.io.entity.StringEntity; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Mem0-based implementation of memory service @@ -53,7 +54,7 @@ */ public class Mem0MemoryService implements MemoryService { - private static final Logger logger = Logger.getLogger(Mem0MemoryService.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(Mem0MemoryService.class); private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); private static final String MEM0_API_BASE_URL = "https://api.mem0.ai"; private static final String API_VERSION_V1 = "v1"; @@ -104,7 +105,7 @@ public CompletableFuture stop() { } logger.info("Mem0 memory service stopped"); } catch (Exception e) { - logger.severe("Failed to close HTTP client: " + e.getMessage()); + logger.error("Failed to close HTTP client: {}", e.getMessage()); } }); } @@ -134,7 +135,7 @@ public CompletableFuture health() { return response.getCode() == 200; } } catch (Exception e) { - logger.severe("Mem0 memory service health check failed: " + e.getMessage()); + logger.error("Mem0 memory service health check failed: {}", e.getMessage()); return false; } }); @@ -180,14 +181,14 @@ public CompletableFuture addMemory(String userId, List messages, try (CloseableHttpResponse response = httpClient.execute(request)) { int statusCode = response.getCode(); if (statusCode >= 200 && statusCode < 300) { - logger.fine("Added " + messages.size() + " messages to Mem0 for user: " + userId); + logger.info("Added {} messages to Mem0 for user: {}", messages.size(), userId); } else { String responseBody = EntityUtils.toString(response.getEntity()); - logger.warning("Failed to add memory: " + statusCode + " - " + responseBody); + logger.warn("Failed to add memory: {} - {}", statusCode, responseBody); } } } catch (Exception e) { - logger.severe("Failed to add memory: " + e.getMessage()); + logger.error("Failed to add memory: {}", e.getMessage()); throw new RuntimeException("Failed to add memory", e); } }); @@ -272,12 +273,12 @@ public CompletableFuture> searchMemory(String userId, List> listMemory(String userId, Optional deleteMemory(String userId, Optional sess try (CloseableHttpResponse deleteResponse = httpClient.execute(deleteRequest)) { if (deleteResponse.getCode() >= 200 && deleteResponse.getCode() < 300) { - logger.fine("Deleted memory: " + memoryId); + logger.info("Deleted memory: {}", memoryId); } else { String responseBody = EntityUtils.toString(deleteResponse.getEntity()); - logger.warning("Failed to delete memory " + memoryId + ": " + deleteResponse.getCode() + " - " + responseBody); + logger.warn("Failed to delete memory {}: {} - {}", memoryId, deleteResponse.getCode(), responseBody); } } } String sessionInfo = sessionId.map(s -> ", session: " + s).orElse(""); - logger.fine("Deleted " + memoryIds.size() + " memories for user: " + userId + sessionInfo); + logger.info("Deleted {} memories for user: {}{}", memoryIds.size(), userId, sessionInfo); } catch (Exception e) { - logger.severe("Failed to delete memory: " + e.getMessage()); + logger.error("Failed to delete memory: {}", e.getMessage()); throw new RuntimeException("Failed to delete memory", e); } }); @@ -462,12 +463,12 @@ public CompletableFuture> getAllUsers() { } return new ArrayList<>(userIds); } else { - logger.warning("Failed to get all users: " + response.getCode() + " - " + responseBody); + logger.warn("Failed to get all users: {} - {}", response.getCode(), responseBody); return Collections.emptyList(); } } } catch (Exception e) { - logger.severe("Failed to get all users: " + e.getMessage()); + logger.error("Failed to get all users: {}", e.getMessage()); return Collections.emptyList(); } }); @@ -544,7 +545,7 @@ private List parseSearchResponse(String responseBody) { } return messages; } catch (Exception e) { - logger.severe("Failed to parse search response: " + e.getMessage()); + logger.error("Failed to parse search response: {}", e.getMessage()); return Collections.emptyList(); } } @@ -569,7 +570,7 @@ private List parseListResponse(String responseBody) { } return messages; } catch (Exception e) { - logger.severe("Failed to parse list response: " + e.getMessage()); + logger.error("Failed to parse list response: {}", e.getMessage()); return Collections.emptyList(); } } diff --git a/core/src/main/java/io/agentscope/runtime/engine/services/memory/persistence/memory/service/RedisMemoryService.java b/core/src/main/java/io/agentscope/runtime/engine/services/memory/persistence/memory/service/RedisMemoryService.java index 758934d6..a9913bdc 100755 --- a/core/src/main/java/io/agentscope/runtime/engine/services/memory/persistence/memory/service/RedisMemoryService.java +++ b/core/src/main/java/io/agentscope/runtime/engine/services/memory/persistence/memory/service/RedisMemoryService.java @@ -15,6 +15,8 @@ */ package io.agentscope.runtime.engine.services.memory.persistence.memory.service; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.data.redis.core.HashOperations; import org.springframework.data.redis.core.RedisTemplate; @@ -27,7 +29,6 @@ import java.util.Optional; import java.util.Set; import java.util.concurrent.CompletableFuture; -import java.util.logging.Logger; import java.util.stream.Collectors; import com.fasterxml.jackson.core.JsonProcessingException; @@ -41,7 +42,7 @@ * Redis-based memory service implementation */ public class RedisMemoryService implements MemoryService { - Logger logger = Logger.getLogger(RedisMemoryService.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(MemoryService.class); private final RedisTemplate redisTemplate; private final ObjectMapper objectMapper; @@ -128,7 +129,7 @@ public CompletableFuture> searchMemory(String userId, List keywords = Arrays.stream(query.toLowerCase().split("\\s+")) .collect(Collectors.toSet()); - logger.info("keywords: "+keywords); + logger.info("keywords: {}", keywords); HashOperations hashOps = redisTemplate.opsForHash(); Map allFields = hashOps.entries(key); diff --git a/core/src/main/java/io/agentscope/runtime/engine/services/memory/persistence/memory/service/SimpleEmbeddingService.java b/core/src/main/java/io/agentscope/runtime/engine/services/memory/persistence/memory/service/SimpleEmbeddingService.java index d82c357a..c4a0f636 100755 --- a/core/src/main/java/io/agentscope/runtime/engine/services/memory/persistence/memory/service/SimpleEmbeddingService.java +++ b/core/src/main/java/io/agentscope/runtime/engine/services/memory/persistence/memory/service/SimpleEmbeddingService.java @@ -23,12 +23,13 @@ import java.util.Map; import java.util.Set; import java.util.concurrent.CompletableFuture; -import java.util.logging.Logger; import java.util.stream.Collectors; import io.agentscope.runtime.engine.services.memory.service.EmbeddingService; import org.apache.commons.math3.linear.ArrayRealVector; import org.apache.commons.math3.linear.RealVector; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Simple text embedding service implementation @@ -36,7 +37,7 @@ */ public class SimpleEmbeddingService implements EmbeddingService { - Logger logger = Logger.getLogger(SimpleEmbeddingService.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(SimpleEmbeddingService.class); private static final int EMBEDDING_DIMENSION = 300; // Fixed dimension private final Map vocabulary = new HashMap<>(); @@ -68,7 +69,7 @@ public CompletableFuture> embedText(String text) { return embedding; } catch (Exception e) { - logger.severe("Failed to generate text embedding" + e.getMessage()); + logger.error("Failed to generate text embedding{}", e.getMessage()); return createZeroVector(); } }); @@ -95,7 +96,7 @@ public double cosineSimilarity(List vector1, List vector2) { return dotProduct / (norm1 * norm2); } catch (Exception e) { - logger.severe("Failed to compute cosine similarity" + e.getMessage()); + logger.error("Failed to compute cosine similarity{}", e.getMessage()); return 0.0; } } @@ -113,7 +114,7 @@ public double euclideanDistance(List vector1, List vector2) { return v1.getDistance(v2); } catch (Exception e) { - logger.severe("Failed to compute Euclidean distance" + e.getMessage()); + logger.error("Failed to compute Euclidean distance{}", e.getMessage()); return Double.MAX_VALUE; } } diff --git a/core/src/main/java/io/agentscope/runtime/engine/services/memory/persistence/memory/service/TableStoreMemoryService.java b/core/src/main/java/io/agentscope/runtime/engine/services/memory/persistence/memory/service/TableStoreMemoryService.java index 0a7d832d..e1b83c5d 100755 --- a/core/src/main/java/io/agentscope/runtime/engine/services/memory/persistence/memory/service/TableStoreMemoryService.java +++ b/core/src/main/java/io/agentscope/runtime/engine/services/memory/persistence/memory/service/TableStoreMemoryService.java @@ -25,7 +25,6 @@ import java.util.Set; import java.util.UUID; import java.util.concurrent.CompletableFuture; -import java.util.logging.Logger; import java.util.stream.Collectors; import com.alicloud.openservices.tablestore.SyncClient; @@ -42,6 +41,8 @@ import io.agentscope.runtime.engine.schemas.Message; import io.agentscope.runtime.engine.schemas.TextContent; import io.agentscope.runtime.engine.services.memory.service.MemoryService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * TableStore-based implementation of memory service @@ -49,7 +50,7 @@ */ public class TableStoreMemoryService implements MemoryService { - private static final Logger logger = Logger.getLogger(TableStoreMemoryService.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(MemoryService.class); private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); private static final String DEFAULT_SESSION_ID = "default"; @@ -96,7 +97,7 @@ public CompletableFuture start() { .build(); knowledgeStore.initTable(); - logger.info("TableStore memory service started with table: " + tableName); + logger.info("TableStore memory service started with table: {}", tableName); }); } @@ -114,7 +115,7 @@ public CompletableFuture stop() { public CompletableFuture health() { return CompletableFuture.supplyAsync(() -> { if (knowledgeStore == null) { - logger.warning("TableStore memory service is not started"); + logger.warn("TableStore memory service is not started"); return false; } @@ -126,7 +127,7 @@ public CompletableFuture health() { knowledgeStore.searchDocuments(request); return true; } catch (Exception e) { - logger.severe("TableStore memory service health check failed: " + e.getMessage()); + logger.error("TableStore memory service health check failed: {}", e.getMessage()); return false; } }); @@ -146,7 +147,7 @@ public CompletableFuture addMemory(String userId, List messages, knowledgeStore.putDocument(document); } - logger.fine("Added " + messages.size() + " messages to TableStore for user: " + userId); + logger.info("Added {} messages to TableStore for user: {}", messages.size(), userId); }); } @@ -258,8 +259,7 @@ public CompletableFuture deleteMemory(String userId, Optional sess knowledgeStore.deleteDocument(hit.getDocument().getDocumentId()); } - logger.fine("Deleted memory for user: " + userId + - (sessionId.isPresent() ? ", session: " + sessionId.get() : "")); + logger.info("Deleted memory for user: {}{}", userId, sessionId.isPresent() ? ", session: " + sessionId.get() : ""); }); } @@ -311,7 +311,7 @@ private Document convertMessageToDocument(Message message, String userId, String metadata.put("message_metadata", metadataJson); } } catch (Exception e) { - logger.severe("Failed to serialize message content: " + e.getMessage()); + logger.error("Failed to serialize message content: {}", e.getMessage()); } document.setMetadata(metadata); @@ -353,7 +353,7 @@ private Message convertDocumentToMessage(Document document) { message.setMetadata(messageMetadata); } } catch (Exception e) { - logger.severe("Failed to deserialize message content: " + e.getMessage()); + logger.error("Failed to deserialize message content: {}", e.getMessage()); } return message; diff --git a/core/src/main/java/io/agentscope/runtime/engine/services/memory/persistence/session/InMemorySessionHistoryService.java b/core/src/main/java/io/agentscope/runtime/engine/services/memory/persistence/session/InMemorySessionHistoryService.java index 2ecd7fa3..cf1e0de3 100755 --- a/core/src/main/java/io/agentscope/runtime/engine/services/memory/persistence/session/InMemorySessionHistoryService.java +++ b/core/src/main/java/io/agentscope/runtime/engine/services/memory/persistence/session/InMemorySessionHistoryService.java @@ -23,19 +23,20 @@ import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; -import java.util.logging.Logger; import java.util.stream.Collectors; import io.agentscope.runtime.engine.schemas.Message; import io.agentscope.runtime.engine.schemas.Session; import io.agentscope.runtime.engine.services.memory.service.SessionHistoryService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * In-memory implementation of session history service * Stores all session data in dictionary, suitable for development, testing and scenarios that don't require persistence */ public class InMemorySessionHistoryService implements SessionHistoryService { - public static Logger logger = Logger.getLogger(InMemorySessionHistoryService.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(InMemorySessionHistoryService.class); private final Map> sessions = new ConcurrentHashMap<>(); @@ -122,8 +123,7 @@ public CompletableFuture appendMessage(Session session, List mess if (existingSession != null) { existingSession.getMessages().addAll(messages); } else { - logger.severe("Warning: Session " + session.getId() + - " not found in storage for append_message."); + logger.error("Warning: Session {} not found in storage for append_message.", session.getId()); } } }); diff --git a/core/src/main/java/io/agentscope/runtime/engine/services/memory/persistence/session/TableStoreSessionHistoryService.java b/core/src/main/java/io/agentscope/runtime/engine/services/memory/persistence/session/TableStoreSessionHistoryService.java index 92109406..706c2b45 100755 --- a/core/src/main/java/io/agentscope/runtime/engine/services/memory/persistence/session/TableStoreSessionHistoryService.java +++ b/core/src/main/java/io/agentscope/runtime/engine/services/memory/persistence/session/TableStoreSessionHistoryService.java @@ -25,7 +25,6 @@ import java.util.Optional; import java.util.UUID; import java.util.concurrent.CompletableFuture; -import java.util.logging.Logger; import com.alicloud.openservices.tablestore.SyncClient; import com.aliyun.openservices.tablestore.agent.memory.MemoryStoreImpl; @@ -38,6 +37,8 @@ import io.agentscope.runtime.engine.schemas.Session; import io.agentscope.runtime.engine.schemas.TextContent; import io.agentscope.runtime.engine.services.memory.service.SessionHistoryService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * TableStore-based implementation of session history service @@ -45,7 +46,7 @@ */ public class TableStoreSessionHistoryService implements SessionHistoryService { - private static final Logger logger = Logger.getLogger(TableStoreSessionHistoryService.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(TableStoreSessionHistoryService.class); private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); private static final String SESSION_SECONDARY_INDEX_NAME = "agentscope_runtime_session_secondary_index"; @@ -109,8 +110,7 @@ public CompletableFuture start() { .build(); memoryStore.initTable(); - logger.info("TableStore session history service started with tables: " + - sessionTableName + ", " + messageTableName); + logger.info("TableStore session history service started with tables: {}, {}", sessionTableName, messageTableName); }); } @@ -128,7 +128,7 @@ public CompletableFuture stop() { public CompletableFuture health() { return CompletableFuture.supplyAsync(() -> { if (memoryStore == null) { - logger.warning("TableStore session history service is not started"); + logger.warn("TableStore session history service is not started"); return false; } @@ -137,7 +137,7 @@ public CompletableFuture health() { memoryStore.listAllSessions(); return true; } catch (Exception e) { - logger.severe("TableStore session history service health check failed: " + e.getMessage()); + logger.error("TableStore session history service health check failed: {}", e.getMessage()); return false; } }); @@ -155,7 +155,7 @@ public CompletableFuture createSession(String userId, Optional memoryStore.putSession(tablestoreSession); Session session = new Session(sid, userId, new ArrayList<>()); - logger.fine("Created session: " + sid + " for user: " + userId); + logger.info("Created session: {} for user: {}", sid, userId); return session; }); @@ -196,7 +196,7 @@ public CompletableFuture> getSession(String userId, String ses public CompletableFuture deleteSession(String userId, String sessionId) { return CompletableFuture.runAsync(() -> { memoryStore.deleteSessionAndMessages(userId, sessionId); - logger.fine("Deleted session: " + sessionId + " for user: " + userId); + logger.info("Deleted session: {} for user: {}", sessionId, userId); }); } @@ -254,10 +254,9 @@ public CompletableFuture appendMessage(Session session, List mess memoryStore.putMessage(tablestoreMessage); } - logger.fine("Appended " + messages.size() + " messages to session: " + session.getId()); + logger.info("Appended {} messages to session: {}", messages.size(), session.getId()); } else { - logger.severe("Warning: Session " + session.getId() + - " not found in TableStore storage for append_message."); + logger.error("Warning: Session {} not found in TableStore storage for append_message.", session.getId()); } }); } @@ -301,7 +300,7 @@ private com.aliyun.openservices.tablestore.agent.model.Message convertMessageToT metadata.put("message_metadata", messageMetadataJson); } } catch (Exception e) { - logger.severe("Failed to serialize message: " + e.getMessage()); + logger.error("Failed to serialize message: {}", e.getMessage()); } tablestoreMessage.setMetadata(metadata); @@ -366,7 +365,7 @@ private Message convertTablestoreMessageToMessage( } } catch (Exception e) { - logger.severe("Failed to deserialize message: " + e.getMessage()); + logger.error("Failed to deserialize message: {}", e.getMessage()); } return message; diff --git a/core/src/main/java/io/agentscope/runtime/engine/shared/ServiceManager.java b/core/src/main/java/io/agentscope/runtime/engine/shared/ServiceManager.java index 732c98a7..39f17bb3 100644 --- a/core/src/main/java/io/agentscope/runtime/engine/shared/ServiceManager.java +++ b/core/src/main/java/io/agentscope/runtime/engine/shared/ServiceManager.java @@ -16,13 +16,15 @@ package io.agentscope.runtime.engine.shared; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; -import java.util.logging.Logger; /** * Abstract base class for service managers @@ -30,7 +32,7 @@ */ public abstract class ServiceManager implements AutoCloseable { - Logger logger = Logger.getLogger(ServiceManager.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(ServiceManager.class); private final List services = new ArrayList<>(); private final Map serviceInstances = new ConcurrentHashMap<>(); @@ -64,7 +66,7 @@ public ServiceManager register(Class serviceClass, String nam } services.add(new ServiceRegistration(serviceClass, name, args)); - logger.info("Registered service: " + name + "(" + serviceClass.getSimpleName() + ")"); + logger.info("Registered service: {}({})", name, serviceClass.getSimpleName()); return this; } @@ -99,9 +101,9 @@ public CompletableFuture start() { .newInstance(); instance.start().get(); serviceInstances.put(registration.name, instance); - logger.info("Successfully started service: " + registration.name); + logger.info("Successfully started service: {}", registration.name); } catch (Exception e) { - logger.severe("Failed to start service: " + registration.name + " - " + e.getMessage()); + logger.error("Failed to start service: {} - {}", registration.name, e.getMessage()); throw new RuntimeException("Failed to start service: " + registration.name, e); } } @@ -114,14 +116,14 @@ public CompletableFuture start() { try { service.start().get(); } catch (Exception e) { - logger.severe("Failed to start pre-instantiated service: " + name + " - " + e.getMessage()); + logger.error("Failed to start pre-instantiated service: {} - {}", name, e.getMessage()); throw new RuntimeException("Failed to start pre-instantiated service: " + name, e); } } } } catch (Exception e) { - logger.severe("Failed to start services" + e.getMessage()); + logger.error("Failed to start services{}", e.getMessage()); // Ensure proper cleanup on initialization failure stop().join(); throw new RuntimeException("Failed to start services", e); @@ -141,7 +143,7 @@ public CompletableFuture stop() { try { service.stop().get(); } catch (Exception e) { - logger.severe("Error stopping service" + e.getMessage()); + logger.error("Error stopping service{}", e.getMessage()); } } serviceInstances.clear(); @@ -207,7 +209,7 @@ public CompletableFuture> healthCheck() { try { healthStatus.put(name, service.health().get()); } catch (Exception e) { - logger.severe("Health check failed for service " + name + " - " + e.getMessage()); + logger.error("Health check failed for service {} - {}", name, e.getMessage()); healthStatus.put(name, false); } } diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/box/AgentBaySandbox.java b/core/src/main/java/io/agentscope/runtime/sandbox/box/AgentBaySandbox.java index b184c643..1ce479dd 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/box/AgentBaySandbox.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/box/AgentBaySandbox.java @@ -29,10 +29,10 @@ import io.agentscope.runtime.sandbox.manager.model.container.ContainerModel; import io.agentscope.runtime.sandbox.manager.model.container.SandboxType; import io.agentscope.runtime.sandbox.manager.registry.RegisterSandbox; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.*; -import java.util.logging.Logger; - @RegisterSandbox( imageName = "agentbay-cloud", @@ -43,7 +43,7 @@ ) public class AgentBaySandbox extends CloudSandbox { - private static final Logger logger = Logger.getLogger(AgentBaySandbox.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(AgentBaySandbox.class); private String imageId; private Map labels; @@ -71,11 +71,9 @@ public AgentBaySandbox(SandboxManager managerApi, String userId, String sessionI ); } this.sandboxId = containerModel.getContainerId(); - logger.info("Sandbox initialized: " + this.sandboxId + - " (type=" + sandboxType + ", user=" + userId + - ", session=" + sessionId + ", autoRelease=" + autoRelease + ")"); + logger.info("Sandbox initialized: {} (type={}, user={}, session={}, autoRelease={})", this.sandboxId, sandboxType, userId, sessionId, autoRelease); } catch (Exception e) { - logger.severe("Failed to initialize sandbox: " + e.getMessage()); + logger.error("Failed to initialize sandbox: {}", e.getMessage()); throw new RuntimeException("Failed to initialize sandbox", e); } } @@ -127,7 +125,7 @@ public Map listTools(String toolType) { public String callCloudTool(String toolName, Map parameters) { Session session = getSession(); if (session == null) { - logger.severe("AgentBay session not found: " + this.sandboxId); + logger.error("AgentBay session not found: {}", this.sandboxId); return "AgentBay session not found: " + this.sandboxId; } if(Objects.equals(toolName, "run_shell_command")){ @@ -184,7 +182,7 @@ public String runIpythonCell(String code) { Session session = getSession(); code = code == null ? "" : code; if (session == null) { - logger.severe("AgentBay session not found: " + this.sandboxId); + logger.error("AgentBay session not found: {}", this.sandboxId); return "AgentBay session not found: " + this.sandboxId; } CodeExecutionResult result = session.getCode().runCode(code, "python"); @@ -203,7 +201,7 @@ public String runShellCommand(String command) { Session session = getSession(); command = command == null ? "" : command; if (session == null) { - logger.severe("AgentBay session not found: " + this.sandboxId); + logger.error("AgentBay session not found: {}", this.sandboxId); return "AgentBay session not found: " + this.sandboxId; } CommandResult result = session.getCommand().executeCommand(command, 1000); @@ -220,7 +218,7 @@ public String readFile(String path) { Session session = getSession(); path = path == null ? "" : path; if (session == null) { - logger.severe("AgentBay session not found: " + this.sandboxId); + logger.error("AgentBay session not found: {}", this.sandboxId); return "AgentBay session not found: " + this.sandboxId; } FileContentResult result = session.getFileSystem().readFile(path); @@ -237,7 +235,7 @@ public String writeFile(String path, String content) { path = path == null ? "" : path; content = content == null ? "" : content; if (session == null) { - logger.severe("AgentBay session not found: " + this.sandboxId); + logger.error("AgentBay session not found: {}", this.sandboxId); return "AgentBay session not found: " + this.sandboxId; } BoolResult result = session.getFileSystem().writeFile(path, content); @@ -252,7 +250,7 @@ public String listDirectory(String path) { Session session = getSession(); path = path == null ? "" : path; if (session == null) { - logger.severe("AgentBay session not found: " + this.sandboxId); + logger.error("AgentBay session not found: {}", this.sandboxId); return "AgentBay session not found: " + this.sandboxId; } DirectoryListResult result = session.getFileSystem().listDirectory(path); @@ -269,7 +267,7 @@ public String moveFile(String source, String destination) { source = source == null ? "" : source; destination = destination == null ? "" : destination; if (session == null) { - logger.severe("AgentBay session not found: " + this.sandboxId); + logger.error("AgentBay session not found: {}", this.sandboxId); return "AgentBay session not found: " + this.sandboxId; } BoolResult result = session.getFileSystem().moveFile(source, destination); @@ -284,7 +282,7 @@ public String deleteFile(String path) { Session session = getSession(); path = path == null ? "" : path; if (session == null) { - logger.severe("AgentBay session not found: " + this.sandboxId); + logger.error("AgentBay session not found: {}", this.sandboxId); return "AgentBay session not found: " + this.sandboxId; } DeleteResult result = session.getFileSystem().deleteFile(path); @@ -299,7 +297,7 @@ public String createDirectory(String path) { Session session = getSession(); path = path == null ? "" : path; if (session == null) { - logger.severe("AgentBay session not found: " + this.sandboxId); + logger.error("AgentBay session not found: {}", this.sandboxId); return "AgentBay session not found: " + this.sandboxId; } BoolResult result = session.getFileSystem().createDirectory(path); @@ -313,7 +311,7 @@ public String createDirectory(String path) { public String takeScreenShot() { Session session = getSession(); if (session == null) { - logger.severe("AgentBay session not found: " + this.sandboxId); + logger.error("AgentBay session not found: {}", this.sandboxId); return "AgentBay session not found: " + this.sandboxId; } OperationResult result = session.getComputer().screenshot(); @@ -329,7 +327,7 @@ public String browserNavigate(String url) { Session session = getSession(); url = url == null ? "" : url; if (session == null) { - logger.severe("AgentBay session not found: " + this.sandboxId); + logger.error("AgentBay session not found: {}", this.sandboxId); return "AgentBay session not found: " + this.sandboxId; } Map response = new HashMap<>(); @@ -351,7 +349,7 @@ public String browserNavigate(String url) { result = page.content(); browser.close(); } catch (Exception e) { - logger.severe("Playwright integration failed: " + e.getMessage()); + logger.error("Playwright integration failed: {}", e.getMessage()); } response = Map.of( "success", true, @@ -359,7 +357,7 @@ public String browserNavigate(String url) { "error", "" ); } catch (Exception e) { - logger.severe("Browser navigate failed: " + e.getMessage()); + logger.error("Browser navigate failed: {}", e.getMessage()); response = Map.of( "success", false, "error", e.getMessage() != null ? e.getMessage() : "" @@ -372,7 +370,7 @@ public String browserClick(String selector) { Session session = getSession(); selector = selector == null ? "" : selector; if (session == null) { - logger.severe("AgentBay session not found: " + this.sandboxId); + logger.error("AgentBay session not found: {}", this.sandboxId); return "AgentBay session not found: " + this.sandboxId; } Map response = new HashMap<>(); @@ -385,7 +383,7 @@ public String browserClick(String selector) { "error", result.getMessage() != null ? result.getMessage() : "" ); } catch (BrowserException e) { - logger.severe("Browser click failed: " + e.getMessage()); + logger.error("Browser click failed: {}", e.getMessage()); response = Map.of( "success", false, "error", e.getMessage() != null ? e.getMessage() : "" diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/box/DummySandbox.java b/core/src/main/java/io/agentscope/runtime/sandbox/box/DummySandbox.java index 50bb4dbc..5ff948a4 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/box/DummySandbox.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/box/DummySandbox.java @@ -18,12 +18,13 @@ import io.agentscope.runtime.sandbox.manager.SandboxManager; import io.agentscope.runtime.sandbox.manager.model.container.ContainerModel; import io.agentscope.runtime.sandbox.manager.model.container.SandboxType; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.Map; -import java.util.logging.Logger; public class DummySandbox implements AutoCloseable { - private static final Logger logger = Logger.getLogger(DummySandbox.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(DummySandbox.class); private final String sandboxId; private final String userId; @@ -46,9 +47,8 @@ public DummySandbox( // For dummy sandbox, we just use a fixed ID this.sandboxId = "dummy-sandbox-" + userId + "-" + sessionId; - - logger.info("DummySandbox initialized: " + this.sandboxId + - " (This is a dummy sandbox, no real container created)"); + + logger.info("DummySandbox initialized: {} (This is a dummy sandbox, no real container created)", this.sandboxId); } public String getSandboxId() { @@ -81,8 +81,7 @@ public Map listTools(String toolType) { } public String callTool(String name, Map arguments) { - logger.info("DummySandbox.callTool() called with name=" + name + - " - returning dummy response"); + logger.info("DummySandbox.callTool() called with name={} - returning dummy response", name); return "{\"status\": \"success\", \"message\": \"Dummy sandbox call\"}"; } diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/box/MobileSandbox.java b/core/src/main/java/io/agentscope/runtime/sandbox/box/MobileSandbox.java index 4cca06a1..72f30b8b 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/box/MobileSandbox.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/box/MobileSandbox.java @@ -19,13 +19,14 @@ import io.agentscope.runtime.sandbox.manager.SandboxManager; import io.agentscope.runtime.sandbox.manager.model.container.SandboxType; import io.agentscope.runtime.sandbox.manager.registry.RegisterSandbox; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.logging.Logger; @RegisterSandbox( imageName = "agentscope-registry.ap-southeast-1.cr.aliyuncs.com/agentscope/runtime-sandbox-mobile:latest", @@ -36,7 +37,7 @@ runtimeConfig = {"privileged=true"} ) public class MobileSandbox extends Sandbox { - private static final Logger logger = Logger.getLogger(MobileSandbox.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(MobileSandbox.class); private static boolean hostCheckDone = false; public MobileSandbox(SandboxManager managerApi, String userId, String sessionId) { @@ -67,7 +68,7 @@ public void checkHostReadiness() { String arch = System.getProperty("os.arch").toLowerCase(); if ("aarch64".equals(arch) || "arm64".equals(arch)) { - logger.warning(""" + logger.warn(""" ======================== WARNING ======================== ARM64/aarch64 architecture detected (e.g., Apple M-series). diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/box/Sandbox.java b/core/src/main/java/io/agentscope/runtime/sandbox/box/Sandbox.java index dca28980..e361f684 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/box/Sandbox.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/box/Sandbox.java @@ -18,12 +18,13 @@ import io.agentscope.runtime.sandbox.manager.SandboxManager; import io.agentscope.runtime.sandbox.manager.model.container.ContainerModel; import io.agentscope.runtime.sandbox.manager.model.container.SandboxType; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.Map; -import java.util.logging.Logger; public abstract class Sandbox implements AutoCloseable { - private static final Logger logger = Logger.getLogger(Sandbox.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(Sandbox.class); protected final SandboxManager managerApi; protected String sandboxId; @@ -66,11 +67,9 @@ public Sandbox( ); } this.sandboxId = containerModel.getContainerName(); - logger.info("Sandbox initialized: " + this.sandboxId + - " (type=" + sandboxType + ", user=" + userId + - ", session=" + sessionId + ", autoRelease=" + autoRelease + ")"); + logger.info("Sandbox initialized: {} (type={}, user={}, session={}, autoRelease={})", this.sandboxId, sandboxType, userId, sessionId, autoRelease); } catch (Exception e) { - logger.severe("Failed to initialize sandbox: " + e.getMessage()); + logger.error("Failed to initialize sandbox: {}", e.getMessage()); throw new RuntimeException("Failed to initialize sandbox", e); } } @@ -126,13 +125,13 @@ public void close() { try { if (autoRelease) { - logger.info("Auto-releasing sandbox: " + sandboxId); + logger.info("Auto-releasing sandbox: {}", sandboxId); managerApi.releaseSandbox(sandboxType, userId, sessionId); } else { - logger.info("Sandbox closed (not released, can be reused): " + sandboxId); + logger.info("Sandbox closed (not released, can be reused): {}", sandboxId); } } catch (Exception e) { - logger.severe("Failed to cleanup sandbox: " + e.getMessage()); + logger.error("Failed to cleanup sandbox: {}", e.getMessage()); } } @@ -142,11 +141,11 @@ public void close() { */ public void release() { try { - logger.info("Manually releasing sandbox: " + sandboxId); + logger.info("Manually releasing sandbox: {}", sandboxId); managerApi.releaseSandbox(sandboxType, userId, sessionId); closed = true; } catch (Exception e) { - logger.severe("Failed to release sandbox: " + e.getMessage()); + logger.error("Failed to release sandbox: {}", e.getMessage()); throw new RuntimeException("Failed to release sandbox", e); } } diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/manager/SandboxManager.java b/core/src/main/java/io/agentscope/runtime/sandbox/manager/SandboxManager.java index c31868b0..6038e4c1 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/manager/SandboxManager.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/manager/SandboxManager.java @@ -32,18 +32,20 @@ import io.agentscope.runtime.sandbox.manager.remote.RemoteWrapper; import io.agentscope.runtime.sandbox.manager.remote.RequestMethod; import io.agentscope.runtime.sandbox.manager.util.*; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.nio.file.Paths; import java.util.*; -import java.util.logging.Logger; /** * Sandbox Manager for managing container lifecycle */ public class SandboxManager implements AutoCloseable { + private static final Logger logger = LoggerFactory.getLogger(SandboxManager.class); + private final Map sandboxMap = new HashMap<>(); private final ContainerManagerType containerManagerType; - Logger logger = Logger.getLogger(SandboxManager.class.getName()); String BROWSER_SESSION_ID = "123e4567-e89b-12d3-a456-426614174000"; private final ManagerConfig managerConfig; private BaseClient containerClient; @@ -77,7 +79,7 @@ public SandboxManager(ManagerConfig managerConfig) { public SandboxManager(ManagerConfig managerConfig, String baseUrl, String bearerToken) { if (baseUrl != null && !baseUrl.isEmpty()) { this.remoteHttpClient = new RemoteHttpClient(baseUrl, bearerToken); - logger.info("Initialized SandboxManager in remote mode with base URL: " + baseUrl); + logger.info("Initialized SandboxManager in remote mode with base URL: {}", baseUrl); this.managerConfig = managerConfig != null ? managerConfig : new ManagerConfig.Builder().build(); this.containerManagerType = ContainerManagerType.CLOUD; this.storageManager = null; @@ -98,9 +100,9 @@ public SandboxManager(ManagerConfig managerConfig, String baseUrl, String bearer this.redisEnabled = managerConfig.getRedisEnabled(); this.portManager = new PortManager(managerConfig.getPortRange()); - logger.info("Initializing SandboxManager with container manager: " + this.containerManagerType); - logger.info("Container pool size: " + this.poolSize); - logger.info("Redis enabled: " + this.redisEnabled); + logger.info("Initializing SandboxManager with container manager: {}", this.containerManagerType); + logger.info("Container pool size: {}", this.poolSize); + logger.info("Redis enabled: {}", this.redisEnabled); } public void start() { @@ -110,18 +112,18 @@ public void start() { this.redisClient = new RedisClientWrapper(redisConfig); String pong = this.redisClient.ping(); - logger.info("Redis connection test: " + pong); + logger.info("Redis connection test: {}", pong); String mappingPrefix = managerConfig.getContainerPrefixKey() + "mapping"; this.redisContainerMapping = new RedisContainerMapping(this.redisClient, mappingPrefix); String queueName = redisConfig.getRedisContainerPoolKey(); this.poolQueue = new RedisContainerQueue(this.redisClient, queueName); - logger.info("Using Redis-backed container pool with queue: " + queueName); + logger.info("Using Redis-backed container pool with queue: {}", queueName); logger.info("Redis client initialized successfully for container management"); } catch (Exception e) { - logger.severe("Failed to initialize Redis client: " + e.getMessage()); + logger.error("Failed to initialize Redis client: {}", e.getMessage()); throw new RuntimeException("Failed to initialize Redis", e); } } else { @@ -129,7 +131,7 @@ public void start() { logger.info("Using in-memory container storage"); } - logger.info("Using container type: " + this.containerManagerType); + logger.info("Using container type: {}", this.containerManagerType); if (managerConfig.getAgentBayApiKey() != null) { agentBayClient = new AgentBayClient(managerConfig.getAgentBayApiKey()); @@ -144,7 +146,7 @@ public void start() { dockerClientConfig = DockerClientConfig.builder().build(); } DockerClient dockerClient = new DockerClient(dockerClientConfig, portManager); - logger.info("Docker client created: " + dockerClient); + logger.info("Docker client created: {}", dockerClient); this.containerClient = dockerClient; dockerClient.connectDocker(); @@ -154,7 +156,7 @@ public void start() { if (managerConfig.getClientConfig() instanceof KubernetesClientConfig kubernetesClientConfig) { kubernetesClient = new KubernetesClient(kubernetesClientConfig); } else { - logger.warning("Provided clientConfig is not an instance of KubernetesClientConfig, using default configuration"); + logger.warn("Provided clientConfig is not an instance of KubernetesClientConfig, using default configuration"); kubernetesClient = new KubernetesClient(); } this.containerClient = kubernetesClient; @@ -207,12 +209,12 @@ private AgentRunClient getAgentRunClient(ManagerConfig managerConfig) { } private void initContainerPool() { - logger.info("Initializing container pool with size: " + poolSize); + logger.info("Initializing container pool with size: {}", poolSize); while (poolQueue.size() < poolSize) { for (SandboxType type : managerConfig.getDefaultSandboxType()) { if (type == SandboxType.AGENTBAY) { - logger.warning("Skipping AgentBay sandbox type for container pool initialization"); + logger.warn("Skipping AgentBay sandbox type for container pool initialization"); continue; } try { @@ -221,24 +223,23 @@ private void initContainerPool() { if (containerModel != null) { if (poolQueue.size() < poolSize) { poolQueue.enqueue(containerModel); - logger.info("Added container to pool: " + containerModel.getContainerName() + " (pool size: " + poolQueue.size() + "/" + poolSize + ")"); + logger.info("Added container to pool: {} (pool size: {}/{})", containerModel.getContainerName(), poolQueue.size(), poolSize); } else { - logger.info("Pool size limit reached, releasing container: " + containerModel.getContainerName()); + logger.info("Pool size limit reached, releasing container: {}", containerModel.getContainerName()); releaseContainer(containerModel); break; } } else { - logger.severe("Failed to create container for pool"); + logger.error("Failed to create container for pool"); break; } } catch (Exception e) { - logger.severe("Error initializing container pool: " + e.getMessage()); - e.printStackTrace(); + logger.error("Error initializing container pool: {}", e.getMessage()); break; } } } - logger.info("Container pool initialization complete. Pool size: " + poolQueue.size()); + logger.info("Container pool initialization complete. Pool size: {}", poolQueue.size()); } public ContainerModel createFromPool(SandboxType sandboxType, String imageId, Map labels) { @@ -257,42 +258,42 @@ public ContainerModel createFromPool(SandboxType sandboxType, String imageId, Ma ContainerModel containerModel = poolQueue.dequeue(); if (containerModel == null) { - logger.warning("No container available in pool after " + attempts + " attempts"); + logger.warn("No container available in pool after {} attempts", attempts); continue; } - logger.info("Retrieved container from pool: " + containerModel.getContainerName()); + logger.info("Retrieved container from pool: {}", containerModel.getContainerName()); String currentImage = SandboxRegistryService.getImageByType(sandboxType).orElse(containerModel.getVersion()); if (!currentImage.equals(containerModel.getVersion())) { - logger.warning("Container " + containerModel.getContainerName() + " is outdated (has: " + containerModel.getVersion() + ", current: " + currentImage + "), releasing and trying next"); + logger.warn("Container {} is outdated (has: {}, current: {}), releasing and trying next", + containerModel.getContainerName(), containerModel.getVersion(), currentImage); releaseContainer(containerModel); continue; } if (!containerClient.inspectContainer(containerModel.getContainerId())) { - logger.warning("Container " + containerModel.getContainerId() + " not found or has been removed externally, trying next"); + logger.warn("Container {} not found or has been removed externally, trying next", containerModel.getContainerId()); continue; } String status = containerClient.getContainerStatus(containerModel.getContainerId()); if (!"running".equals(status)) { - logger.warning("Container " + containerModel.getContainerId() + " is not running (status: " + status + "), trying next"); + logger.warn("Container {} is not running (status: {}), trying next", containerModel.getContainerId(), status); releaseContainer(containerModel); continue; } - logger.info("Successfully retrieved running container from pool: " + containerModel.getContainerName()); + logger.info("Successfully retrieved running container from pool: {}", containerModel.getContainerName()); return containerModel; } catch (Exception e) { - logger.severe("Error getting container from pool (attempt " + attempts + "): " + e.getMessage()); - e.printStackTrace(); + logger.error("Error getting container from pool (attempt {}): {}", attempts, e.getMessage()); } } - logger.warning("Failed to get container from pool after " + maxAttempts + " attempts, creating new container"); + logger.warn("Failed to get container from pool after {} attempts, creating new container", maxAttempts); return createContainer(sandboxType, null, null, null, imageId, labels); } @@ -330,7 +331,8 @@ public ContainerModel createFromPool(SandboxType sandboxType, String userID, Str ContainerModel existingContainer = sandboxMap.get(key); if (existingContainer != null) { - logger.info("Reusing existing container: " + existingContainer.getContainerName() + " (userID: " + userID + ", sessionID: " + sessionID + ")"); + logger.info("Reusing existing container: {} (userID: {}, sessionID: {})", + existingContainer.getContainerName(), userID, sessionID); return existingContainer; } @@ -338,7 +340,8 @@ public ContainerModel createFromPool(SandboxType sandboxType, String userID, Str existingContainer = redisContainerMapping.get(key); if (existingContainer != null) { sandboxMap.put(key, existingContainer); - logger.info("Retrieved container from Redis: " + existingContainer.getContainerName() + " (userID: " + userID + ", sessionID: " + sessionID + ")"); + logger.info("Retrieved container from Redis: {} (userID: {}, sessionID: {})", + existingContainer.getContainerName(), userID, sessionID); return existingContainer; } } @@ -346,7 +349,7 @@ public ContainerModel createFromPool(SandboxType sandboxType, String userID, Str ContainerModel containerModel = createFromPool(sandboxType, imageId, labels); if (containerModel == null) { - logger.severe("Failed to get container from pool"); + logger.error("Failed to get container from pool"); return null; } @@ -357,7 +360,8 @@ public ContainerModel createFromPool(SandboxType sandboxType, String userID, Str logger.info("Stored pool container in Redis"); } - logger.info("Added pool container to sandbox map: " + containerModel.getContainerName() + " (userID: " + userID + ", sessionID(key): " + sessionID + ", container sessionId: " + containerModel.getSessionId() + ")"); + logger.info("Added pool container to sandbox map: {} (userID: {}, sessionID(key): {}, container sessionId: {})", + containerModel.getContainerName(), userID, sessionID, containerModel.getSessionId()); return containerModel; } @@ -400,7 +404,7 @@ public ContainerModel createContainer(SandboxType sandboxType, String mountDir, String containerId = createResult.getContainerId(); if (containerId == null) { - logger.severe("Container creation failed: containerId is null"); + logger.error("Container creation failed: containerId is null"); return null; } List resultPorts = createResult.getPorts(); @@ -414,7 +418,7 @@ public ContainerModel createContainer(SandboxType sandboxType, String mountDir, String[] mappedPorts = resultPorts != null ? resultPorts.toArray(new String[0]) : new String[]{firstPort}; - ContainerModel containerModel = ContainerModel.builder() + return ContainerModel.builder() .sessionId(containerId) .containerId(containerId) .containerName(containerId) @@ -430,7 +434,6 @@ public ContainerModel createContainer(SandboxType sandboxType, String mountDir, .authToken("") .version("agentbay-cloud") .build(); - return containerModel; } if (environment == null) { @@ -440,7 +443,7 @@ public ContainerModel createContainer(SandboxType sandboxType, String mountDir, for (Map.Entry entry : environment.entrySet()) { String value = entry.getValue(); if (value == null) { - logger.warning("Environment variable " + entry.getKey() + " has null value"); + logger.warn("Environment variable {} has null value", entry.getKey()); return null; } } @@ -451,7 +454,7 @@ public ContainerModel createContainer(SandboxType sandboxType, String mountDir, String imageName = SandboxRegistryService.getImageByType(sandboxType).orElse("agentscope-registry.ap-southeast-1.cr.aliyuncs.com/agentscope/runtime-sandbox-base:latest"); SandboxConfig sandboxConfig = SandboxRegistryService.getConfigByType(sandboxType).orElse(null); if (sandboxConfig != null) { - logger.info("Using registered sandbox configuration: " + sandboxConfig.getDescription()); + logger.info("Using registered sandbox configuration: {}", sandboxConfig.getDescription()); if (sandboxConfig.getEnvironment() != null && !sandboxConfig.getEnvironment().isEmpty()) { Map mergedEnv = new HashMap<>(sandboxConfig.getEnvironment()); mergedEnv.putAll(environment); @@ -459,15 +462,15 @@ public ContainerModel createContainer(SandboxType sandboxType, String mountDir, } } - logger.info("Checking image: " + imageName); + logger.info("Checking image: {}", imageName); if (containerManagerType == ContainerManagerType.DOCKER) { if (!containerClient.ensureImageAvailable(imageName)) { - logger.severe("Can not get image: " + imageName); + logger.error("Can not get image: {}", imageName); throw new RuntimeException("Pull image failed: " + imageName); } - logger.info("Docker image is ready: " + imageName); + logger.info("Docker image is ready: {}", imageName); } else if (containerManagerType == ContainerManagerType.KUBERNETES) { - logger.info("Kubernetes image is ready: " + imageName); + logger.info("Kubernetes image is ready: {}", imageName); } String sessionId = RandomStringGenerator.generateRandomString(22); String currentDir = System.getProperty("user.dir"); @@ -486,12 +489,12 @@ public ContainerModel createContainer(SandboxType sandboxType, String mountDir, storagePath = managerConfig.getFileSystemConfig().getStorageFolderPath(); } if (!mountDir.isEmpty() && !storagePath.isEmpty() && containerManagerType != ContainerManagerType.AGENTRUN && containerManagerType != ContainerManagerType.FC) { - logger.info("Downloading from storage path: " + storagePath + " to mount dir: " + mountDir); + logger.info("Downloading from storage path: {} to mount dir: {}", storagePath, mountDir); boolean downloadSuccess = storageManager.downloadFolder(storagePath, mountDir); if (downloadSuccess) { logger.info("Successfully downloaded files from storage"); } else { - logger.warning("Failed to download files from storage, continuing with empty mount dir"); + logger.warn("Failed to download files from storage, continuing with empty mount dir"); } } String runtimeToken = RandomStringGenerator.generateRandomString(32); @@ -502,40 +505,40 @@ public ContainerModel createContainer(SandboxType sandboxType, String mountDir, } Map readonlyMounts = managerConfig.getFileSystemConfig().getReadonlyMounts(); if (readonlyMounts != null && !readonlyMounts.isEmpty()) { - logger.info("Adding readonly mounts: " + readonlyMounts.size() + " mount(s)"); + logger.info("Adding readonly mounts: {} mount(s)", readonlyMounts.size()); for (Map.Entry entry : readonlyMounts.entrySet()) { String hostPath = entry.getKey(); String containerPath = entry.getValue(); if (!java.nio.file.Paths.get(hostPath).isAbsolute()) { hostPath = java.nio.file.Paths.get(hostPath).toAbsolutePath().toString(); - logger.info("Converting relative path to absolute: " + hostPath); + logger.info("Converting relative path to absolute: {}", hostPath); } java.io.File hostFile = new java.io.File(hostPath); if (!hostFile.exists()) { - logger.warning("Readonly mount host path does not exist: " + hostPath + ", skipping"); + logger.warn("Readonly mount host path does not exist: {}, skipping", hostPath); continue; } volumeBindings.add(new VolumeBinding(hostPath, containerPath, "ro")); - logger.info("Added readonly mount: " + hostPath + " -> " + containerPath); + logger.info("Added readonly mount: {} -> {}", hostPath, containerPath); } } Map nonCopyMounts = managerConfig.getFileSystemConfig().getNonCopyMount(); if(nonCopyMounts != null && !nonCopyMounts.isEmpty()){ - logger.info("Adding non-copy mounts: " + nonCopyMounts.size() + " mount(s)"); + logger.info("Adding non-copy mounts: {} mount(s)", nonCopyMounts.size()); for (Map.Entry entry : nonCopyMounts.entrySet()) { String hostPath = entry.getKey(); String containerPath = entry.getValue(); if (!java.nio.file.Paths.get(hostPath).isAbsolute()) { hostPath = java.nio.file.Paths.get(hostPath).toAbsolutePath().toString(); - logger.info("Converting relative path to absolute: " + hostPath); + logger.info("Converting relative path to absolute: {}", hostPath); } java.io.File hostFile = new java.io.File(hostPath); if (!hostFile.exists()) { - logger.warning("NonCopy mount host path does not exist: " + hostPath + ", skipping"); + logger.warn("NonCopy mount host path does not exist: {}, skipping", hostPath); continue; } volumeBindings.add(new VolumeBinding(hostPath, containerPath, "rw")); - logger.info("Added non Copy mount: " + hostPath + " -> " + containerPath); + logger.info("Added non Copy mount: {} -> {}", hostPath, containerPath); } } @@ -544,7 +547,7 @@ public ContainerModel createContainer(SandboxType sandboxType, String mountDir, if (sandboxConfig != null) { runtimeConfig = sandboxConfig.getRuntimeConfig(); } - logger.info("Runtime config: " + runtimeConfig); + logger.info("Runtime config: {}", runtimeConfig); String containerName; String prefix = managerConfig.getContainerPrefixKey(); if (prefix == null || prefix.isEmpty()) { @@ -561,7 +564,7 @@ public ContainerModel createContainer(SandboxType sandboxType, String mountDir, String containerId = createResult.getContainerId(); if (containerId == null) { - logger.severe("Container creation failed: containerId is null"); + logger.error("Container creation failed: containerId is null"); return null; } List resultPorts = createResult.getPorts(); @@ -592,7 +595,7 @@ public ContainerModel createContainer(SandboxType sandboxType, String mountDir, .version(imageName) .build(); - logger.info("Container Model: " + containerModel); + logger.info("Container Model: {}", containerModel); containerClient.startContainer(containerId); return containerModel; @@ -603,7 +606,7 @@ private void releaseContainer(ContainerModel containerModel) { return; } try { - logger.info("Releasing container: " + containerModel.getContainerName()); + logger.info("Releasing container: {}", containerModel.getContainerName()); portManager.releaseContainerPorts(containerModel.getContainerName()); containerClient.stopContainer(containerModel.getContainerId()); containerClient.removeContainer(containerModel.getContainerId()); @@ -611,7 +614,7 @@ private void releaseContainer(ContainerModel containerModel) { storageManager.uploadFolder(containerModel.getMountDir(), containerModel.getStoragePath()); } } catch (Exception e) { - logger.warning("Error releasing container " + containerModel.getContainerName() + ": " + e.getMessage()); + logger.warn("Error releasing container {}: {}", containerModel.getContainerName(), e.getMessage()); } } @@ -633,7 +636,7 @@ public ContainerModel getSandbox(SandboxType sandboxType, String mountDir, Strin if (redisEnabled && redisContainerMapping != null) { ContainerModel existingModel = redisContainerMapping.get(key); if (existingModel != null) { - logger.info("Found existing container in Redis: " + existingModel.getContainerName()); + logger.info("Found existing container in Redis: {}", existingModel.getContainerName()); // Also update local cache sandboxMap.put(key, existingModel); return existingModel; @@ -648,7 +651,7 @@ public ContainerModel getSandbox(SandboxType sandboxType, String mountDir, Strin if (redisEnabled && redisContainerMapping != null) { redisContainerMapping.put(key, containerModel); - logger.info("Stored container in Redis: " + containerModel.getContainerName()); + logger.info("Stored container in Redis: {}", containerModel.getContainerName()); } startSandbox(sandboxType, userID, sessionID); @@ -757,11 +760,11 @@ public void stopAndRemoveSandbox(SandboxType sandboxType, String userID, String try { String containerId = containerModel.getContainerId(); String containerName = containerModel.getContainerName(); - logger.info("Stopping and removing " + sandboxType + " sandbox (Container ID: " + containerId + ", Name: " + containerName + ")"); + logger.info("Stopping and removing {} sandbox (Container ID: {}, Name: {})", sandboxType, containerId, containerName); if (sandboxType == SandboxType.AGENTBAY) { agentBayClient.removeContainer(containerId); - logger.info("Deleted AgentBay container: " + containerName); + logger.info("Deleted AgentBay container: {}", containerName); } else { portManager.releaseContainerPorts(containerName); containerClient.stopContainer(containerId); @@ -773,16 +776,16 @@ public void stopAndRemoveSandbox(SandboxType sandboxType, String userID, String redisContainerMapping.remove(key); logger.info("Removed container from Redis"); } - logger.info(sandboxType + " sandbox has been successfully removed"); + logger.info("{} sandbox has been successfully removed", sandboxType); } catch (Exception e) { - logger.severe("Error removing " + sandboxType + " sandbox: " + e.getMessage()); + logger.error("Error removing {} sandbox: {}", sandboxType, e.getMessage()); sandboxMap.remove(key); if (redisEnabled && redisContainerMapping != null) { redisContainerMapping.remove(key); } } } else { - logger.warning("Sandbox " + sandboxType + " not found, may have already been removed"); + logger.warn("Sandbox {} not found, may have already been removed", sandboxType); } } @@ -825,11 +828,11 @@ public Map getAllSandboxes() { if (redisEnabled && redisContainerMapping != null) { try { Map redisData = redisContainerMapping.getAll(); - logger.info("Retrieved " + redisData.size() + " containers from Redis"); + logger.info("Retrieved {} containers from Redis", redisData.size()); allSandboxes.putAll(redisData); } catch (Exception e) { - logger.warning("Failed to retrieve containers from Redis: " + e.getMessage()); + logger.warn("Failed to retrieve containers from Redis: {}", e.getMessage()); } } @@ -862,28 +865,28 @@ public ContainerModel getInfo(String identity) { for (ContainerModel model : sandboxMap.values()) { if (identity.equals(model.getContainerName())) { - logger.fine("Found container by name: " + identity); + logger.info("Found container by name: {}", identity); return model; } } for (ContainerModel model : sandboxMap.values()) { if (identity.equals(model.getSessionId())) { - logger.fine("Found container by session ID: " + identity); + logger.info("Found container by session ID: {}", identity); return model; } } for (ContainerModel model : sandboxMap.values()) { if (identity.equals(model.getContainerId())) { - logger.fine("Found container by container ID: " + identity); + logger.info("Found container by container ID: {}", identity); return model; } } for (ContainerModel model : sandboxMap.values()) { if (identity.equals(model.getContainerName())) { - logger.fine("Found container by prefixed session ID: " + identity); + logger.info("Found container by prefixed session ID: {}", identity); return model; } } @@ -909,7 +912,7 @@ public boolean release(String identity) { try { ContainerModel containerModel = getInfo(identity); - logger.info("Releasing container with identity: " + identity); + logger.info("Releasing container with identity: {}", identity); SandboxKey keyToRemove = null; for (Map.Entry entry : sandboxMap.entrySet()) { @@ -921,7 +924,7 @@ public boolean release(String identity) { if (keyToRemove != null) { sandboxMap.remove(keyToRemove); - logger.info("Removed container from sandbox map: " + keyToRemove); + logger.info("Removed container from sandbox map: {}", keyToRemove); if (redisEnabled && redisContainerMapping != null) { redisContainerMapping.remove(keyToRemove); @@ -933,34 +936,34 @@ public boolean release(String identity) { if (keyToRemove != null && keyToRemove.getSandboxType() == SandboxType.AGENTBAY) { agentBayClient.removeContainer(containerModel.getContainerId()); - logger.info("Deleted AgentBay container: " + containerModel.getContainerName()); + logger.info("Deleted AgentBay container: {}", containerModel.getContainerName()); return true; } containerClient.stopContainer(containerModel.getContainerId()); containerClient.removeContainer(containerModel.getContainerId()); - logger.info("Container destroyed: " + containerModel.getContainerName()); + logger.info("Container destroyed: {}", containerModel.getContainerName()); if (containerModel.getMountDir() != null && containerModel.getStoragePath() != null) { try { - logger.info("Uploading container data to storage: " + containerModel.getStoragePath()); + logger.info("Uploading container data to storage: {}", containerModel.getStoragePath()); boolean uploaded = storageManager.uploadFolder(containerModel.getMountDir(), containerModel.getStoragePath()); if (uploaded) { logger.info("Successfully uploaded container data to storage"); } else { - logger.warning("Failed to upload container data to storage"); + logger.warn("Failed to upload container data to storage"); } } catch (Exception e) { - logger.warning("Failed to upload to storage: " + e.getMessage()); + logger.warn("Failed to upload to storage: {}", e.getMessage()); } } return true; } catch (RuntimeException e) { - logger.warning("Container not found for identity: " + identity); + logger.warn("Container not found for identity: {}", identity); return false; } catch (Exception e) { - logger.severe("Failed to release container: " + e.getMessage()); + logger.error("Failed to release container: {}", e.getMessage()); e.printStackTrace(); return false; } @@ -992,18 +995,17 @@ public void cleanupAllSandboxes() { if (poolQueue != null) { try { - logger.info("Cleaning up container pool (current size: " + poolQueue.size() + ")"); + logger.info("Cleaning up container pool (current size: {})", poolQueue.size()); while (!poolQueue.isEmpty()) { ContainerModel containerModel = poolQueue.dequeue(); if (containerModel != null) { - logger.info("Destroying pool container: " + containerModel.getContainerName()); + logger.info("Destroying pool container: {}", containerModel.getContainerName()); release(containerModel.getContainerId()); } } logger.info("Container pool cleanup complete"); } catch (Exception e) { - logger.severe("Error cleaning up container pool: " + e.getMessage()); - e.printStackTrace(); + logger.error("Error cleaning up container pool: {}", e.getMessage()); } } else { logger.info("Remote mode: no local pool to cleanup"); @@ -1013,16 +1015,16 @@ public void cleanupAllSandboxes() { if (sandboxMap.isEmpty()) { logger.info("No additional sandbox containers to clean up"); } else { - logger.info("Cleaning up " + sandboxMap.size() + " active sandbox containers"); - logger.info("Sandbox types: " + sandboxMap.keySet()); + logger.info("Cleaning up {} active sandbox containers", sandboxMap.size()); + logger.info("Sandbox types: {}", sandboxMap.keySet()); for (SandboxKey key : new HashSet<>(sandboxMap.keySet())) { try { - logger.info("Cleaning up " + key.getSandboxType() + " sandbox for user " + key.getUserID() + " session " + key.getSessionID()); + logger.info("Cleaning up {} sandbox for user {} session {}", key.getSandboxType(), key.getUserID(), key.getSessionID()); stopAndRemoveSandbox(key.getSandboxType(), key.getUserID(), key.getSessionID()); - logger.info(key.getSandboxType() + " sandbox cleanup complete"); + logger.info("{} sandbox cleanup complete", key.getSandboxType()); } catch (Exception e) { - logger.severe("Error cleaning up " + key.getSandboxType() + " sandbox: " + e.getMessage()); + logger.error("Error cleaning up {} sandbox: {}", key.getSandboxType(), e.getMessage()); } } @@ -1051,7 +1053,7 @@ public void close() { redisClient.close(); logger.info("Redis connection closed"); } catch (Exception e) { - logger.warning("Error closing Redis connection: " + e.getMessage()); + logger.warn("Error closing Redis connection: {}", e.getMessage()); } } @@ -1070,7 +1072,7 @@ private SandboxClient establishConnection(String sandboxId) { } return new SandboxHttpClient(containerInfo, 60); } catch (Exception e) { - logger.severe("Failed to establish connection to sandbox: " + e.getMessage()); + logger.error("Failed to establish connection to sandbox: {}", e.getMessage()); throw new RuntimeException("Failed to establish connection", e); } } @@ -1101,7 +1103,7 @@ public Map listTools(String sandboxId, String userId, String ses try (SandboxClient client = establishConnection(sandboxId)) { return client.listTools(toolType, Map.of()); } catch (Exception e) { - logger.severe("Error listing tools: " + e.getMessage()); + logger.error("Error listing tools: {}", e.getMessage()); return new HashMap<>(); } } @@ -1128,7 +1130,7 @@ public String callTool(String sandboxId, String userId, String sessionId, String try (SandboxClient client = establishConnection(sandboxId)) { return client.callTool(toolName, arguments); } catch (Exception e) { - logger.severe("Error calling tool " + toolName + ": " + e.getMessage()); + logger.error("Error calling tool {}: {}", toolName, e.getMessage()); e.printStackTrace(); return "{\"isError\":true,\"content\":[{\"type\":\"text\",\"text\":\"Error calling tool: " + e.getMessage() + "\"}]}"; } @@ -1161,7 +1163,7 @@ public Map addMcpServers(String sandboxId, String userId, String try (SandboxClient client = establishConnection(sandboxId)) { return client.addMcpServers(serverConfigs, overwrite); } catch (Exception e) { - logger.severe("Error adding MCP servers: " + e.getMessage()); + logger.error("Error adding MCP servers: {}", e.getMessage()); return new HashMap<>(); } } @@ -1169,10 +1171,10 @@ public Map addMcpServers(String sandboxId, String userId, String public boolean releaseSandbox(SandboxType sandboxType, String userId, String sessionId) { try { stopAndRemoveSandbox(sandboxType, userId, sessionId); - logger.info("Released sandbox: type=" + sandboxType + ", user=" + userId + ", session=" + sessionId); + logger.info("Released sandbox: type={}, user={}, session={}", sandboxType, userId, sessionId); return true; } catch (Exception e) { - logger.severe("Failed to release sandbox: " + e.getMessage()); + logger.error("Failed to release sandbox: {}", e.getMessage()); return false; } } diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/manager/client/AgentBayClient.java b/core/src/main/java/io/agentscope/runtime/sandbox/manager/client/AgentBayClient.java index f5478f22..692d5bce 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/manager/client/AgentBayClient.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/manager/client/AgentBayClient.java @@ -24,13 +24,14 @@ import com.aliyun.agentbay.session.CreateSessionParams; import com.aliyun.agentbay.session.Session; import io.agentscope.runtime.sandbox.manager.model.fs.VolumeBinding; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.List; import java.util.Map; -import java.util.logging.Logger; public class AgentBayClient extends BaseClient{ - Logger logger = Logger.getLogger(AgentBayClient.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(AgentBayClient.class); private AgentBay agentBay; private String apiKey; @@ -40,7 +41,7 @@ public AgentBayClient(String apiKey){ try{ agentBay = new AgentBay(apiKey); } catch (AgentBayException e) { - logger.severe("Failed to initialize AgentBay client: " + e.getMessage()); + logger.error("Failed to initialize AgentBay client: {}", e.getMessage()); } } @@ -58,14 +59,14 @@ public ContainerCreateResult createContainer(String imageId, Map SessionResult sessionResult = agentBay.create(params); if(sessionResult.isSuccess()){ String sessionId = sessionResult.getSessionId(); - logger.info("AgentBay session created successfully: " + sessionId); + logger.info("AgentBay session created successfully: {}", sessionId); return new ContainerCreateResult(sessionId); } else { - logger.severe("Failed to create AgentBay session: " + sessionResult.getErrorMessage()); + logger.error("Failed to create AgentBay session: {}", sessionResult.getErrorMessage()); } } catch (AgentBayException e){ - logger.severe("Failed to create AgentBay session: " + e.getMessage()); + logger.error("Failed to create AgentBay session: {}", e.getMessage()); } return new ContainerCreateResult(null, null, null); } @@ -90,18 +91,18 @@ public void removeContainer(String containerId) { try{ SessionResult getResult = agentBay.get(containerId); if(!getResult.isSuccess()){ - logger.warning("AgentBay session not found: " + containerId); + logger.warn("AgentBay session not found: {}", containerId); return; } DeleteResult deleteResult = agentBay.delete(getResult.getSession(), false); if(deleteResult.isSuccess()){ - logger.info("AgentBay session removed successfully: " + containerId); + logger.info("AgentBay session removed successfully: {}", containerId); } else { - logger.warning("Failed to remove AgentBay session: " + deleteResult.getErrorMessage()); + logger.warn("Failed to remove AgentBay session: {}", deleteResult.getErrorMessage()); } } catch (AgentBayException e) { - logger.severe("Failed to remove AgentBay session: " + e.getMessage()); + logger.error("Failed to remove AgentBay session: {}", e.getMessage()); } } @@ -112,7 +113,7 @@ public Map getSessionInfo(String sessionId) { Session session = getResult.getSession(); SessionInfoResult infoResult = session.info(); if(infoResult.isSuccess()){ - logger.info("AgentBay session info retrieved successfully: " + sessionId); + logger.info("AgentBay session info retrieved successfully: {}", sessionId); return Map.of( "sessionId", infoResult.getSessionInfo().getSessionId(), "resourceId", infoResult.getSessionInfo().getResourceId(), @@ -122,14 +123,14 @@ public Map getSessionInfo(String sessionId) { "requestId", infoResult.getRequestId() ); } else { - logger.warning("Failed to get AgentBay session info: " + infoResult.getErrorMessage()); + logger.warn("Failed to get AgentBay session info: {}", infoResult.getErrorMessage()); return Map.of("error", infoResult.getErrorMessage()); } } else { - logger.warning("AgentBay session not found: " + sessionId); + logger.warn("AgentBay session not found: {}", sessionId); } } catch (AgentBayException e) { - logger.severe("Failed to get AgentBay session info: " + e.getMessage()); + logger.error("Failed to get AgentBay session info: {}", e.getMessage()); } return null; } @@ -140,10 +141,10 @@ public Session getSession(String sessionId){ if(getResult.isSuccess()){ return getResult.getSession(); } else { - logger.severe("AgentBay session not found: " + sessionId); + logger.error("AgentBay session not found: {}", sessionId); } } catch (AgentBayException e) { - logger.severe("Failed to get AgentBay session: " + e.getMessage()); + logger.error("Failed to get AgentBay session: {}", e.getMessage()); } return null; } diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/manager/client/AgentRunClient.java b/core/src/main/java/io/agentscope/runtime/sandbox/manager/client/AgentRunClient.java index a10b4ea5..a1149f28 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/manager/client/AgentRunClient.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/manager/client/AgentRunClient.java @@ -20,12 +20,13 @@ import com.aliyun.teaopenapi.models.Config; import io.agentscope.runtime.sandbox.manager.client.config.AgentRunClientConfig; import io.agentscope.runtime.sandbox.manager.model.fs.VolumeBinding; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.net.URI; import java.net.URISyntaxException; import java.util.*; import java.util.concurrent.ConcurrentHashMap; -import java.util.logging.Logger; /** * Client for managing AgentRun containers in the sandbox environment. @@ -35,7 +36,7 @@ * API calls and status polling. */ public class AgentRunClient extends BaseClient { - private static final Logger logger = Logger.getLogger(AgentRunClient.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(AgentRunClient.class); private static final int GET_AGENT_RUNTIME_STATUS_MAX_ATTEMPTS = 60; private static final int GET_AGENT_RUNTIME_STATUS_INTERVAL = 1; // seconds @@ -63,9 +64,7 @@ public AgentRunClient(AgentRunClientConfig config) throws Exception { ? config.getAgentRunPrefix() : "agentscope-sandbox"; this.getAgentRuntimeStatusMaxAttempts = GET_AGENT_RUNTIME_STATUS_MAX_ATTEMPTS; this.getAgentRuntimeStatusInterval = GET_AGENT_RUNTIME_STATUS_INTERVAL; - logger.info("AgentRunClient initialized with config: " + config - + ", region: " + config.getAgentRunRegionId() - + ", prefix: " + this.agentRunPrefix); + logger.info("AgentRunClient initialized with config: {}, region: {}, prefix: {}", config, config.getAgentRunRegionId(), this.agentRunPrefix); } @Override @@ -74,7 +73,7 @@ public boolean connect() { this.connected = (client != null); return this.connected; } catch (Exception e) { - logger.severe("Failed to connect to AgentRun: " + e.getMessage()); + logger.error("Failed to connect to AgentRun: {}", e.getMessage()); this.connected = false; return false; } @@ -89,7 +88,7 @@ public boolean isConnected() { public ContainerCreateResult createContainer(String containerName, String imageName, List ports, List volumeBindings, Map environment, Map runtimeConfig) { - logger.fine("Creating AgentRun session with image: " + imageName); + logger.info("Creating AgentRun session with image: {}", imageName); @SuppressWarnings("unused") int port = 80; @@ -104,7 +103,7 @@ public ContainerCreateResult createContainer(String containerName, String imageN try { String sessionId = (containerName != null && !containerName.isEmpty()) ? containerName : generateSessionId(); - logger.info("Created AgentRun session: " + sessionId); + logger.info("Created AgentRun session: {}", sessionId); String agentRuntimeName = agentRunPrefix + "-" + sessionId; ContainerConfiguration containerConfig = new ContainerConfiguration(); @@ -196,24 +195,24 @@ public ContainerCreateResult createContainer(String containerName, String imageN sessionData.put("endpoint_domain", endpointPublicUrlDomain); sessionData.put("endpoint_path", endpointPublicUrlPath); sessionData.put("ports", agentRunPorts); - - logger.info("Domain (netloc): " + endpointPublicUrlDomain); - logger.info("Path: " + endpointPublicUrlPath); - logger.info("Ports entry: " + agentRunPorts.get(0)); + + logger.info("Domain (netloc): {}", endpointPublicUrlDomain); + logger.info("Path: {}", endpointPublicUrlPath); + logger.info("Ports entry: {}", agentRunPorts.get(0)); } catch (URISyntaxException e) { - logger.warning("Failed to parse endpoint URL: " + endpointPublicUrl + ", error: " + e.getMessage()); + logger.error("Failed to parse endpoint URL: {}, error: {}", endpointPublicUrl, e.getMessage()); agentRunPorts.add(String.valueOf(HTTPS_PORT)); sessionData.put("ports", agentRunPorts); } sessionManager.createSession(sessionId, sessionData); - logger.info("Success to create agent runtime with ID: " + agentRuntimeId + ", create session id: " + sessionId); - logger.info("endpoint_public_url: " + endpointPublicUrl); + logger.info("Success to create agent runtime with ID: {}, create session id: {}", agentRuntimeId, sessionId); + logger.info("endpoint_public_url: {}", endpointPublicUrl); return new ContainerCreateResult(sessionId, agentRunPorts, endpointPublicUrlDomain, HTTPS_PROTOCOL); } catch (Exception e) { - logger.severe("Failed to create AgentRun session: " + e.getMessage()); + logger.error("Failed to create AgentRun session: {}", e.getMessage()); throw new RuntimeException("Failed to create AgentRun session", e); } } @@ -222,7 +221,7 @@ public ContainerCreateResult createContainer(String containerName, String imageN public void startContainer(String containerId) { Map session = sessionManager.getSession(containerId); if (session == null) { - logger.warning("AgentRun session id not found: " + containerId); + logger.warn("AgentRun session id not found: {}", containerId); return; } String agentRuntimeId = (String) session.get("agent_runtime_id"); @@ -234,9 +233,9 @@ public void startContainer(String containerId) { sessionManager.updateSession(containerId, Collections.singletonMap("status", "running")); } } - logger.info("set agentRun session status to running: " + containerId); + logger.info("set agentRun session status to running: {}", containerId); } catch (Exception e) { - logger.severe("failed to set agentRun session status to running: " + containerId + ": " + e.getMessage()); + logger.error("failed to set agentRun session status to running: {}: {}", containerId, e.getMessage()); } } @@ -244,15 +243,15 @@ public void startContainer(String containerId) { public void stopContainer(String containerId) { Map session = sessionManager.getSession(containerId); if (session == null) { - logger.warning("AgentRun session id not found: " + containerId); + logger.warn("AgentRun session id not found: {}", containerId); return; } try { sessionManager.updateSession(containerId, Collections.singletonMap("status", "stopped")); - logger.info("set agentRun session status to stopped: " + containerId); + logger.info("set agentRun session status to stopped: {}", containerId); } catch (Exception e) { - logger.severe("failed to set agentRun session status to stopped: " + containerId + ": " + e.getMessage()); + logger.error("failed to set agentRun session status to stopped: {}: {}", containerId, e.getMessage()); } } @@ -260,29 +259,29 @@ public void stopContainer(String containerId) { public void removeContainer(String containerId) { Map session = sessionManager.getSession(containerId); if (session == null) { - logger.warning("AgentRun session id not found: " + containerId); + logger.warn("AgentRun session id not found: {}", containerId); return; } String agentRuntimeId = (String) session.get("agent_runtime_id"); try { - logger.info("Deleting agent runtime with ID: " + agentRuntimeId); + logger.info("Deleting agent runtime with ID: {}", agentRuntimeId); DeleteAgentRuntimeResponse response = client.deleteAgentRuntime(agentRuntimeId); if (response.getBody() != null && "SUCCESS".equals(response.getBody().getCode())) { - logger.info("Agent runtime deletion initiated successfully for ID: " + agentRuntimeId); + logger.info("Agent runtime deletion initiated successfully for ID: {}", agentRuntimeId); Map pollStatus = pollAgentRuntimeStatus(agentRuntimeId); String statusResult = (String) pollStatus.get("status"); - logger.info("Agent runtime deletion status: " + statusResult); + logger.info("Agent runtime deletion status: {}", statusResult); sessionManager.deleteSession(containerId); - logger.info("Successfully removed AgentRun session: " + containerId); + logger.info("Successfully removed AgentRun session: {}", containerId); } else { - logger.severe("Failed to delete agent runtime"); + logger.warn("Failed to delete agent runtime"); } } catch (Exception e) { - logger.severe("Exception occurred while deleting agent runtime: " + e.getMessage()); + logger.error("Exception occurred while deleting agent runtime: {}", e.getMessage()); } } @@ -290,7 +289,7 @@ public void removeContainer(String containerId) { public String getContainerStatus(String containerId) { Map session = sessionManager.getSession(containerId); if (session == null) { - logger.warning("AgentRun session id not found: " + containerId); + logger.warn("AgentRun session id not found: {}", containerId); return "unknown"; } String agentRuntimeId = (String) session.get("agent_runtime_id"); @@ -336,7 +335,7 @@ public boolean pullImage(String imageName) { public Map inspect(String sessionId) { Map session = sessionManager.getSession(sessionId); if (session == null) { - logger.warning("AgentRun session id not found: " + sessionId); + logger.warn("AgentRun session id not found: {}", sessionId); return Collections.emptyMap(); } String agentRuntimeId = (String) session.get("agent_runtime_id"); @@ -368,7 +367,7 @@ public Map inspect(String sessionId) { } else{ - logger.warning("Failed to get agent runtime info for ID: " + agentRuntimeId); + logger.warn("Failed to get agent runtime info for ID: {}", agentRuntimeId); agentRuntimeInfo.put("error", "Failed to get agent runtime info"); agentRuntimeInfo.put("agent_runtime_id", agentRuntimeId); agentRuntimeInfo.put("code", response.getBody() != null ? response.getBody().getCode() : null); @@ -377,7 +376,7 @@ public Map inspect(String sessionId) { } } } catch (Exception e) { - logger.severe("Exception occurred while getting agent runtime info: " + e.getMessage()); + logger.error("Exception occurred while getting agent runtime info: {}", e.getMessage()); agentRuntimeInfo.put("error", e.getMessage()); agentRuntimeInfo.put("message", "Exception occurred while getting agent runtime info: " + e.getMessage()); agentRuntimeInfo.put("agent_runtime_id", agentRuntimeId); @@ -481,17 +480,16 @@ private Map pollAgentRuntimeEndpointStatus(String agentRuntimeId int maxAttempts = getAgentRuntimeStatusMaxAttempts; int intervalSeconds = getAgentRuntimeStatusInterval; - logger.info("Starting to poll agent runtime endpoint status for ID: " + agentRuntimeEndpointId); + logger.info("Starting to poll agent runtime endpoint status for ID: {}", agentRuntimeEndpointId); for (int attempt = 1; attempt <= maxAttempts; attempt++) { Map statusResponse = getAgentRuntimeEndpointStatus(agentRuntimeId, agentRuntimeEndpointId); if (!Boolean.TRUE.equals(statusResponse.get("success"))) { - logger.warning("Attempt " + attempt + "/" + maxAttempts + ": Failed to get status - " - + statusResponse.get("message")); + logger.warn("Attempt {}/{}: Failed to get status - {}", attempt, maxAttempts, statusResponse.get("message")); if (attempt < maxAttempts) { try { - Thread.sleep(intervalSeconds * 1000); + Thread.sleep(intervalSeconds * 1000L); } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; @@ -503,19 +501,19 @@ private Map pollAgentRuntimeEndpointStatus(String agentRuntimeId String currentStatus = (String) statusResponse.get("status"); String statusReason = (String) statusResponse.get("status_reason"); - logger.info("Attempt " + attempt + "/" + maxAttempts + ": Status = " + currentStatus); + logger.info("Attempt {}/{}: Status = {}", attempt, maxAttempts, currentStatus); if (statusReason != null) { - logger.info(" Status reason: " + statusReason); + logger.info(" Status reason: {}", statusReason); } if (terminalStates.contains(currentStatus)) { - logger.info("Reached terminal state '" + currentStatus + "' after " + attempt + " attempts"); + logger.info("Reached terminal state '{}' after {} attempts", currentStatus, attempt); return statusResponse; } if (attempt < maxAttempts) { try { - Thread.sleep(intervalSeconds * 1000); + Thread.sleep(intervalSeconds * 1000L); } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; @@ -523,7 +521,7 @@ private Map pollAgentRuntimeEndpointStatus(String agentRuntimeId } } - logger.warning("Exceeded maximum attempts (" + maxAttempts + ") without reaching a terminal state"); + logger.warn("Exceeded maximum attempts ({}) without reaching a terminal state", maxAttempts); return getAgentRuntimeEndpointStatus(agentRuntimeId, agentRuntimeEndpointId); } @@ -533,7 +531,7 @@ private Map getAgentRuntimeStatus(String agentRuntimeId) { private Map getAgentRuntimeStatus(String agentRuntimeId, String agentRuntimeVersion) { try { - logger.fine("Getting agent runtime status for ID: " + agentRuntimeId); + logger.info("Getting agent runtime status for ID: {}", agentRuntimeId); GetAgentRuntimeRequest request = new GetAgentRuntimeRequest(); if (agentRuntimeVersion != null) { @@ -544,7 +542,7 @@ private Map getAgentRuntimeStatus(String agentRuntimeId, String if (response.getBody() != null && "SUCCESS".equals(response.getBody().getCode()) && response.getBody().getData() != null) { String status = response.getBody().getData().getStatus(); - logger.fine("Agent runtime status for ID " + agentRuntimeId + ": " + status); + logger.info("Agent runtime status for ID {}: {}", agentRuntimeId, status); Map result = new HashMap<>(); result.put("success", true); result.put("status", status); @@ -561,7 +559,7 @@ private Map getAgentRuntimeStatus(String agentRuntimeId, String } } catch (Exception e) { - logger.severe("Exception occurred while getting agent runtime status: " + e.getMessage()); + logger.error("Exception occurred while getting agent runtime status: {}", e.getMessage()); Map result = new HashMap<>(); result.put("success", false); result.put("error", e.getMessage()); @@ -572,7 +570,7 @@ private Map getAgentRuntimeStatus(String agentRuntimeId, String private Map getAgentRuntimeEndpointStatus(String agentRuntimeId, String agentRuntimeEndpointId) { try { - logger.fine("Getting agent runtime endpoint status for ID: " + agentRuntimeEndpointId); + logger.info("Getting agent runtime endpoint status for ID: {}", agentRuntimeEndpointId); GetAgentRuntimeEndpointResponse response = client.getAgentRuntimeEndpoint( agentRuntimeId, agentRuntimeEndpointId); @@ -580,7 +578,7 @@ private Map getAgentRuntimeEndpointStatus(String agentRuntimeId, if (response.getBody() != null && "SUCCESS".equals(response.getBody().getCode()) && response.getBody().getData() != null) { String status = response.getBody().getData().getStatus(); - logger.fine("Agent runtime endpoint status for ID " + agentRuntimeEndpointId + ": " + status); + logger.info("Agent runtime endpoint status for ID {}: {}", agentRuntimeEndpointId, status); Map result = new HashMap<>(); result.put("success", true); result.put("status", status); @@ -597,7 +595,7 @@ private Map getAgentRuntimeEndpointStatus(String agentRuntimeId, } } catch (Exception e) { - logger.fine("Exception occurred while getting agent runtime endpoint status: " + e.getMessage()); + logger.info("Exception occurred while getting agent runtime endpoint status: {}", e.getMessage()); Map result = new HashMap<>(); result.put("success", false); result.put("error", e.getMessage()); @@ -617,17 +615,17 @@ private Map pollAgentRuntimeStatus(String agentRuntimeId, String int maxAttempts = getAgentRuntimeStatusMaxAttempts; int intervalSeconds = getAgentRuntimeStatusInterval; - logger.info("Starting to poll agent runtime status for ID: " + agentRuntimeId); + logger.info("Starting to poll agent runtime status for ID: {}", agentRuntimeId); for (int attempt = 1; attempt <= maxAttempts; attempt++) { Map statusResponse = getAgentRuntimeStatus(agentRuntimeId, agentRuntimeVersion); if (!Boolean.TRUE.equals(statusResponse.get("success"))) { - logger.warning("Attempt " + attempt + "/" + maxAttempts + ": Failed to get status - " - + statusResponse.get("message")); + logger.warn("Attempt {}/{}: Failed to get status - {}", attempt, maxAttempts, + statusResponse.get("message")); if (attempt < maxAttempts) { try { - Thread.sleep(intervalSeconds * 1000); + Thread.sleep(intervalSeconds * 1000L); } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; @@ -639,19 +637,19 @@ private Map pollAgentRuntimeStatus(String agentRuntimeId, String String currentStatus = (String) statusResponse.get("status"); String statusReason = (String) statusResponse.get("status_reason"); - logger.info("Attempt " + attempt + "/" + maxAttempts + ": Status = " + currentStatus); + logger.info("Attempt {}/{}: Status = {}", attempt, maxAttempts, currentStatus); if (statusReason != null) { - logger.info(" Status reason: " + statusReason); + logger.info(" Status reason: {}", statusReason); } if (terminalStates.contains(currentStatus)) { - logger.info("Reached terminal state '" + currentStatus + "' after " + attempt + " attempts"); + logger.info("Reached terminal state '{}' after {} attempts", currentStatus, attempt); return statusResponse; } if (attempt < maxAttempts) { try { - Thread.sleep(intervalSeconds * 1000); + Thread.sleep(intervalSeconds * 1000L); } catch (InterruptedException e) { Thread.currentThread().interrupt(); break; @@ -659,7 +657,7 @@ private Map pollAgentRuntimeStatus(String agentRuntimeId, String } } - logger.warning("Exceeded maximum attempts (" + maxAttempts + ") without reaching a terminal state"); + logger.warn("Exceeded maximum attempts ({}) without reaching a terminal state", maxAttempts); return getAgentRuntimeStatus(agentRuntimeId, agentRuntimeVersion); } @@ -701,17 +699,17 @@ private int parsePort(String portStr) { * updating, and deletion of sessions. */ class AgentRunSessionManager { - private static final Logger logger = Logger.getLogger(AgentRunSessionManager.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(AgentRunSessionManager.class); private final Map> sessions; public AgentRunSessionManager() { this.sessions = new ConcurrentHashMap<>(); - logger.fine("AgentRunSessionManager initialized"); + logger.info("AgentRunSessionManager initialized"); } public void createSession(String sessionId, Map sessionData) { sessions.put(sessionId, sessionData); - logger.info("Created AgentRun session: " + sessionId); + logger.info("Created AgentRun session: {}", sessionId); } public Map getSession(String sessionId) { @@ -722,14 +720,14 @@ public void updateSession(String sessionId, Map updates) { Map session = sessions.get(sessionId); if (session != null) { session.putAll(updates); - logger.fine("Updated AgentRun session: " + sessionId); + logger.info("Updated AgentRun session: {}", sessionId); } } public void deleteSession(String sessionId) { Map removed = sessions.remove(sessionId); if (removed != null) { - logger.info("Deleted AgentRun session: " + sessionId); + logger.info("Deleted AgentRun session: {}", sessionId); } } diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/manager/client/DockerClient.java b/core/src/main/java/io/agentscope/runtime/sandbox/manager/client/DockerClient.java index 7dbfde81..a3d77763 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/manager/client/DockerClient.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/manager/client/DockerClient.java @@ -28,13 +28,14 @@ import io.agentscope.runtime.sandbox.manager.model.container.PortRange; import io.agentscope.runtime.sandbox.manager.model.fs.VolumeBinding; import io.agentscope.runtime.sandbox.manager.util.PortManager; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.*; import java.util.concurrent.ConcurrentHashMap; -import java.util.logging.Logger; public class DockerClient extends BaseClient { - Logger logger = Logger.getLogger(DockerClient.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(DockerClient.class); private com.github.dockerjava.api.DockerClient client; private boolean connected = false; private DockerClientConfig config; @@ -75,7 +76,7 @@ public boolean connect() { this.connected = true; return true; } catch (Exception e) { - logger.severe("Failed to connect to Docker: " + e.getMessage()); + logger.error("Failed to connect to Docker: {}", e.getMessage()); this.connected = false; return false; } @@ -101,7 +102,7 @@ public ContainerCreateResult createContainer(String containerName, String imageN if (portManager != null) { portMapping = findFreePorts(ports); } else { - logger.warning("Ports requested but no PortManager available. Cannot allocate ports."); + logger.warn("Ports requested but no PortManager available. Cannot allocate ports."); } } @@ -111,15 +112,15 @@ public ContainerCreateResult createContainer(String containerName, String imageN String containerId = response.getId(); // Store port mapping in cache - if (portMapping != null && !portMapping.isEmpty()) { + if (!portMapping.isEmpty()) { List hostPorts = new ArrayList<>(portMapping.values()); portsCache.put(containerId, hostPorts); - logger.fine("Stored port mapping for container " + containerId + ": " + hostPorts); + logger.info("Stored port mapping for container {}: {}", containerId, hostPorts); } // Extract ports from portMapping List portList = new ArrayList<>(); - if (portMapping != null && !portMapping.isEmpty()) { + if (!portMapping.isEmpty()) { for (Integer port : portMapping.values()) { portList.add(String.valueOf(port)); } @@ -148,7 +149,7 @@ private Map findFreePorts(List containerPorts) { String containerPort = containerPorts.get(i); Integer hostPort = freePorts[i]; portMapping.put(containerPort, hostPort); - logger.fine("Mapped container port " + containerPort + " to host port " + hostPort); + logger.info("Mapped container port {} to host port {}", containerPort, hostPort); } return portMapping; @@ -182,7 +183,7 @@ public void removeContainer(String containerId) { for (Integer port : ports) { portManager.releasePort(port); } - logger.fine("Released " + ports.size() + " port(s) for container " + containerId); + logger.info("Released {} port(s) for container {}", ports.size(), containerId); } removeContainer(client, containerId); @@ -205,9 +206,9 @@ private com.github.dockerjava.api.DockerClient openDockerClient() { if (this.config.getCertPath() != null && !this.config.getCertPath().isEmpty()) { configBuilder.withDockerCertPath(this.config.getCertPath()); - logger.info("Connecting to Docker at " + dockerHost + " with TLS"); + logger.info("Connecting to Docker at {} with TLS", dockerHost); } else { - logger.info("Connecting to Docker at " + dockerHost + " without TLS"); + logger.info("Connecting to Docker at {} without TLS", dockerHost); } var config = configBuilder.build(); @@ -223,9 +224,7 @@ private com.github.dockerjava.api.DockerClient openDockerClient() { logger.info("Successfully connected to Docker using configured host and port"); return client; } catch (Exception e) { - logger.warning("Failed to connect to Docker using configured host (" + - this.config.getHost() + ":" + this.config.getPort() + - "): " + e.getMessage()); + logger.warn("Failed to connect to Docker using configured host ({}:{}): {}", this.config.getHost(), this.config.getPort(), e.getMessage()); logger.info("Falling back to default Docker configuration"); } } @@ -346,7 +345,7 @@ public CreateContainerResponse createContainers(com.github.dockerjava.api.Docker // Set runtime configuration from runtimeConfig map if (runtimeConfig != null && !runtimeConfig.isEmpty()) { - logger.info("Applying runtime configuration: " + runtimeConfig); + logger.info("Applying runtime configuration: {}", runtimeConfig); hostConfig = applyRuntimeConfig(hostConfig, runtimeConfig); createCmd.withHostConfig(hostConfig); } @@ -373,7 +372,7 @@ private HostConfig applyRuntimeConfig(HostConfig hostConfig, Map Long memoryLimit = parseMemoryLimit(memLimitObj); if (memoryLimit != null) { hostConfig = hostConfig.withMemory(memoryLimit); - logger.info("Applied memory limit: " + memoryLimit + " bytes"); + logger.info("Applied memory limit: {} bytes", memoryLimit); } } @@ -383,7 +382,7 @@ private HostConfig applyRuntimeConfig(HostConfig hostConfig, Map Long nanoCpus = parseNanoCpus(nanoCpusObj); if (nanoCpus != null) { hostConfig = hostConfig.withNanoCPUs(nanoCpus); - logger.info("Applied nano CPUs: " + nanoCpus); + logger.info("Applied nano CPUs: {}", nanoCpus); } } @@ -393,9 +392,9 @@ private HostConfig applyRuntimeConfig(HostConfig hostConfig, Map boolean enableGpu = parseBoolean(enableGpuObj); if (enableGpu) { DeviceRequest gpuRequest = new DeviceRequest() - .withCapabilities(Arrays.asList(Arrays.asList("gpu"))) + .withCapabilities(List.of(List.of("gpu"))) .withCount(-1); - hostConfig = hostConfig.withDeviceRequests(Arrays.asList(gpuRequest)); + hostConfig = hostConfig.withDeviceRequests(Collections.singletonList(gpuRequest)); logger.info("Applied GPU support: enabled"); } } @@ -406,8 +405,8 @@ private HostConfig applyRuntimeConfig(HostConfig hostConfig, Map Integer maxConnections = parseInteger(maxConnectionsObj); if (maxConnections != null) { Ulimit ulimit = new Ulimit("nofile", maxConnections.longValue(), maxConnections.longValue()); - hostConfig = hostConfig.withUlimits(Arrays.asList(ulimit)); - logger.info("Applied max connections (nofile limit): " + maxConnections); + hostConfig = hostConfig.withUlimits(List.of(ulimit)); + logger.info("Applied max connections (nofile limit): {}", maxConnections); } } @@ -416,7 +415,7 @@ private HostConfig applyRuntimeConfig(HostConfig hostConfig, Map Object privilegedObj = runtimeConfig.get("privileged"); boolean privileged = parseBoolean(privilegedObj); hostConfig = hostConfig.withPrivileged(privileged); - logger.info("Applied privileged mode: " + privileged); + logger.info("Applied privileged mode: {}", privileged); } return hostConfig; @@ -449,27 +448,19 @@ private Long parseMemoryLimit(Object memLimitObj) { double value = Double.parseDouble(numberPart); - switch (unitPart) { - case "k": - case "kb": - return (long) (value * 1024); - case "m": - case "mb": - return (long) (value * 1024 * 1024); - case "g": - case "gb": - return (long) (value * 1024 * 1024 * 1024); - case "t": - case "tb": - return (long) (value * 1024 * 1024 * 1024 * 1024); - case "": - return (long) value; - default: - logger.warning("Unknown memory unit: " + unitPart); - return null; - } + return switch (unitPart) { + case "k", "kb" -> (long) (value * 1024); + case "m", "mb" -> (long) (value * 1024 * 1024); + case "g", "gb" -> (long) (value * 1024 * 1024 * 1024); + case "t", "tb" -> (long) (value * 1024 * 1024 * 1024 * 1024); + case "" -> (long) value; + default -> { + logger.warn("Unknown memory unit: {}", unitPart); + yield null; + } + }; } catch (NumberFormatException e) { - logger.warning("Failed to parse memory limit: " + memLimitStr); + logger.warn("Failed to parse memory limit: {}", memLimitStr); return null; } } @@ -492,7 +483,7 @@ private Long parseNanoCpus(Object nanoCpusObj) { try { return Long.parseLong(nanoCpusObj.toString()); } catch (NumberFormatException e) { - logger.warning("Failed to parse nano CPUs: " + nanoCpusObj); + logger.warn("Failed to parse nano CPUs: {}", nanoCpusObj); return null; } } @@ -515,7 +506,7 @@ private Integer parseInteger(Object obj) { try { return Integer.parseInt(obj.toString()); } catch (NumberFormatException e) { - logger.warning("Failed to parse integer: " + obj); + logger.warn("Failed to parse integer: {}", obj); return null; } } @@ -548,9 +539,9 @@ private boolean parseBoolean(Object obj) { public void startContainer(com.github.dockerjava.api.DockerClient client, String containerId) { try { client.startContainerCmd(containerId).exec(); - logger.info("Container started successfully: " + containerId); + logger.info("Container started successfully: {}", containerId); } catch (Exception e) { - logger.severe("Failed to start container: " + e.getMessage()); + logger.error("Failed to start container: {}", e.getMessage()); } } @@ -565,12 +556,12 @@ public void stopContainer(com.github.dockerjava.api.DockerClient client, String String status = getContainerStatus(client, containerId); if ("running".equals(status)) { client.stopContainerCmd(containerId).exec(); - logger.info("Container stopped successfully: " + containerId); + logger.info("Container stopped successfully: {}", containerId); } else { - logger.info("Container is already stopped, status: " + status); + logger.info("Container is already stopped, status: {}", status); } } catch (Exception e) { - System.err.println("Failed to stop container: " + e.getMessage()); + logger.error("Failed to stop container: {}", e.getMessage()); } } @@ -586,10 +577,9 @@ public void removeContainer(com.github.dockerjava.api.DockerClient client, Strin .withForce(true) .withRemoveVolumes(true) .exec(); - logger.info("Container deleted successfully: " + containerId); + logger.info("Container deleted successfully: {}", containerId); } catch (Exception e) { - System.err.println("Failed to delete container: " + e.getMessage()); - e.printStackTrace(); + logger.error("Failed to delete container: {}", e.getMessage()); } } @@ -605,7 +595,7 @@ public String getContainerStatus(com.github.dockerjava.api.DockerClient client, InspectContainerResponse response = client.inspectContainerCmd(containerId).exec(); return response.getState().getStatus(); } catch (Exception e) { - System.err.println("Failed to get container status: " + e.getMessage()); + logger.error("Failed to get container status: {}", e.getMessage()); return "unknown"; } } @@ -665,16 +655,16 @@ public boolean imageExists(com.github.dockerjava.api.DockerClient client, String if (repoTags != null) { for (String repoTag : repoTags) { if (repoTag.equals(imageName)) { - logger.info("Image found locally: " + imageName); + logger.info("Image found locally: {}", imageName); return true; } } } } - logger.info("Image not found locally: " + imageName); + logger.info("Image not found locally: {}", imageName); return false; } catch (Exception e) { - logger.severe("Failed to check if image exists: " + e.getMessage()); + logger.error("Failed to check if image exists: {}", e.getMessage()); return false; } } @@ -688,7 +678,7 @@ public boolean imageExists(com.github.dockerjava.api.DockerClient client, String */ public boolean pullImage(com.github.dockerjava.api.DockerClient client, String imageName) { try { - logger.info("Pulling image: " + imageName); + logger.info("Pulling image: {}", imageName); PullImageCmd pullCmd = client.pullImageCmd(imageName); @@ -696,18 +686,18 @@ public boolean pullImage(com.github.dockerjava.api.DockerClient client, String i @Override public void onNext(PullResponseItem item) { if (item.getStatus() != null) { - logger.info("Pull progress: " + item.getStatus()); + logger.info("Pull progress: {}", item.getStatus()); } if (item.getErrorDetail() != null) { - logger.warning("Pull error: " + item.getErrorDetail().getMessage()); + logger.warn("Pull error: {}", item.getErrorDetail().getMessage()); } } }).awaitCompletion(); - logger.info("Successfully pulled image: " + imageName); + logger.info("Successfully pulled image: {}", imageName); return true; } catch (Exception e) { - logger.severe("Failed to pull image " + imageName + ": " + e.getMessage()); + logger.error("Failed to pull image {}: {}", imageName, e.getMessage()); return false; } } diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/manager/client/FcClient.java b/core/src/main/java/io/agentscope/runtime/sandbox/manager/client/FcClient.java index 9e91b52b..0279892f 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/manager/client/FcClient.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/manager/client/FcClient.java @@ -22,6 +22,8 @@ import com.aliyun.teautil.models.RuntimeOptions; import io.agentscope.runtime.sandbox.manager.client.config.FcClientConfig; import io.agentscope.runtime.sandbox.manager.model.fs.VolumeBinding; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.net.URI; import java.net.URISyntaxException; @@ -31,10 +33,9 @@ import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; -import java.util.logging.Logger; public class FcClient extends BaseClient { - private static final Logger logger = Logger.getLogger(FcClient.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(FcClient.class); private static final String HTTPS_PROTOCOL = "https"; private static final int HTTPS_PORT = 443; @@ -51,7 +52,7 @@ public FcClient(FcClientConfig fcClientConfig) throws Exception { this.functionPrefix = fcClientConfig.getFcPrefix() != null ? fcClientConfig.getFcPrefix() : "agentscope-sandbox"; this.fcClient = createFcClient(); - logger.info("FunctionComputeClient initialized successfully with config: " + fcClientConfig); + logger.info("FunctionComputeClient initialized successfully with config: {}", fcClientConfig); testConnection(); } @@ -76,12 +77,12 @@ private void testConnection() { if (response != null && response.getBody() != null && response.getBody().getFunctions() != null) { int funcCount = response.getBody().getFunctions().size(); - logger.info("FunctionComputeClient FC connection test successful: " + funcCount + " functions"); + logger.info("FunctionComputeClient FC connection test successful: {} functions", funcCount); this.connected = true; } } catch (Exception e) { - logger.warning("FunctionComputeClient FC connection test failed: " + e.getMessage()); - logger.warning("FunctionComputeClient This may not affect normal usage. If there are permission issues, please check AccessKey permission configuration."); + logger.warn("FunctionComputeClient FC connection test failed: {}", e.getMessage()); + logger.warn("FunctionComputeClient This may not affect normal usage. If there are permission issues, please check AccessKey permission configuration."); } } @@ -141,7 +142,7 @@ public ContainerCreateResult createContainer(String containerName, String imageN healthCheckConfig.setTimeoutSeconds(1); customContainerConfig.setHealthCheckConfig(healthCheckConfig); - logger.info("FunctionComputeClient building custom health check configuration: " + healthCheckConfig); + logger.info("FunctionComputeClient building custom health check configuration: {}", healthCheckConfig); // 3. Build function creation parameters CreateFunctionInput createFunctionInput = new CreateFunctionInput(); @@ -169,7 +170,7 @@ public ContainerCreateResult createContainer(String containerName, String imageN logConfig.setEnableInstanceMetrics(true); logConfig.setLogBeginRule("DefaultRegex"); createFunctionInput.setLogConfig(logConfig); - logger.info("Configuring log service: " + fcClientConfig.getFcLogProject() + "/" + fcClientConfig.getFcLogStore()); + logger.info("Configuring log service: {}/{}", fcClientConfig.getFcLogProject(), fcClientConfig.getFcLogStore()); } // 5. If VPC configuration exists @@ -179,7 +180,7 @@ public ContainerCreateResult createContainer(String containerName, String imageN vpcConfig.setVSwitchIds(fcClientConfig.getFcVswitchIds()); vpcConfig.setSecurityGroupId(fcClientConfig.getFcSecurityGroupId()); createFunctionInput.setVpcConfig(vpcConfig); - logger.info("Configuring VPC network: " + fcClientConfig.getFcVpcId()); + logger.info("Configuring VPC network: {}", fcClientConfig.getFcVpcId()); } // 6. Create function @@ -192,9 +193,9 @@ public ContainerCreateResult createContainer(String containerName, String imageN CreateFunctionResponse response = fcClient.createFunctionWithOptions(createFunctionRequest, headers, runtimeOptions); logger.info("FunctionComputeClient function created successfully!"); - logger.info("FunctionComputeClient function name: " + response.getBody().getFunctionName()); - logger.info("FunctionComputeClient runtime: " + response.getBody().getRuntime()); - logger.info("FunctionComputeClient create time: " + response.getBody().getCreatedTime()); + logger.info("FunctionComputeClient function name: {}", response.getBody().getFunctionName()); + logger.info("FunctionComputeClient runtime: {}", response.getBody().getRuntime()); + logger.info("FunctionComputeClient create time: {}", response.getBody().getCreatedTime()); // 7. Create HTTP trigger Map triggerInfo = createHttpTrigger(functionName, sessionId); @@ -210,7 +211,7 @@ public ContainerCreateResult createContainer(String containerName, String imageN Thread.currentThread().interrupt(); throw new RuntimeException("Interrupted while waiting for function to be ready", e); } - logger.info("Check function deployment status, function name: " + functionName); + logger.info("Check function deployment status, function name: {}", functionName); } // 9. Create session data @@ -233,7 +234,7 @@ public ContainerCreateResult createContainer(String containerName, String imageN // 10. Register session fcSessionManager.createSession(sessionId, sessionData); - logger.info("FunctionComputeClient FC function " + sessionId + " created and registered session successfully"); + logger.info("FunctionComputeClient FC function {} created and registered session successfully", sessionId); // 11. Parse URL URI parsedUrl; @@ -253,16 +254,16 @@ public ContainerCreateResult createContainer(String containerName, String imageN return new ContainerCreateResult(sessionId, resultPorts, endpointPublicUrlDomain, HTTPS_PROTOCOL); } catch (Exception e) { - logger.severe("Create FC function failed: " + e.getMessage()); + logger.error("Create FC function failed: {}", e.getMessage()); // Provide more detailed error information String errorMsg = e.getMessage(); if (errorMsg != null) { if (errorMsg.contains("InvalidAccessKeyId")) { - logger.severe("Authentication failed, please check if FC_ACCESS_KEY_ID is correct"); + logger.error("Authentication failed, please check if FC_ACCESS_KEY_ID is correct"); } else if (errorMsg.contains("SignatureDoesNotMatch")) { - logger.severe("Signature mismatch, please check if FC_ACCESS_KEY_SECRET is correct"); + logger.error("Signature mismatch, please check if FC_ACCESS_KEY_SECRET is correct"); } else if (errorMsg.contains("Forbidden")) { - logger.severe("Insufficient permissions, please check if AccessKey has FC service permissions"); + logger.error("Insufficient permissions, please check if AccessKey has FC service permissions"); } } throw new RuntimeException("FC function creation failed: " + e.getMessage(), e); @@ -273,7 +274,7 @@ public ContainerCreateResult createContainer(String containerName, String imageN public void startContainer(String containerId) { Map session = fcSessionManager.getSession(containerId); if (session == null) { - logger.warning("FunctionComputeClient session record not found: " + containerId); + logger.warn("FunctionComputeClient session record not found: {}", containerId); return; } @@ -286,7 +287,7 @@ public void startContainer(String containerId) { Thread.sleep(interval * 1000L); } catch (InterruptedException e) { Thread.currentThread().interrupt(); - logger.warning("Interrupted while waiting for FC function to start"); + logger.warn("Interrupted while waiting for FC function to start"); return; } String functionStatus = getContainerStatus(containerId); @@ -295,14 +296,14 @@ public void startContainer(String containerId) { break; } - logger.info("FunctionComputeClient waiting for FC function to be ready... (" + (i + 1) + "/" + maxRetries + ") | " + - "Current status: " + functionStatus + ", session: " + containerId); + logger.info("FunctionComputeClient waiting for FC function to be ready... ({}/{}) | Current status: {}, session: {}", + i + 1, maxRetries, functionStatus, containerId); } String finalStatus = getContainerStatus(containerId); if (!"running".equals(finalStatus)) { - logger.warning("FunctionComputeClient start timeout: Waiting for FC function to enter running state exceeded " + timeoutSeconds + - " seconds, final status: " + finalStatus + ", session: " + containerId); + logger.warn("FunctionComputeClient start timeout: Waiting for FC function to enter running state exceeded {} seconds, final status: {}, session: {}", + timeoutSeconds, finalStatus, containerId); return; } @@ -310,14 +311,14 @@ public void startContainer(String containerId) { Map updates = new HashMap<>(); updates.put("status", "running"); fcSessionManager.updateSession(containerId, updates); - logger.info("FunctionComputeClient FC function started: " + containerId); + logger.info("FunctionComputeClient FC function started: {}", containerId); } @Override public void stopContainer(String containerId) { Map session = fcSessionManager.getSession(containerId); if (session == null) { - logger.warning("FunctionComputeClient session record not found: " + containerId); + logger.warn("FunctionComputeClient session record not found: {}", containerId); return; } @@ -327,9 +328,9 @@ public void stopContainer(String containerId) { Map updates = new HashMap<>(); updates.put("status", "stopped"); fcSessionManager.updateSession(containerId, updates); - logger.info("FunctionComputeClient FC function status set to stopped: " + containerId); + logger.info("FunctionComputeClient FC function status set to stopped: {}", containerId); } catch (Exception e) { - logger.severe("FunctionComputeClient stop FC function failed " + containerId + ": " + e.getMessage()); + logger.error("FunctionComputeClient stop FC function failed {}: {}", containerId, e.getMessage()); } } @@ -341,7 +342,7 @@ public void removeContainer(String containerId) { public void removeContainer(String containerId, boolean force) { Map session = fcSessionManager.getSession(containerId); if (session == null) { - logger.warning("FunctionComputeClient session record not found, skipping deletion: " + containerId); + logger.warn("FunctionComputeClient session record not found, skipping deletion: {}", containerId); return; } @@ -349,15 +350,15 @@ public void removeContainer(String containerId, boolean force) { String triggerName = (String) session.get("trigger_name"); try { - logger.info("FunctionComputeClient starting to delete FC function: " + functionName); + logger.info("FunctionComputeClient starting to delete FC function: {}", functionName); // 1. Delete trigger first (if exists) if (triggerName != null) { try { fcClient.deleteTriggerWithOptions(functionName, triggerName, new HashMap<>(), new RuntimeOptions()); - logger.info("FunctionComputeClient trigger deleted: " + triggerName); + logger.info("FunctionComputeClient trigger deleted: {}", triggerName); } catch (Exception triggerError) { - logger.warning("FunctionComputeClient delete trigger failed (continuing to delete function): " + triggerError.getMessage()); + logger.warn("FunctionComputeClient delete trigger failed (continuing to delete function): {}", triggerError.getMessage()); } } @@ -367,13 +368,13 @@ public void removeContainer(String containerId, boolean force) { // 3. Delete session record fcSessionManager.deleteSession(containerId); - logger.info("FunctionComputeClient FC function deleted successfully: " + functionName); + logger.info("FunctionComputeClient FC function deleted successfully: {}", functionName); } catch (Exception e) { - logger.severe("FunctionComputeClient delete FC function failed: " + e.getMessage()); + logger.error("FunctionComputeClient delete FC function failed: {}", e.getMessage()); if (force) { // Force cleanup - delete session record even if API call fails fcSessionManager.deleteSession(containerId); - logger.warning("FunctionComputeClient force delete session record: " + containerId); + logger.warn("FunctionComputeClient force delete session record: {}", containerId); } else { throw new RuntimeException("FunctionComputeClient FC function removal failed: " + e.getMessage(), e); } @@ -384,7 +385,7 @@ public void removeContainer(String containerId, boolean force) { public String getContainerStatus(String containerId) { Map session = fcSessionManager.getSession(containerId); if (session == null) { - logger.warning("FunctionComputeClient session record not found: " + containerId); + logger.warn("FunctionComputeClient session record not found: {}", containerId); return "not_found"; } @@ -406,7 +407,7 @@ public boolean imageExists(String imageName) { public boolean inspectContainer(String containerIdOrName) { Map session = fcSessionManager.getSession(containerIdOrName); if (session == null) { - logger.warning("FunctionComputeClient session record not found: " + containerIdOrName); + logger.warn("FunctionComputeClient session record not found: {}", containerIdOrName); return false; } @@ -416,11 +417,11 @@ public boolean inspectContainer(String containerIdOrName) { functionQueryRequest.setQualifier("LATEST"); GetFunctionResponse response = fcClient.getFunction(functionName, functionQueryRequest); - logger.info("FunctionComputeClient function inspect: " + response); + logger.info("FunctionComputeClient function inspect: {}", response); return response != null && response.getBody() != null; } catch (Exception e) { - logger.severe("FunctionComputeClient get FC function information failed: " + e.getMessage()); + logger.error("FunctionComputeClient get FC function information failed: {}", e.getMessage()); return false; } } @@ -435,7 +436,7 @@ private boolean checkFunctionReady(String functionName) { String status = getFunctionStatus(functionName); return "running".equals(status); } catch (Exception e) { - logger.severe("Error checking function status: " + e.getMessage()); + logger.error("Error checking function status: {}", e.getMessage()); return false; } } @@ -462,7 +463,7 @@ private String getFunctionStatus(String functionName) { return "unknown"; } } catch (Exception e) { - logger.severe("FunctionComputeClient get FC function status failed: " + e.getMessage()); + logger.error("FunctionComputeClient get FC function status failed: {}", e.getMessage()); // If API call fails, return status from session return "unknown"; } @@ -482,7 +483,7 @@ private Map createHttpTrigger(String functionName, String sessio String triggerName = "sandbox-http-trigger-" + sessionId; try { - logger.info("FunctionComputeClient creating HTTP trigger: " + triggerName); + logger.info("FunctionComputeClient creating HTTP trigger: {}", triggerName); // Build trigger configuration as JSON string // Format: {"authType":"anonymous","methods":["GET","POST","PUT","DELETE","HEAD","OPTIONS"]} @@ -503,8 +504,8 @@ private Map createHttpTrigger(String functionName, String sessio RuntimeOptions runtime = new RuntimeOptions(); CreateTriggerResponse response = fcClient.createTriggerWithOptions(functionName, createTriggerRequest, new HashMap<>(), runtime); - logger.info("FunctionComputeClient HTTP trigger created successfully: " + triggerName); - logger.info("FunctionComputeClient HTTP trigger response: " + response); + logger.info("FunctionComputeClient HTTP trigger created successfully: {}", triggerName); + logger.info("FunctionComputeClient HTTP trigger response: {}", response); // Extract trigger information from response Map triggerInfo = new HashMap<>(); @@ -544,13 +545,13 @@ private Map createHttpTrigger(String functionName, String sessio } logger.info("FunctionComputeClient trigger URL information:"); - logger.info("FunctionComputeClient - Internet URL: " + triggerInfo.get("url_internet")); - logger.info("FunctionComputeClient - Intranet URL: " + triggerInfo.get("url_intranet")); - logger.info("FunctionComputeClient - Trigger ID: " + triggerInfo.get("trigger_id")); + logger.info("FunctionComputeClient - Internet URL: {}", triggerInfo.get("url_internet")); + logger.info("FunctionComputeClient - Intranet URL: {}", triggerInfo.get("url_intranet")); + logger.info("FunctionComputeClient - Trigger ID: {}", triggerInfo.get("trigger_id")); return triggerInfo; } catch (Exception e) { - logger.severe("FunctionComputeClient create HTTP trigger failed: " + e.getMessage()); + logger.error("FunctionComputeClient create HTTP trigger failed: {}", e.getMessage()); // Even if creation fails, return basic information for subsequent cleanup Map triggerInfo = new HashMap<>(); triggerInfo.put("trigger_name", triggerName); @@ -588,12 +589,12 @@ private String replaceFcImages(String image) { } class FCSessionManager { - private static final Logger logger = Logger.getLogger(FCSessionManager.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(FCSessionManager.class); private final Map> sessionMap = new ConcurrentHashMap<>(); public void createSession(String sessionId, Map sessionData) { this.sessionMap.put(sessionId, sessionData); - logger.info("Created FC session: " + sessionId); + logger.info("Created FC session: {}", sessionId); } public Map getSession(String sessionId) { @@ -604,13 +605,13 @@ public void updateSession(String sessionId, Map updates) { Map session = this.sessionMap.get(sessionId); if (session != null) { session.putAll(updates); - logger.info("Updated FC session: " + sessionId); + logger.info("Updated FC session: {}", sessionId); } } public void deleteSession(String sessionId) { this.sessionMap.remove(sessionId); - logger.info("Deleted FC session: " + sessionId); + logger.info("Deleted FC session: {}", sessionId); } public List listSessions() { diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/manager/client/KubernetesClient.java b/core/src/main/java/io/agentscope/runtime/sandbox/manager/client/KubernetesClient.java index 2cf643dd..cd460976 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/manager/client/KubernetesClient.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/manager/client/KubernetesClient.java @@ -25,17 +25,18 @@ import io.kubernetes.client.openapi.apis.CoreV1Api; import io.kubernetes.client.openapi.models.*; import io.kubernetes.client.util.Config; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.File; import java.util.*; -import java.util.logging.Logger; /** * Kubernetes container management client implementation */ public class KubernetesClient extends BaseClient { - private static final Logger logger = Logger.getLogger(KubernetesClient.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(KubernetesClient.class); private static final String DEFAULT_NAMESPACE = "default"; private ApiClient apiClient; @@ -70,7 +71,7 @@ public boolean connect() { if (!kubeconfigFile.exists()) { throw new RuntimeException("Kubeconfig file not found: " + kubeconfigPath); } - logger.info("Loading Kubernetes configuration from file: " + kubeconfigPath); + logger.info("Loading Kubernetes configuration from file: {}", kubeconfigPath); this.apiClient = Config.fromConfig(kubeconfigPath); } else { logger.info("Using default Kubernetes configuration"); @@ -87,7 +88,7 @@ public boolean connect() { this.connected = true; return true; } catch (Exception e) { - logger.warning("API resources check failed, trying alternative connection test: " + e.getMessage()); + logger.warn("API resources check failed, trying alternative connection test: {}", e.getMessage()); ProcessBuilder processBuilder = new ProcessBuilder("kubectl", "cluster-info"); Process process = processBuilder.start(); @@ -102,7 +103,7 @@ public boolean connect() { } } } catch (Exception e) { - logger.severe("Failed to connect to Kubernetes: " + e.getMessage()); + logger.error("Failed to connect to Kubernetes: {}", e.getMessage()); this.connected = false; return false; } @@ -145,9 +146,9 @@ private void validateConfig() { } logger.info("Kubernetes configuration validated successfully"); - logger.info("Using namespace: " + namespace); + logger.info("Using namespace: {}", namespace); if (kubeconfigPath != null) { - logger.info("Using kubeconfig: " + kubeconfigPath); + logger.info("Using kubeconfig: {}", kubeconfigPath); } else { logger.info("Using default kubeconfig"); } @@ -179,7 +180,7 @@ public ContainerCreateResult createContainer(String containerName, String imageN V1Deployment deployment = createDeploymentObject(deploymentName, imageName, ports, portMapping, volumeBindings, environment, runtimeConfig); V1Deployment createdDeployment = appsApi.createNamespacedDeployment(namespace, deployment).execute(); - logger.info("Deployment created: " + createdDeployment.getMetadata().getName()); + logger.info("Deployment created: {}", createdDeployment.getMetadata().getName()); List exposedPorts = new ArrayList<>(); String serviceIp = "localhost"; @@ -187,10 +188,14 @@ public ContainerCreateResult createContainer(String containerName, String imageN if (!portMapping.isEmpty()) { V1Service service = createLoadBalancerServiceObject(serviceName, deploymentName, portMapping); V1Service createdService = coreApi.createNamespacedService(namespace, service).execute(); - logger.info("LoadBalancer Service created: " + createdService.getMetadata().getName() + - ", ports: " + createdService.getSpec().getPorts().stream() - .map(p -> p.getPort() + "->" + p.getTargetPort()) - .toList()); + if (createdService.getSpec() != null) { + if (createdService.getSpec().getPorts() != null) { + logger.info("LoadBalancer Service created: {}, ports: {}", createdService.getMetadata().getName(), + createdService.getSpec().getPorts().stream() + .map(p -> p.getPort() + "->" + p.getTargetPort()) + .toList()); + } + } // Get exposed ports from portMapping for (Integer port : portMapping.values()) { @@ -202,9 +207,9 @@ public ContainerCreateResult createContainer(String containerName, String imageN String externalIP = waitForLoadBalancerExternalIP(deploymentName, 60); if (externalIP != null && !externalIP.isEmpty()) { serviceIp = externalIP; - logger.info("Kubernetes LoadBalancer environment: using External IP " + externalIP); + logger.info("Kubernetes LoadBalancer environment: using External IP {}", externalIP); } else { - logger.warning("Unable to get LoadBalancer External IP, trying pod node IP"); + logger.warn("Unable to get LoadBalancer External IP, trying pod node IP"); // Fallback to pod node IP try { serviceIp = getPodNodeIp(deploymentName); @@ -212,12 +217,12 @@ public ContainerCreateResult createContainer(String containerName, String imageN serviceIp = "localhost"; } } catch (Exception e) { - logger.warning("Failed to get pod node IP, using localhost: " + e.getMessage()); + logger.warn("Failed to get pod node IP, using localhost: {}", e.getMessage()); serviceIp = "localhost"; } } } catch (Exception e) { - logger.warning("Failed to get LoadBalancer External IP, trying pod node IP: " + e.getMessage()); + logger.warn("Failed to get LoadBalancer External IP, trying pod node IP: {}", e.getMessage()); // Fallback to pod node IP try { serviceIp = getPodNodeIp(deploymentName); @@ -225,7 +230,7 @@ public ContainerCreateResult createContainer(String containerName, String imageN serviceIp = "localhost"; } } catch (Exception ex) { - logger.warning("Failed to get pod node IP, using localhost: " + ex.getMessage()); + logger.warn("Failed to get pod node IP, using localhost: {}", ex.getMessage()); serviceIp = "localhost"; } } @@ -234,13 +239,13 @@ public ContainerCreateResult createContainer(String containerName, String imageN return new ContainerCreateResult(deploymentName, exposedPorts, serviceIp); } catch (ApiException e) { - logger.severe("Failed to create container (Deployment/Service): " + e.getMessage()); + logger.error("Failed to create container (Deployment/Service): {}", e.getMessage()); try { appsApi.deleteNamespacedDeployment(deploymentName, namespace).execute(); coreApi.deleteNamespacedService(serviceName, namespace).execute(); - logger.info("Rolled back resources for: " + containerName); + logger.info("Rolled back resources for: {}", containerName); } catch (Exception cleanupEx) { - logger.warning("Failed to rollback after createContainer error: " + cleanupEx.getMessage()); + logger.warn("Failed to rollback after createContainer error: {}", cleanupEx.getMessage()); } throw new RuntimeException("Failed to create container", e); } @@ -281,7 +286,7 @@ private String getPodNodeIp(String podName) { return null; } catch (Exception e) { - logger.warning("Failed to get pod node IP: " + e.getMessage()); + logger.warn("Failed to get pod node IP: {}", e.getMessage()); return null; } } @@ -300,11 +305,13 @@ public String createDeployment(String deploymentName, String imageName, environment, runtimeConfig); V1Deployment createdDeployment = appsApi.createNamespacedDeployment(namespace, deployment).execute(); - logger.info("Deployment created successfully: " + createdDeployment.getMetadata().getName()); + if (createdDeployment.getMetadata() != null) { + logger.info("Deployment created successfully: {}", createdDeployment.getMetadata().getName()); + } return createdDeployment.getMetadata().getName(); } catch (ApiException e) { - logger.severe("Failed to create deployment: " + e.getMessage()); + logger.error("Failed to create deployment: {}", e.getMessage()); throw new RuntimeException("Failed to create deployment", e); } } @@ -425,12 +432,12 @@ private V1Deployment createDeploymentObject(String deploymentName, String imageN .imagePullPolicy("IfNotPresent"); if (runtimeConfig != null && !runtimeConfig.isEmpty()) { - logger.info("Applying runtime configuration to Kubernetes container: " + runtimeConfig); + logger.info("Applying runtime configuration to Kubernetes container: {}", runtimeConfig); container = applyRuntimeConfigToContainer(container, runtimeConfig); } V1PodSpec podSpec = new V1PodSpec() - .containers(Arrays.asList(container)); + .containers(Collections.singletonList(container)); if (!volumes.isEmpty()) { podSpec.volumes(volumes); @@ -464,11 +471,14 @@ public void startContainer(String containerId) { try { V1Deployment deployment = appsApi.readNamespacedDeployment(containerId, namespace).execute(); - Integer replicas = deployment.getStatus().getReplicas(); + Integer replicas = null; + if (deployment.getStatus() != null) { + replicas = deployment.getStatus().getReplicas(); + } Integer readyReplicas = deployment.getStatus().getReadyReplicas(); - logger.info("Deployment " + containerId + " replicas: " + replicas + ", ready: " + readyReplicas); + logger.info("Deployment {} replicas: {}, ready: {}", containerId, replicas, readyReplicas); } catch (ApiException e) { - logger.severe("Failed to start container: " + e.getMessage()); + logger.error("Failed to start container: {}", e.getMessage()); throw new RuntimeException("Failed to start container", e); } } @@ -480,10 +490,10 @@ public void stopContainer(String containerId) { } try { appsApi.deleteNamespacedDeployment(containerId, namespace).execute(); - logger.info("Deployment " + containerId + " deleted successfully"); + logger.info("Deployment {} deleted successfully", containerId); deleteServiceIfExists(containerId); } catch (ApiException e) { - logger.severe("Failed to stop container: " + e.getMessage()); + logger.error("Failed to stop container: {}", e.getMessage()); throw new RuntimeException("Failed to stop container", e); } } @@ -497,15 +507,15 @@ public void removeContainer(String containerId) { try { appsApi.deleteNamespacedDeployment(containerId, namespace).execute(); - logger.info("Deployment " + containerId + " deleted successfully"); + logger.info("Deployment {} deleted successfully", containerId); deleteServiceIfExists(containerId); } catch (ApiException e) { if (e.getCode() == 404) { - logger.info("Deployment " + containerId + " already deleted"); + logger.info("Deployment {} already deleted", containerId); } else { - logger.severe("Failed to remove container: " + e.getMessage()); + logger.error("Failed to remove container: {}", e.getMessage()); throw new RuntimeException("Failed to remove container", e); } } @@ -521,7 +531,7 @@ public String getContainerStatus(String containerId) { V1Deployment deployment = appsApi.readNamespacedDeployment(containerId, namespace).execute(); Integer replicas = deployment.getStatus().getReplicas(); Integer readyReplicas = deployment.getStatus().getReadyReplicas(); - if (readyReplicas != null && replicas != null && readyReplicas.equals(replicas)) { + if (readyReplicas != null && readyReplicas.equals(replicas)) { return "Running"; } else if (readyReplicas != null && readyReplicas > 0) { return "PartiallyReady"; @@ -529,7 +539,7 @@ public String getContainerStatus(String containerId) { return "Pending"; } } catch (ApiException e) { - logger.severe("Failed to get container status: " + e.getMessage()); + logger.error("Failed to get container status: {}", e.getMessage()); return "unknown"; } } @@ -543,7 +553,7 @@ public List listPods() { V1PodList podList = coreApi.listNamespacedPod(namespace).execute(); return podList.getItems(); } catch (ApiException e) { - logger.severe("Failed to list pods: " + e.getMessage()); + logger.error("Failed to list pods: {}", e.getMessage()); throw new RuntimeException("Failed to list pods", e); } catch (Exception e) { return new ArrayList<>(); @@ -559,7 +569,7 @@ public List listDeployments() { V1DeploymentList deploymentList = appsApi.listNamespacedDeployment(namespace).execute(); return deploymentList.getItems(); } catch (ApiException e) { - logger.severe("Failed to list deployments: " + e.getMessage()); + logger.error("Failed to list deployments: {}", e.getMessage()); throw new RuntimeException("Failed to list deployments", e); } } @@ -583,20 +593,20 @@ public String getLoadBalancerExternalIP(String containerId) { V1LoadBalancerIngress firstIngress = ingress.get(0); String externalIP = firstIngress.getIp(); if (externalIP != null && !externalIP.isEmpty()) { - logger.info("LoadBalancer External IP: " + externalIP); + logger.info("LoadBalancer External IP: {}", externalIP); return externalIP; } } } - logger.info("LoadBalancer External IP not yet assigned for service: " + serviceName); + logger.info("LoadBalancer External IP not yet assigned for service: {}", serviceName); return null; } catch (ApiException e) { if (e.getCode() == 404) { - logger.warning("Service " + serviceName + " not found"); + logger.warn("Service {} not found", serviceName); return null; } else { - logger.severe("Failed to get LoadBalancer External IP: " + e.getMessage()); + logger.error("Failed to get LoadBalancer External IP: {}", e.getMessage()); throw new RuntimeException("Failed to get LoadBalancer External IP", e); } } @@ -620,7 +630,7 @@ public String waitForLoadBalancerExternalIP(String containerId, int timeoutSecon } } - logger.warning("Timeout waiting for LoadBalancer External IP for container: " + containerId); + logger.warn("Timeout waiting for LoadBalancer External IP for container: {}", containerId); return null; } @@ -652,7 +662,7 @@ private V1Container applyRuntimeConfigToContainer(V1Container container, Map 0; if (removed) { - logger.fine("Removed container from Redis with key: " + fullKey); + logger.info("Removed container from Redis with key: {}", fullKey); } return removed; @@ -163,7 +164,7 @@ public Map getAll() { } } } catch (Exception e) { - logger.warning("Failed to deserialize container for key " + fullKey + ": " + e.getMessage()); + logger.warn("Failed to deserialize container for key {}: {}", fullKey, e.getMessage()); } } @@ -178,7 +179,7 @@ private SandboxKey parseSandboxKey(String keyString) { try { String[] parts = keyString.split(":", 3); if (parts.length != 3) { - logger.warning("Invalid key format: " + keyString); + logger.warn("Invalid key format: {}", keyString); return null; } @@ -190,7 +191,7 @@ private SandboxKey parseSandboxKey(String keyString) { return new SandboxKey(userID, sessionID, sandboxType); } catch (Exception e) { - logger.warning("Failed to parse SandboxKey from: " + keyString + ", error: " + e.getMessage()); + logger.warn("Failed to parse SandboxKey from: {}, error: {}", keyString, e.getMessage()); return null; } } @@ -202,8 +203,8 @@ public void clear() { for (String fullKey : fullKeys) { redisClient.delete(fullKey); } - - logger.info("Cleared all entries with prefix: " + prefix); + + logger.info("Cleared all entries with prefix: {}", prefix); } public int size() { diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/manager/collections/RedisContainerQueue.java b/core/src/main/java/io/agentscope/runtime/sandbox/manager/collections/RedisContainerQueue.java index b43d0127..0674689e 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/manager/collections/RedisContainerQueue.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/manager/collections/RedisContainerQueue.java @@ -19,15 +19,15 @@ import com.fasterxml.jackson.databind.ObjectMapper; import io.agentscope.runtime.sandbox.manager.model.container.ContainerModel; import io.agentscope.runtime.sandbox.manager.util.RedisClientWrapper; - -import java.util.logging.Logger; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * Redis-backed implementation of ContainerQueue */ public class RedisContainerQueue implements ContainerQueue { - - private static final Logger logger = Logger.getLogger(RedisContainerQueue.class.getName()); + + private static final Logger logger = LoggerFactory.getLogger(RedisContainerQueue.class); private final RedisClientWrapper redisClient; private final String queueName; @@ -37,22 +37,22 @@ public RedisContainerQueue(RedisClientWrapper redisClient, String queueName) { this.redisClient = redisClient; this.queueName = queueName; this.objectMapper = new ObjectMapper(); - logger.info("Redis container queue initialized with name: " + queueName); + logger.info("Redis container queue initialized with name: {}", queueName); } @Override public void enqueue(ContainerModel item) { if (item == null) { - logger.warning("Attempted to enqueue null item, skipping"); + logger.warn("Attempted to enqueue null item, skipping"); return; } try { String json = objectMapper.writeValueAsString(item); redisClient.rpush(queueName, json); - logger.fine("Enqueued container: " + item.getContainerName()); + logger.info("Enqueued container: {}", item.getContainerName()); } catch (JsonProcessingException e) { - logger.severe("Failed to serialize container model: " + e.getMessage()); + logger.error("Failed to serialize container model: {}", e.getMessage()); throw new RuntimeException("Failed to enqueue container", e); } } @@ -66,10 +66,10 @@ public ContainerModel dequeue() { } ContainerModel model = objectMapper.readValue(json, ContainerModel.class); - logger.fine("Dequeued container: " + model.getContainerName()); + logger.info("Dequeued container: {}", model.getContainerName()); return model; } catch (JsonProcessingException e) { - logger.severe("Failed to deserialize container model: " + e.getMessage()); + logger.error("Failed to deserialize container model: {}", e.getMessage()); throw new RuntimeException("Failed to dequeue container", e); } } @@ -84,7 +84,7 @@ public ContainerModel peek() { return objectMapper.readValue(json, ContainerModel.class); } catch (JsonProcessingException e) { - logger.severe("Failed to deserialize container model: " + e.getMessage()); + logger.error("Failed to deserialize container model: {}", e.getMessage()); throw new RuntimeException("Failed to peek container", e); } } @@ -104,7 +104,7 @@ public int size() { @Override public void clear() { redisClient.ltrim(queueName); - logger.info("Cleared Redis queue: " + queueName); + logger.info("Cleared Redis queue: {}", queueName); } } diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/manager/model/container/SandboxKey.java b/core/src/main/java/io/agentscope/runtime/sandbox/manager/model/container/SandboxKey.java index 60ec8a70..cb5df1f3 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/manager/model/container/SandboxKey.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/manager/model/container/SandboxKey.java @@ -15,11 +15,13 @@ */ package io.agentscope.runtime.sandbox.manager.model.container; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.util.Objects; -import java.util.logging.Logger; public class SandboxKey { - Logger logger = Logger.getLogger(SandboxKey.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(SandboxKey.class); private final String userID; private final String sessionID; private final SandboxType sandboxType; @@ -35,7 +37,7 @@ public SandboxKey(String userID, String sessionID, SandboxType sandboxType, Stri public SandboxKey(String userID, String sessionID, SandboxType sandboxType) { this(userID, sessionID, sandboxType, sandboxType == SandboxType.AGENTBAY ? "linux_latest" : ""); if (sandboxType == SandboxType.AGENTBAY) { - logger.warning("Creating SandboxKey without default \"linux_latest\" imageID for AGENTBAY type."); + logger.warn("Creating SandboxKey without default \"linux_latest\" imageID for AGENTBAY type."); } } diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/manager/registry/SandboxAnnotationProcessor.java b/core/src/main/java/io/agentscope/runtime/sandbox/manager/registry/SandboxAnnotationProcessor.java index 90f8a953..a8b03707 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/manager/registry/SandboxAnnotationProcessor.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/manager/registry/SandboxAnnotationProcessor.java @@ -18,13 +18,14 @@ import io.agentscope.runtime.sandbox.box.*; import io.agentscope.runtime.sandbox.manager.model.container.SandboxConfig; import io.agentscope.runtime.sandbox.manager.model.container.SandboxType; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; -import java.util.logging.Logger; public class SandboxAnnotationProcessor { - private static final Logger logger = Logger.getLogger(SandboxAnnotationProcessor.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(SandboxAnnotationProcessor.class); /** * Process a single class with @RegisterSandbox annotation @@ -75,21 +76,17 @@ public static void processClass(Class clazz) { environment, runtimeConfig ); - logger.info("Registered custom sandbox via annotation: " + - "type=" + customType + - ", class=" + clazz.getSimpleName() + - ", image=" + imageName); + logger.info("Registered custom sandbox via annotation: type={}, class={}, image={}", + customType, clazz.getSimpleName(), imageName); } else { SandboxRegistryService.register(clazz, config); - logger.info("Registered sandbox via annotation: " + - "type=" + sandboxType + - ", class=" + clazz.getSimpleName() + - ", image=" + imageName); + logger.info("Registered sandbox via annotation: type={}, class={}, image={}", + sandboxType, clazz.getSimpleName(), imageName); } } catch (Exception e) { - logger.severe("Failed to process @RegisterSandbox annotation on class " + - clazz.getName() + ": " + e.getMessage()); + logger.error("Failed to process @RegisterSandbox annotation on class {}: {}", + clazz.getName(), e.getMessage()); throw new RuntimeException("Failed to register sandbox: " + clazz.getName(), e); } } @@ -100,8 +97,8 @@ public static void processClass(Class clazz) { * @param packageName Package name */ public static void scanAndRegisterPackage(String packageName) { - logger.info("Scanning package for @RegisterSandbox annotations: " + packageName); - logger.warning("Package scanning not fully implemented. " + + logger.info("Scanning package for @RegisterSandbox annotations: {}", packageName); + logger.warn("Package scanning not fully implemented. " + "Please call processClass() manually for each sandbox class " + "or use a classpath scanner like Reflections library."); } @@ -117,49 +114,49 @@ public static void registerAllKnownSandboxes() { Class baseSandboxClass = Class.forName(BaseSandbox.class.getName()); processClass(baseSandboxClass); } catch (ClassNotFoundException e) { - logger.fine("BaseSandbox class not found, skipping: " + e.getMessage()); + logger.info("BaseSandbox class not found, skipping: {}", e.getMessage()); } try { Class filesystemSandboxClass = Class.forName(FilesystemSandbox.class.getName()); processClass(filesystemSandboxClass); } catch (ClassNotFoundException e) { - logger.fine("FilesystemSandbox class not found, skipping: " + e.getMessage()); + logger.info("FilesystemSandbox class not found, skipping: {}", e.getMessage()); } try { Class browserSandboxClass = Class.forName(BrowserSandbox.class.getName()); processClass(browserSandboxClass); } catch (ClassNotFoundException e) { - logger.fine("BrowserSandbox class not found, skipping: " + e.getMessage()); + logger.info("BrowserSandbox class not found, skipping: {}", e.getMessage()); } try { Class dummySandboxClass = Class.forName(DummySandbox.class.getName()); processClass(dummySandboxClass); } catch (ClassNotFoundException e) { - logger.fine("DummySandbox class not found, skipping: " + e.getMessage()); + logger.info("DummySandbox class not found, skipping: {}", e.getMessage()); } try { Class bfclSandboxClass = Class.forName(BFCLSandbox.class.getName()); processClass(bfclSandboxClass); } catch (ClassNotFoundException e) { - logger.fine("BFCLSandbox class not found, skipping: " + e.getMessage()); + logger.info("BFCLSandbox class not found, skipping: {}", e.getMessage()); } try { Class appworldSandboxClass = Class.forName(APPWorldSandbox.class.getName()); processClass(appworldSandboxClass); } catch (ClassNotFoundException e) { - logger.fine("APPWorldSandbox class not found, skipping: " + e.getMessage()); + logger.info("APPWorldSandbox class not found, skipping: {}", e.getMessage()); } try { Class webshopSandboxClass = Class.forName(WebShopSandbox.class.getName()); processClass(webshopSandboxClass); } catch (ClassNotFoundException e) { - logger.fine("WebShopSandbox class not found, skipping: " + e.getMessage()); + logger.info("WebShopSandbox class not found, skipping: {}", e.getMessage()); } logger.info("Finished registering sandbox classes"); @@ -172,7 +169,7 @@ public static void registerAllKnownSandboxes() { */ private static Map parseKeyValueArray(String[] array) { Map result = new HashMap<>(); - if (array == null || array.length == 0) { + if (array == null) { return result; } @@ -188,7 +185,7 @@ private static Map parseKeyValueArray(String[] array) { value = resolveEnvironmentVariables(value); result.put(key, value); } else { - logger.warning("Invalid key-value pair format: " + item); + logger.warn("Invalid key-value pair format: {}", item); } } @@ -242,7 +239,7 @@ private static String resolveEnvironmentVariables(String value) { result.append(envValue); } else { result.append(defaultValue); - logger.fine("Environment variable '" + envVarName + "' not found, using default: '" + defaultValue + "'"); + logger.info("Environment variable '{}' not found, using default: '{}'", envVarName, defaultValue); } startIndex = placeholderEnd + 1; @@ -257,7 +254,7 @@ private static String resolveEnvironmentVariables(String value) { */ private static Map parseKeyValueArrayAsObject(String[] array) { Map result = new HashMap<>(); - if (array == null || array.length == 0) { + if (array == null) { return result; } @@ -273,7 +270,7 @@ private static Map parseKeyValueArrayAsObject(String[] array) { Object parsedValue = parseValue(value); result.put(key, parsedValue); } else { - logger.warning("Invalid key-value pair format: " + item); + logger.warn("Invalid key-value pair format: {}", item); } } @@ -286,7 +283,7 @@ private static Map parseKeyValueArrayAsObject(String[] array) { */ private static Map parseResourceLimits(String[] array) { Map result = new HashMap<>(); - if (array == null || array.length == 0) { + if (array == null) { return result; } @@ -307,7 +304,7 @@ private static Map parseResourceLimits(String[] array) { double cpuValue = Double.parseDouble(value); result.put("cpu", cpuValue); } catch (NumberFormatException e) { - logger.warning("Invalid CPU value: " + value); + logger.warn("Invalid CPU value: {}", value); result.put("cpu", value); } } else { diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/manager/registry/SandboxRegistry.java b/core/src/main/java/io/agentscope/runtime/sandbox/manager/registry/SandboxRegistry.java index bc143adb..82bdbf50 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/manager/registry/SandboxRegistry.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/manager/registry/SandboxRegistry.java @@ -18,18 +18,19 @@ import io.agentscope.runtime.sandbox.manager.model.container.DynamicSandboxType; import io.agentscope.runtime.sandbox.manager.model.container.SandboxConfig; import io.agentscope.runtime.sandbox.manager.model.container.SandboxType; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; -import java.util.logging.Logger; /** * Sandbox registry for managing sandbox configurations */ public class SandboxRegistry { - private static final Logger logger = Logger.getLogger(SandboxRegistry.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(SandboxRegistry.class); private static final Map, SandboxConfig> classRegistry = new ConcurrentHashMap<>(); private static final Map> typeRegistry = new ConcurrentHashMap<>(); @@ -42,7 +43,7 @@ public class SandboxRegistry { Class.forName(SandboxRegistryInitializer.class.getName()); logger.info("SandboxRegistryInitializer loaded and executed"); } catch (ClassNotFoundException e) { - logger.warning("SandboxRegistryInitializer not found, annotation-based registration disabled"); + logger.warn("SandboxRegistryInitializer not found, annotation-based registration disabled"); } } @@ -66,9 +67,7 @@ public static void register(Class targetClass, SandboxConfig config) { typeRegistry.put(sandboxType, targetClass); typeConfigRegistry.put(sandboxType, config); - logger.info("Registered sandbox: type=" + sandboxType + - ", class=" + targetClass.getSimpleName() + - ", image=" + config.getImageName()); + logger.info("Registered sandbox: type={}, class={}, image={}", sandboxType, targetClass.getSimpleName(), config.getImageName()); } /** @@ -85,7 +84,7 @@ public static void register(SandboxType sandboxType, String imageName) { .build(); typeConfigRegistry.put(sandboxType, config); - logger.info("Registered sandbox: type=" + sandboxType + ", image=" + imageName); + logger.info("Registered sandbox: type={}, image={}", sandboxType, imageName); } /** @@ -123,9 +122,7 @@ public static void register( typeConfigRegistry.put(sandboxType, config); - logger.info("Registered sandbox with full config: type=" + sandboxType + - ", image=" + imageName + - ", timeout=" + timeout + "s"); + logger.info("Registered sandbox with full config: type={}, image={}, timeout={}s", sandboxType, imageName, timeout); } /** @@ -220,7 +217,7 @@ public static boolean unregister(SandboxType sandboxType) { } if (config != null) { - logger.info("Unregistered sandbox: type=" + sandboxType); + logger.info("Unregistered sandbox: type={}", sandboxType); return true; } return false; @@ -262,7 +259,7 @@ public static void registerCustomType(String typeName, String imageName) { .build(); customTypeRegistry.put(typeName.toLowerCase(), config); - logger.info("Registered custom sandbox type: name=" + typeName + ", image=" + imageName); + logger.info("Registered custom sandbox type: name={}, image={}", typeName, imageName); } /** @@ -302,9 +299,7 @@ public static void registerCustomType( customTypeRegistry.put(typeName.toLowerCase(), config); - logger.info("Registered custom sandbox type with full config: name=" + typeName + - ", image=" + imageName + - ", timeout=" + timeout + "s"); + logger.info("Registered custom sandbox type with full config: name={}, image={}, timeout={}s", typeName, imageName, timeout); } /** diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/manager/registry/SandboxRegistryInitializer.java b/core/src/main/java/io/agentscope/runtime/sandbox/manager/registry/SandboxRegistryInitializer.java index 348d14f8..65490d67 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/manager/registry/SandboxRegistryInitializer.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/manager/registry/SandboxRegistryInitializer.java @@ -15,15 +15,17 @@ */ package io.agentscope.runtime.sandbox.manager.registry; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.util.Collection; import java.util.LinkedHashSet; import java.util.ServiceLoader; import java.util.Set; -import java.util.logging.Logger; import java.util.stream.Collectors; public class SandboxRegistryInitializer { - private static final Logger logger = Logger.getLogger(SandboxRegistryInitializer.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(SandboxRegistryInitializer.class); private static boolean initialized = false; static { @@ -47,7 +49,7 @@ public static synchronized void initialize() { initialized = true; logger.info("SandboxRegistryService initialization completed successfully"); } catch (Exception e) { - logger.severe("Failed to initialize SandboxRegistryService: " + e.getMessage()); + logger.error("Failed to initialize SandboxRegistryService: {}", e.getMessage()); throw new RuntimeException("Failed to initialize SandboxRegistryService", e); } } @@ -60,7 +62,7 @@ private static void registerViaSpi() { try { Collection> classes = provider.getSandboxClasses(); if (classes == null) { - logger.fine("Provider " + provider.getClass().getName() + " returned null class list, skipping"); + logger.info("Provider {} returned null class list, skipping", provider.getClass().getName()); continue; } @@ -72,23 +74,21 @@ private static void registerViaSpi() { registered.add(clazz); } - logger.info("Sandbox SPI provider loaded: " + provider.getClass().getName() - + ", provided=" + classes.size()); + logger.info("Sandbox SPI provider loaded: {}, provided={}", provider.getClass().getName(), classes.size()); } catch (Exception e) { - logger.warning("Failed to load sandboxes from provider " + provider.getClass().getName() - + ": " + e.getMessage()); + logger.warn("Failed to load sandboxes from provider {}: {}", provider.getClass().getName(), e.getMessage()); } } if (registered.isEmpty()) { - logger.warning("No sandbox classes discovered via SPI; registry is empty until providers are added."); + logger.warn("No sandbox classes discovered via SPI; registry is empty until providers are added."); return; } String summary = registered.stream() .map(Class::getSimpleName) .collect(Collectors.joining(", ")); - logger.info("Registered sandboxes via SPI: " + summary); + logger.info("Registered sandboxes via SPI: {}", summary); } diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/manager/registry/SandboxRegistryService.java b/core/src/main/java/io/agentscope/runtime/sandbox/manager/registry/SandboxRegistryService.java index f9b1af74..3f760a4f 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/manager/registry/SandboxRegistryService.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/manager/registry/SandboxRegistryService.java @@ -18,18 +18,19 @@ import io.agentscope.runtime.sandbox.manager.model.container.DynamicSandboxType; import io.agentscope.runtime.sandbox.manager.model.container.SandboxConfig; import io.agentscope.runtime.sandbox.manager.model.container.SandboxType; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; -import java.util.logging.Logger; /** * Sandbox registry for managing sandbox configurations */ public class SandboxRegistryService { - private static final Logger logger = Logger.getLogger(SandboxRegistryService.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(SandboxRegistryService.class); private static final Map, SandboxConfig> classRegistry = new ConcurrentHashMap<>(); private static final Map> typeRegistry = new ConcurrentHashMap<>(); @@ -42,7 +43,7 @@ public class SandboxRegistryService { Class.forName(SandboxRegistryInitializer.class.getName()); logger.info("SandboxRegistryInitializer loaded and executed"); } catch (ClassNotFoundException e) { - logger.warning("SandboxRegistryInitializer not found, annotation-based registration disabled"); + logger.warn("SandboxRegistryInitializer not found, annotation-based registration disabled"); } } @@ -66,9 +67,7 @@ public static void register(Class targetClass, SandboxConfig config) { typeRegistry.put(sandboxType, targetClass); typeConfigRegistry.put(sandboxType, config); - logger.info("Registered sandbox: type=" + sandboxType + - ", class=" + targetClass.getSimpleName() + - ", image=" + config.getImageName()); + logger.info("Registered sandbox: type={}, class={}, image={}", sandboxType, targetClass.getSimpleName(), config.getImageName()); } /** @@ -85,7 +84,7 @@ public static void register(SandboxType sandboxType, String imageName) { .build(); typeConfigRegistry.put(sandboxType, config); - logger.info("Registered sandbox: type=" + sandboxType + ", image=" + imageName); + logger.info("Registered sandbox: type={}, image={}", sandboxType, imageName); } /** @@ -123,9 +122,7 @@ public static void register( typeConfigRegistry.put(sandboxType, config); - logger.info("Registered sandbox with full config: type=" + sandboxType + - ", image=" + imageName + - ", timeout=" + timeout + "s"); + logger.info("Registered sandbox with full config: type={}, image={}, timeout={}s", sandboxType, imageName, timeout); } /** @@ -220,7 +217,7 @@ public static boolean unregister(SandboxType sandboxType) { } if (config != null) { - logger.info("Unregistered sandbox: type=" + sandboxType); + logger.info("Unregistered sandbox: type={}", sandboxType); return true; } return false; @@ -262,7 +259,7 @@ public static void registerCustomType(String typeName, String imageName) { .build(); customTypeRegistry.put(typeName.toLowerCase(), config); - logger.info("Registered custom sandbox type: name=" + typeName + ", image=" + imageName); + logger.info("Registered custom sandbox type: name={}, image={}", typeName, imageName); } /** @@ -304,9 +301,7 @@ public static void registerCustomType( customTypeRegistry.put(typeName.toLowerCase(), config); - logger.info("Registered custom sandbox type with full config: name=" + typeName + - ", image=" + imageName + - ", timeout=" + timeout + "s"); + logger.info("Registered custom sandbox type with full config: name={}, image={}, timeout={}s", typeName, imageName, timeout); } /** diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/manager/remote/RemoteHttpClient.java b/core/src/main/java/io/agentscope/runtime/sandbox/manager/remote/RemoteHttpClient.java index ff6f6840..4b537d52 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/manager/remote/RemoteHttpClient.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/manager/remote/RemoteHttpClient.java @@ -16,6 +16,9 @@ package io.agentscope.runtime.sandbox.manager.remote; import com.fasterxml.jackson.databind.ObjectMapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.net.URI; import java.net.URLEncoder; import java.net.http.HttpClient; @@ -24,15 +27,14 @@ import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; -import java.util.logging.Logger; /** * HTTP client for making remote calls to SandboxManager server. * This client handles the communication with the remote SandboxManager service. */ public class RemoteHttpClient { - - private static final Logger logger = Logger.getLogger(RemoteHttpClient.class.getName()); + + private static final Logger logger = LoggerFactory.getLogger(RemoteHttpClient.class); private final HttpClient httpClient; private final String baseUrl; private final String bearerToken; @@ -56,8 +58,8 @@ public RemoteHttpClient(String baseUrl, String bearerToken) { */ public Object makeRequest(RequestMethod method, String endpoint, Map data, String successKey) { String url = baseUrl + (endpoint.startsWith("/") ? endpoint : "/" + endpoint); - - logger.info("Making " + method + " request to: " + url); + + logger.info("Making {} request to: {}", method, url); try { HttpRequest request = buildHttpRequest(method, url, data); @@ -68,7 +70,7 @@ public Object makeRequest(RequestMethod method, String endpoint, Map= 300) { String errorMessage = extractErrorMessage(body, statusCode); - logger.severe("HTTP error: " + statusCode + " - " + errorMessage); + logger.error("HTTP error: {} - {}", statusCode, errorMessage); Map errorResponse = new HashMap<>(); errorResponse.put("error", errorMessage); if (successKey != null && !successKey.isEmpty()) { @@ -78,7 +80,7 @@ public Object makeRequest(RequestMethod method, String endpoint, Map errorResponse = new HashMap<>(); errorResponse.put("error", "Error: " + e.getMessage()); if (successKey != null && !successKey.isEmpty()) { @@ -154,7 +155,7 @@ private String extractErrorMessage(String responseBody, int statusCode) { return responseBody; } } catch (Exception parseException) { - logger.warning("Failed to parse error response: " + parseException.getMessage()); + logger.warn("Failed to parse error response: {}", parseException.getMessage()); } return "HTTP " + statusCode + " Error"; } diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/manager/util/PortManager.java b/core/src/main/java/io/agentscope/runtime/sandbox/manager/util/PortManager.java index 1e86a2b2..d4828994 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/manager/util/PortManager.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/manager/util/PortManager.java @@ -16,6 +16,8 @@ package io.agentscope.runtime.sandbox.manager.util; import io.agentscope.runtime.sandbox.manager.model.container.PortRange; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.InetSocketAddress; @@ -23,14 +25,13 @@ import java.util.HashSet; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; -import java.util.logging.Logger; /** * Thread-safe port allocation manager * Manages port allocation and release to avoid port conflicts */ public class PortManager { - private static final Logger logger = Logger.getLogger(PortManager.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(PortManager.class); private final Set allocatedPorts = ConcurrentHashMap.newKeySet(); @@ -40,8 +41,7 @@ public class PortManager { public PortManager(PortRange portRange) { this.portRange = portRange; - logger.info("PortManager initialized with port range: " + - portRange.getStart() + "-" + portRange.getEnd()); + logger.info("PortManager initialized with port range: {}-{}", portRange.getStart(), portRange.getEnd()); } /** @@ -61,12 +61,12 @@ public synchronized int allocatePort() { if (isPortAvailable(port)) { allocatedPorts.add(port); - logger.fine("Allocated port: " + port); + logger.info("Allocated port: {}", port); return port; } } - - logger.warning("No available ports in range " + startPort + "-" + endPort); + + logger.warn("No available ports in range {}-{}", startPort, endPort); return -1; } @@ -116,7 +116,7 @@ public void registerContainerPorts(String containerName, int... ports) { for (int port : ports) { portSet.add(port); } - logger.fine("Registered " + ports.length + " port(s) for container: " + containerName); + logger.info("Registered {} port(s) for container: {}", ports.length, containerName); } /** @@ -126,7 +126,7 @@ public void registerContainerPorts(String containerName, int... ports) { */ public synchronized void releasePort(int port) { if (allocatedPorts.remove(port)) { - logger.fine("Released port: " + port); + logger.info("Released port: {}", port); } } @@ -141,7 +141,7 @@ public synchronized void releaseContainerPorts(String containerName) { for (int port : ports) { allocatedPorts.remove(port); } - logger.fine("Released " + ports.size() + " port(s) for container: " + containerName); + logger.info("Released {} port(s) for container: {}", ports.size(), containerName); } } diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/manager/util/RedisClientWrapper.java b/core/src/main/java/io/agentscope/runtime/sandbox/manager/util/RedisClientWrapper.java index aefa1d41..63d54118 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/manager/util/RedisClientWrapper.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/manager/util/RedisClientWrapper.java @@ -20,18 +20,19 @@ import io.lettuce.core.RedisURI; import io.lettuce.core.api.StatefulRedisConnection; import io.lettuce.core.api.sync.RedisCommands; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.List; import java.util.Set; -import java.util.logging.Logger; /** * Redis Client wrapper for managing Redis connections and operations * Uses Lettuce as the underlying Redis client */ public class RedisClientWrapper implements AutoCloseable { - - private static final Logger logger = Logger.getLogger(RedisClientWrapper.class.getName()); + + private static final Logger logger = LoggerFactory.getLogger(RedisClientWrapper.class); private final RedisClient redisClient; private final StatefulRedisConnection connection; @@ -43,7 +44,7 @@ public class RedisClientWrapper implements AutoCloseable { * @param config Redis manager configuration */ public RedisClientWrapper(RedisManagerConfig config) { - logger.info("Initializing Redis client with server: " + config.getRedisServer() + ":" + config.getRedisPort()); + logger.info("Initializing Redis client with server: {}:{}", config.getRedisServer(), config.getRedisPort()); RedisURI.Builder uriBuilder = RedisURI.builder() .withHost(config.getRedisServer()) diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/manager/util/SandboxHttpClient.java b/core/src/main/java/io/agentscope/runtime/sandbox/manager/util/SandboxHttpClient.java index bef20b9f..c35265e3 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/manager/util/SandboxHttpClient.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/manager/util/SandboxHttpClient.java @@ -17,6 +17,8 @@ import com.fasterxml.jackson.databind.ObjectMapper; import io.agentscope.runtime.sandbox.manager.model.container.ContainerModel; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.URI; @@ -26,14 +28,13 @@ import java.time.Duration; import java.util.HashMap; import java.util.Map; -import java.util.logging.Logger; /** * Sandbox HTTP Client * Used for HTTP communication with sandbox containers and calling tools within the sandbox */ public class SandboxHttpClient extends SandboxClient { - private static final Logger logger = Logger.getLogger(SandboxHttpClient.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(SandboxHttpClient.class); private static final ObjectMapper objectMapper = new ObjectMapper(); private final String sessionId; @@ -88,7 +89,7 @@ public void waitUntilHealthy() { while (System.currentTimeMillis() - startTime < timeoutMillis) { if (checkHealth()) { - logger.info("Sandbox service is healthy: " + baseUrl); + logger.info("Sandbox service is healthy: {}", baseUrl); return; } @@ -116,7 +117,7 @@ public Map listTools(String toolType, Map argume HttpResponse.BodyHandlers.ofString()); if (response.statusCode() != 200) { - logger.warning("Failed to list tools: HTTP " + response.statusCode()); + logger.warn("Failed to list tools: HTTP {}", response.statusCode()); return new HashMap<>(); } @@ -134,7 +135,7 @@ public Map listTools(String toolType, Map argume return tools; } catch (Exception e) { - logger.severe("Error listing tools: " + e.getMessage()); + logger.error("Error listing tools: {}", e.getMessage()); return new HashMap<>(); } } @@ -171,8 +172,7 @@ public String callTool(String toolName, Map arguments) { return response.body(); } catch (Exception e) { - logger.severe("Error calling tool " + toolName + ": " + e.getMessage()); - e.printStackTrace(); + logger.error("Error calling tool {}: {}", toolName, e.getMessage()); return createErrorResponse("Error calling tool: " + e.getMessage()); } } @@ -196,7 +196,7 @@ public Map addMcpServers(Map serverConfigs, bool HttpResponse.BodyHandlers.ofString()); if (response.statusCode() != 200) { - logger.warning("Failed to add MCP servers: HTTP " + response.statusCode()); + logger.warn("Failed to add MCP servers: HTTP {}", response.statusCode()); return new HashMap<>(); } @@ -204,7 +204,7 @@ public Map addMcpServers(Map serverConfigs, bool Map result = objectMapper.readValue(response.body(), Map.class); return result; } catch (Exception e) { - logger.severe("Error adding MCP servers: " + e.getMessage()); + logger.error("Error adding MCP servers: {}", e.getMessage()); return new HashMap<>(); } } @@ -232,7 +232,7 @@ private String callGenericTool(String toolName, Map arguments) { return response.body(); } catch (Exception e) { - logger.severe("Error calling generic tool " + toolName + ": " + e.getMessage()); + logger.error("Error calling generic tool {}: {}", toolName, e.getMessage()); return createErrorResponse("Error calling generic tool: " + e.getMessage()); } } diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/manager/util/StorageManager.java b/core/src/main/java/io/agentscope/runtime/sandbox/manager/util/StorageManager.java index 4e23de77..09cac0b7 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/manager/util/StorageManager.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/manager/util/StorageManager.java @@ -24,6 +24,8 @@ import io.agentscope.runtime.sandbox.manager.model.fs.FileSystemConfig; import io.agentscope.runtime.sandbox.manager.model.fs.FileSystemType; import io.agentscope.runtime.sandbox.manager.model.fs.OssConfig; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileOutputStream; @@ -33,13 +35,12 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; -import java.util.logging.Logger; /** * Storage Manager responsible for handling file downloads from local and cloud storage */ public class StorageManager { - private static final Logger logger = Logger.getLogger(StorageManager.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(StorageManager.class); private final FileSystemConfig fileSystemConfig; private OSS ossClient; @@ -54,7 +55,7 @@ public StorageManager(FileSystemConfig fileSystemConfig) { ossConfig.getOssAccessKeyId(), ossConfig.getOssAccessKeySecret() ); - logger.info("OSS client initialized with endpoint: " + ossConfig.getOssEndpoint()); + logger.info("OSS client initialized with endpoint: {}", ossConfig.getOssEndpoint()); } } @@ -86,12 +87,12 @@ public String pathJoin(String... parts) { */ public boolean downloadFolder(String storagePath, String localDir) { if (storagePath == null || storagePath.isEmpty()) { - logger.warning("Storage path is empty, skipping download"); + logger.warn("Storage path is empty, skipping download"); return false; } if (localDir == null || localDir.isEmpty()) { - logger.warning("Local directory is empty, skipping download"); + logger.warn("Local directory is empty, skipping download"); return false; } @@ -103,7 +104,7 @@ public boolean downloadFolder(String storagePath, String localDir) { return copyLocalFolder(storagePath, localDir); } } catch (Exception e) { - logger.severe("Failed to download folder from " + storagePath + " to " + localDir + ": " + e.getMessage()); + logger.error("Failed to download folder from {} to {}: {}", storagePath, localDir, e.getMessage()); return false; } } @@ -117,7 +118,7 @@ public boolean downloadFolder(String storagePath, String localDir) { */ private boolean downloadFromOss(String ossPrefix, String localDir) { if (ossClient == null || !(fileSystemConfig instanceof OssConfig ossConfig)) { - logger.severe("OSS client not initialized"); + logger.error("OSS client not initialized"); return false; } @@ -133,7 +134,7 @@ private boolean downloadFromOss(String ossPrefix, String localDir) { // Ensure prefix ends with / String prefix = ossPrefix.endsWith("/") ? ossPrefix : ossPrefix + "/"; - logger.info("Downloading from OSS bucket: " + bucketName + ", prefix: " + prefix + " to " + localDir); + logger.info("Downloading from OSS bucket: {}, prefix: {} to {}", bucketName, prefix, localDir); // List all objects ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName) @@ -176,21 +177,20 @@ private boolean downloadFromOss(String ossPrefix, String localDir) { } } downloadedCount++; - logger.fine("Downloaded: " + objectKey + " to " + localFile.getAbsolutePath()); + logger.info("Downloaded: {} to {}", objectKey, localFile.getAbsolutePath()); } catch (Exception e) { - logger.warning("Failed to download " + objectKey + ": " + e.getMessage()); + logger.warn("Failed to download {}: {}", objectKey, e.getMessage()); } } listObjectsRequest.setMarker(objectListing.getNextMarker()); } while (objectListing.isTruncated()); - logger.info("Downloaded " + downloadedCount + " files from OSS"); + logger.info("Downloaded {} files from OSS", downloadedCount); return true; } catch (Exception e) { - logger.severe("Failed to download from OSS: " + e.getMessage()); - e.printStackTrace(); + logger.error("Failed to download from OSS: {}", e.getMessage()); return false; } } @@ -208,7 +208,7 @@ private boolean copyLocalFolder(String sourcePath, String targetPath) { Path target = Paths.get(targetPath); if (!Files.exists(source)) { - logger.warning("Source path does not exist: " + sourcePath); + logger.warn("Source path does not exist: {}", sourcePath); return false; } @@ -231,7 +231,7 @@ private boolean copyLocalFolder(String sourcePath, String targetPath) { Files.copy(srcPath, destPath, StandardCopyOption.REPLACE_EXISTING); } } catch (IOException e) { - logger.warning("Failed to copy " + srcPath + ": " + e.getMessage()); + logger.warn("Failed to copy {}: {}", srcPath, e.getMessage()); } }); } else { @@ -239,12 +239,11 @@ private boolean copyLocalFolder(String sourcePath, String targetPath) { Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING); } - logger.info("Copied folder from " + sourcePath + " to " + targetPath); + logger.info("Copied folder from {} to {}", sourcePath, targetPath); return true; } catch (Exception e) { - logger.severe("Failed to copy local folder: " + e.getMessage()); - e.printStackTrace(); + logger.error("Failed to copy local folder: {}", e.getMessage()); return false; } } @@ -258,19 +257,19 @@ private boolean copyLocalFolder(String sourcePath, String targetPath) { */ public boolean uploadFolder(String localDir, String storagePath) { if (localDir == null || localDir.isEmpty()) { - logger.warning("Local directory is empty, skipping upload"); + logger.warn("Local directory is empty, skipping upload"); return false; } if (storagePath == null || storagePath.isEmpty()) { - logger.warning("Storage path is empty, skipping upload"); + logger.warn("Storage path is empty, skipping upload"); return false; } // Check if local directory exists File localDirectory = new File(localDir); if (!localDirectory.exists()) { - logger.warning("Local directory does not exist: " + localDir); + logger.warn("Local directory does not exist: {}", localDir); return false; } @@ -281,8 +280,7 @@ public boolean uploadFolder(String localDir, String storagePath) { return copyLocalFolder(localDir, storagePath); } } catch (Exception e) { - logger.severe("Failed to upload folder from " + localDir + " to " + storagePath + ": " + e.getMessage()); - e.printStackTrace(); + logger.error("Failed to upload folder from {} to {}: {}", localDir, storagePath, e.getMessage()); return false; } } @@ -296,14 +294,14 @@ public boolean uploadFolder(String localDir, String storagePath) { */ private boolean uploadToOss(String localDir, String ossPrefix) { if (ossClient == null || !(fileSystemConfig instanceof OssConfig ossConfig)) { - logger.severe("OSS client not initialized"); + logger.error("OSS client not initialized"); return false; } try { File localDirectory = new File(localDir); if (!localDirectory.exists() || !localDirectory.isDirectory()) { - logger.warning("Local directory does not exist or is not a directory: " + localDir); + logger.warn("Local directory does not exist or is not a directory: {}", localDir); return false; } @@ -312,17 +310,16 @@ private boolean uploadToOss(String localDir, String ossPrefix) { // Ensure prefix ends with / String prefix = ossPrefix.endsWith("/") ? ossPrefix : ossPrefix + "/"; - logger.info("Uploading to OSS bucket: " + bucketName + ", prefix: " + prefix + " from " + localDir); + logger.info("Uploading to OSS bucket: {}, prefix: {} from {}", bucketName, prefix, localDir); int uploadedCount = 0; uploadedCount = uploadDirectoryToOss(localDirectory, bucketName, prefix, ""); - logger.info("Uploaded " + uploadedCount + " files to OSS"); + logger.info("Uploaded {} files to OSS", uploadedCount); return true; } catch (Exception e) { - logger.severe("Failed to upload to OSS: " + e.getMessage()); - e.printStackTrace(); + logger.error("Failed to upload to OSS: {}", e.getMessage()); return false; } } @@ -358,9 +355,9 @@ private int uploadDirectoryToOss(File directory, String bucketName, String baseP // Upload file to OSS ossClient.putObject(bucketName, objectKey, file); uploadedCount++; - logger.fine("Uploaded: " + file.getAbsolutePath() + " to " + objectKey); + logger.info("Uploaded: {} to {}", file.getAbsolutePath(), objectKey); } catch (Exception e) { - logger.warning("Failed to upload " + file.getAbsolutePath() + " to " + objectKey + ": " + e.getMessage()); + logger.warn("Failed to upload {} to {}: {}", file.getAbsolutePath(), objectKey, e.getMessage()); } } } @@ -377,7 +374,7 @@ public void close() { ossClient.shutdown(); logger.info("OSS client closed"); } catch (Exception e) { - logger.warning("Failed to close OSS client: " + e.getMessage()); + logger.warn("Failed to close OSS client: {}", e.getMessage()); } } } diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/manager/util/TrainingSandboxClient.java b/core/src/main/java/io/agentscope/runtime/sandbox/manager/util/TrainingSandboxClient.java index ae8c5611..028cded9 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/manager/util/TrainingSandboxClient.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/manager/util/TrainingSandboxClient.java @@ -18,6 +18,8 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import io.agentscope.runtime.sandbox.manager.model.container.ContainerModel; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.URI; @@ -27,11 +29,9 @@ import java.time.Duration; import java.util.HashMap; import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; public class TrainingSandboxClient extends SandboxClient { - private static final Logger logger = Logger.getLogger(TrainingSandboxClient.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(TrainingSandboxClient.class); private static final ObjectMapper objectMapper = new ObjectMapper(); private final String baseUrl; @@ -104,7 +104,7 @@ public void waitUntilHealthy() { while (System.currentTimeMillis() - startTime < timeoutMillis) { if (checkHealth()) { - logger.info("Training sandbox service is healthy: " + baseUrl); + logger.info("Training sandbox service is healthy: {}", baseUrl); return; } @@ -160,7 +160,7 @@ private Map makeRequest( HttpResponse.BodyHandlers.ofString()); if (response.statusCode() != 200) { - logger.warning("Request failed: HTTP " + response.statusCode()); + logger.warn("Request failed: HTTP {}", response.statusCode()); Map error = new HashMap<>(); error.put("error", "HTTP " + response.statusCode() + ": " + response.body()); return error; @@ -170,8 +170,7 @@ private Map makeRequest( Map result = objectMapper.readValue(response.body(), Map.class); return result; } catch (Exception e) { - logger.severe("Error making request to " + endpoint + ": " + e.getMessage()); - e.printStackTrace(); + logger.error("Error making request to {}: {}", endpoint, e.getMessage()); Map error = new HashMap<>(); error.put("error", e.getMessage()); return error; @@ -224,7 +223,7 @@ public String getEnvProfile(String envType, String split, Map pa try { return objectMapper.writeValueAsString(response.get("data")); } catch (Exception e) { - logger.warning("Failed to serialize env profile data: " + e.getMessage()); + logger.warn("Failed to serialize env profile data: {}", e.getMessage()); return response.get("data").toString(); } } @@ -256,15 +255,15 @@ public Map getToolsInfo(String instanceId, Map m Map dataMap = (Map) data; return dataMap; } else { - logger.warning("Unexpected 'data' type: " + (data != null ? data.getClass() : "null")); + logger.warn("Unexpected 'data' type: {}", data != null ? data.getClass() : "null"); return new HashMap<>(); } } catch (Exception e) { - logger.log(Level.SEVERE, "Failed to parse tools info data", e); + logger.error("Failed to parse tools info data{}", String.valueOf(e)); return new HashMap<>(); } } catch (Exception e) { - logger.warning("Failed to serialize tools info data: " + e.getMessage()); + logger.warn("Failed to serialize tools info data: {}", e.getMessage()); return null; } } @@ -290,7 +289,7 @@ public String createInstance(String envType, String taskId, String instanceId, M try { return objectMapper.writeValueAsString(response.get("data")); } catch (Exception e) { - logger.warning("Failed to serialize create instance data: " + e.getMessage()); + logger.warn("Failed to serialize create instance data: {}", e.getMessage()); return response.get("data").toString(); } } @@ -315,7 +314,7 @@ public String step(String instanceId, Map action, Map messages, Map messages, Map response = makeRequest( @@ -376,39 +375,34 @@ public String callTool(String name, Map arguments) { return null; } - switch (name) { - case "create_instance": - return createInstance( - (String) arguments.get("env_type"), - (String) arguments.get("task_id"), - (String) arguments.get("instance_id"), - getMapOrEmpty(arguments, "params") - ); - case "release_instance": - return releaseInstance((String) arguments.get("instance_id")); - case "evaluate": - return evaluate( - (String) arguments.get("instance_id"), - getMapOrEmpty(arguments, "messages"), - getMapOrEmpty(arguments, "params") - ); - case "step": - return step( - (String) arguments.get("instance_id"), - getMapOrEmpty(arguments, "action"), - getMapOrEmpty(arguments, "params") - ); - case "get_task_ids": - case "get_env_profile": - return getEnvProfile( - (String) arguments.get("env_type"), - (String) arguments.getOrDefault("split", "train"), - getMapOrEmpty(arguments, "params") - ); - default: - logger.warning("Unknown tool name: " + name); - return null; - } + return switch (name) { + case "create_instance" -> createInstance( + (String) arguments.get("env_type"), + (String) arguments.get("task_id"), + (String) arguments.get("instance_id"), + getMapOrEmpty(arguments, "params") + ); + case "release_instance" -> releaseInstance((String) arguments.get("instance_id")); + case "evaluate" -> evaluate( + (String) arguments.get("instance_id"), + getMapOrEmpty(arguments, "messages"), + getMapOrEmpty(arguments, "params") + ); + case "step" -> step( + (String) arguments.get("instance_id"), + getMapOrEmpty(arguments, "action"), + getMapOrEmpty(arguments, "params") + ); + case "get_task_ids", "get_env_profile" -> getEnvProfile( + (String) arguments.get("env_type"), + (String) arguments.getOrDefault("split", "train"), + getMapOrEmpty(arguments, "params") + ); + default -> { + logger.warn("Unknown tool name: {}", name); + yield null; + } + }; } @SuppressWarnings("unchecked") diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/tools/MCPTool.java b/core/src/main/java/io/agentscope/runtime/sandbox/tools/MCPTool.java index f10ba427..b995cef3 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/tools/MCPTool.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/tools/MCPTool.java @@ -19,13 +19,14 @@ import io.agentscope.runtime.sandbox.box.Sandbox; import io.agentscope.runtime.sandbox.manager.SandboxManager; import io.agentscope.runtime.sandbox.manager.model.container.SandboxType; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.Map; -import java.util.logging.Logger; public class MCPTool extends SandboxTool { - - private static final Logger logger = Logger.getLogger(MCPTool.class.getName()); + + private static final Logger logger = LoggerFactory.getLogger(MCPTool.class); private Map serverConfigs; private final String mcpToolName; @@ -65,8 +66,7 @@ public void setServerConfigs(Map serverConfigs) { } public String executeMCPTool(Map arguments) { - logger.info(String.format("Executing MCP tool '%s' with arguments: %s", - mcpToolName, arguments)); + logger.info("Executing MCP tool '{}' with arguments: {}", mcpToolName, arguments); if (sandbox == null) { throw new RuntimeException("Sandbox is not properly initialized for MCP tool"); @@ -76,7 +76,7 @@ public String executeMCPTool(Map arguments) { String result = sandbox.callTool(mcpToolName, arguments); - logger.info(String.format("MCP tool '%s' execution result: %s", mcpToolName, result)); + logger.info("MCP tool '{}' execution result: {}", mcpToolName, result); return result; } diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/tools/McpConfigConverter.java b/core/src/main/java/io/agentscope/runtime/sandbox/tools/McpConfigConverter.java index 3a85f5b1..c3212f83 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/tools/McpConfigConverter.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/tools/McpConfigConverter.java @@ -22,7 +22,6 @@ import java.util.List; import java.util.Map; import java.util.Set; -import java.util.logging.Logger; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; @@ -30,10 +29,12 @@ import io.agentscope.runtime.sandbox.box.Sandbox; import io.agentscope.runtime.sandbox.manager.SandboxManager; import io.agentscope.runtime.sandbox.manager.model.container.SandboxType; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; public class McpConfigConverter { - private static final Logger logger = Logger.getLogger(McpConfigConverter.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(McpConfigConverter.class); private static final ObjectMapper objectMapper = new ObjectMapper(); private Map serverConfigs; @@ -120,7 +121,7 @@ public List toBuiltinTools() { toolsToAdd = processTools(box); } catch (Exception e){ - logger.severe("Failed to create BaseSandbox: " + e.getMessage()); + logger.error("Failed to create BaseSandbox: {}", e.getMessage()); throw new RuntimeException("Failed to create BaseSandbox", e); } } @@ -142,7 +143,7 @@ private List processTools(Sandbox box) { Map mcpServers = (Map) serverConfigs.get("mcpServers"); for (String serverName : mcpServers.keySet()) { - logger.info("Processing MCP server: " + serverName); + logger.info("Processing MCP server: {}", serverName); Map tools = box.listTools(serverName); @@ -153,11 +154,11 @@ private List processTools(Sandbox box) { Map toolInfo = (Map) toolEntry.getValue(); if (!whitelist.isEmpty() && !whitelist.contains(toolName)) { - logger.fine("Skipping tool (not in whitelist): " + toolName); + logger.info("Skipping tool (not in whitelist): {}", toolName); continue; } if (!blacklist.isEmpty() && blacklist.contains(toolName)) { - logger.fine("Skipping tool (in blacklist): " + toolName); + logger.info("Skipping tool (in blacklist): {}", toolName); continue; } @@ -182,11 +183,11 @@ private List processTools(Sandbox box) { ); toolsToAdd.add(mcpTool); - logger.info(String.format("Added MCP tool: %s (server: %s)", toolName, serverName)); + logger.info("Added MCP tool: {} (server: {})", toolName, serverName); } } - logger.info(String.format("Total MCP tools added: %d", toolsToAdd.size())); + logger.info("Total MCP tools added: {}", toolsToAdd.size()); return toolsToAdd; } @@ -196,7 +197,7 @@ private static Map parseServerConfig(String configStr) { return objectMapper.readValue(configStr, new TypeReference>() { }); } catch (Exception e) { - logger.severe("Failed to parse server config: " + e.getMessage()); + logger.error("Failed to parse server config: {}", e.getMessage()); throw new RuntimeException("Failed to parse server config string", e); } } diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/tools/base/RunPythonTool.java b/core/src/main/java/io/agentscope/runtime/sandbox/tools/base/RunPythonTool.java index 8a57227a..7ab36778 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/tools/base/RunPythonTool.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/tools/base/RunPythonTool.java @@ -19,16 +19,16 @@ import io.agentscope.runtime.sandbox.box.BaseSandbox; import io.agentscope.runtime.sandbox.box.Sandbox; import io.agentscope.runtime.sandbox.tools.SandboxTool; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.logging.Logger; public class RunPythonTool extends BaseSandboxTool { - Logger logger = Logger.getLogger(RunPythonTool.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(RunPythonTool.class); public RunPythonTool() { super("run_ipython_cell", "generic", "Execute Python code snippets and return the output or errors."); @@ -40,7 +40,7 @@ public RunPythonTool() { Map properties = new HashMap<>(); properties.put("code", codeProperty); - List required = Arrays.asList("code"); + List required = List.of("code"); schema.put("type", "object"); schema.put("properties", properties); @@ -62,8 +62,7 @@ public String run_ipython_cell(String code) { throw new RuntimeException("Only BaseSandbox supported in run python tool"); } catch (Exception e) { String errorMsg = "Run Python Code Error: " + e.getMessage(); - logger.severe(errorMsg); - e.printStackTrace(); + logger.error(errorMsg); return errorMsg; } } diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/tools/base/RunShellCommandTool.java b/core/src/main/java/io/agentscope/runtime/sandbox/tools/base/RunShellCommandTool.java index 3ddce6a5..a7fc3562 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/tools/base/RunShellCommandTool.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/tools/base/RunShellCommandTool.java @@ -18,16 +18,17 @@ import io.agentscope.runtime.sandbox.box.BaseSandbox; import io.agentscope.runtime.sandbox.box.Sandbox; import io.agentscope.runtime.sandbox.tools.SandboxTool; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.logging.Logger; public class RunShellCommandTool extends BaseSandboxTool { - Logger logger = Logger.getLogger(RunShellCommandTool.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(RunShellCommandTool.class); public RunShellCommandTool() { super("run_shell_command", "generic", "Execute shell commands and return the output or errors."); @@ -39,7 +40,7 @@ public RunShellCommandTool() { Map properties = new HashMap<>(); properties.put("command", commandProperty); - List required = Arrays.asList("command"); + List required = List.of("command"); schema.put("type", "object"); schema.put("properties", properties); @@ -55,17 +56,16 @@ public SandboxTool bind(Sandbox sandbox) { public String run_shell_command(String command) { try { - logger.info("Run Shell Command: " + command); + logger.info("Run Shell Command: {}", command); if(sandbox instanceof BaseSandbox baseSandbox){ String result = baseSandbox.runShellCommand(command); - logger.info("Execute Result: " + result); + logger.info("Execute Result: {}", result); return result; } throw new RuntimeException("Only BaseSandbox supported in run shell command tool"); } catch (Exception e) { String errorMsg = "Run Shell Command Error: " + e.getMessage(); - logger.severe(errorMsg); - e.printStackTrace(); + logger.error(errorMsg); return errorMsg; } } diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/ClickTool.java b/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/ClickTool.java index a6db809d..301dbbc5 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/ClickTool.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/ClickTool.java @@ -18,16 +18,17 @@ import io.agentscope.runtime.sandbox.box.BrowserSandbox; import io.agentscope.runtime.sandbox.box.Sandbox; import io.agentscope.runtime.sandbox.tools.SandboxTool; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.logging.Logger; public class ClickTool extends BrowserSandboxTool { - Logger logger = Logger.getLogger(ClickTool.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(ClickTool.class); public ClickTool() { super("browser_click", "browser", "Click on an element in the browser"); @@ -67,8 +68,7 @@ public String browser_click(String element, String ref) { throw new RuntimeException("Only BrowserSandbox supported in browser click tool"); } catch (Exception e) { String errorMsg = "Browser Click Error: " + e.getMessage(); - logger.severe(errorMsg); - e.printStackTrace(); + logger.error(errorMsg); return errorMsg; } } diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/CloseTool.java b/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/CloseTool.java index ae34b2dc..43052fef 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/CloseTool.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/CloseTool.java @@ -18,12 +18,13 @@ import io.agentscope.runtime.sandbox.box.BrowserSandbox; import io.agentscope.runtime.sandbox.box.Sandbox; import io.agentscope.runtime.sandbox.tools.SandboxTool; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.HashMap; -import java.util.logging.Logger; public class CloseTool extends BrowserSandboxTool { - Logger logger = Logger.getLogger(CloseTool.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(CloseTool.class); public CloseTool() { super("browser_close", "browser", "Close the browser"); @@ -47,8 +48,7 @@ public String browser_close() { throw new RuntimeException("Only BrowserSandbox supported in browser close tool"); } catch (Exception e) { String errorMsg = "Browser Close Error: " + e.getMessage(); - logger.severe(errorMsg); - e.printStackTrace(); + logger.error(errorMsg); return errorMsg; } } diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/ConsoleMessagesTool.java b/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/ConsoleMessagesTool.java index a58872ab..fd1a5275 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/ConsoleMessagesTool.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/ConsoleMessagesTool.java @@ -18,13 +18,14 @@ import io.agentscope.runtime.sandbox.box.BrowserSandbox; import io.agentscope.runtime.sandbox.box.Sandbox; import io.agentscope.runtime.sandbox.tools.SandboxTool; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.HashMap; -import java.util.logging.Logger; public class ConsoleMessagesTool extends BrowserSandboxTool { - Logger logger = Logger.getLogger(ConsoleMessagesTool.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(ConsoleMessagesTool.class); public ConsoleMessagesTool() { super("browser_console_messages", "browser", "Get console messages from the browser"); @@ -48,8 +49,7 @@ public String browser_console_messages() { throw new RuntimeException("Only BrowserSandbox supported in browser console messages tool"); } catch (Exception e) { String errorMsg = "Browser Console Messages Error: " + e.getMessage(); - logger.severe(errorMsg); - e.printStackTrace(); + logger.error(errorMsg); return errorMsg; } } diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/DragTool.java b/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/DragTool.java index dd5116a1..c50e441e 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/DragTool.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/DragTool.java @@ -18,19 +18,20 @@ import io.agentscope.runtime.sandbox.box.BrowserSandbox; import io.agentscope.runtime.sandbox.box.Sandbox; import io.agentscope.runtime.sandbox.tools.SandboxTool; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.logging.Logger; /** * Browser drag tool */ public class DragTool extends BrowserSandboxTool { - Logger logger = Logger.getLogger(DragTool.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(DragTool.class); public DragTool() { super("browser_drag", "browser", "Drag and drop an element in the browser"); @@ -80,8 +81,7 @@ public String browser_drag(String startElement, String startRef, String endEleme throw new RuntimeException("Only BrowserSandbox supported in browser drag tool"); } catch (Exception e) { String errorMsg = "Browser Drag Error: " + e.getMessage(); - logger.severe(errorMsg); - e.printStackTrace(); + logger.error(errorMsg); return errorMsg; } } diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/FileUploadTool.java b/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/FileUploadTool.java index a9df3eff..927b85c5 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/FileUploadTool.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/FileUploadTool.java @@ -18,19 +18,19 @@ import io.agentscope.runtime.sandbox.box.BrowserSandbox; import io.agentscope.runtime.sandbox.box.Sandbox; import io.agentscope.runtime.sandbox.tools.SandboxTool; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.logging.Logger; /** * Browser file upload tool */ public class FileUploadTool extends BrowserSandboxTool { - Logger logger = Logger.getLogger(FileUploadTool.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(FileUploadTool.class); public FileUploadTool() { super("browser_file_upload", "browser", "Upload files in the browser"); @@ -43,7 +43,7 @@ public FileUploadTool() { Map properties = new HashMap<>(); properties.put("paths", pathsProperty); - List required = Arrays.asList("paths"); + List required = List.of("paths"); schema.put("type", "object"); schema.put("properties", properties); @@ -65,8 +65,7 @@ public String browser_file_upload(String[] paths) { throw new RuntimeException("Only BrowserSandbox supported in browser file upload tool"); } catch (Exception e) { String errorMsg = "Browser File Upload Error: " + e.getMessage(); - logger.severe(errorMsg); - e.printStackTrace(); + logger.error(errorMsg); return errorMsg; } } diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/HandleDialogTool.java b/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/HandleDialogTool.java index 7416bbc0..2275b50d 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/HandleDialogTool.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/HandleDialogTool.java @@ -18,19 +18,19 @@ import io.agentscope.runtime.sandbox.box.BrowserSandbox; import io.agentscope.runtime.sandbox.box.Sandbox; import io.agentscope.runtime.sandbox.tools.SandboxTool; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.logging.Logger; /** * Browser dialog handling tool */ public class HandleDialogTool extends BrowserSandboxTool { - Logger logger = Logger.getLogger(HandleDialogTool.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(HandleDialogTool.class); public HandleDialogTool() { super("browser_handle_dialog", "browser", "Handle browser dialogs (alert, confirm, prompt)"); @@ -48,7 +48,7 @@ public HandleDialogTool() { properties.put("accept", acceptProperty); properties.put("promptText", promptTextProperty); - List required = Arrays.asList("accept"); + List required = List.of("accept"); schema.put("type", "object"); schema.put("properties", properties); @@ -70,8 +70,7 @@ public String browser_handle_dialog(Boolean accept, String promptText) { throw new RuntimeException("Only BrowserSandbox supported in browser handle dialog tool"); } catch (Exception e) { String errorMsg = "Browser Handle Dialog Error: " + e.getMessage(); - logger.severe(errorMsg); - e.printStackTrace(); + logger.error(errorMsg); return errorMsg; } } diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/HoverTool.java b/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/HoverTool.java index 2c176e33..07cfc27e 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/HoverTool.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/HoverTool.java @@ -18,19 +18,20 @@ import io.agentscope.runtime.sandbox.box.BrowserSandbox; import io.agentscope.runtime.sandbox.box.Sandbox; import io.agentscope.runtime.sandbox.tools.SandboxTool; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.logging.Logger; /** * Browser hover tool */ public class HoverTool extends BrowserSandboxTool { - Logger logger = Logger.getLogger(HoverTool.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(HoverTool.class); public HoverTool() { super("browser_hover", "browser", "Hover over an element in the browser"); @@ -70,8 +71,7 @@ public String browser_hover(String element, String ref) { throw new RuntimeException("Only BrowserSandbox supported in browser hover tool"); } catch (Exception e) { String errorMsg = "Browser Hover Error: " + e.getMessage(); - logger.severe(errorMsg); - e.printStackTrace(); + logger.error(errorMsg); return errorMsg; } } diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/NavigateBackTool.java b/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/NavigateBackTool.java index b544ce9d..2ae3463b 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/NavigateBackTool.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/NavigateBackTool.java @@ -18,16 +18,17 @@ import io.agentscope.runtime.sandbox.box.BrowserSandbox; import io.agentscope.runtime.sandbox.box.Sandbox; import io.agentscope.runtime.sandbox.tools.SandboxTool; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.HashMap; -import java.util.logging.Logger; /** * Browser back navigation tool */ public class NavigateBackTool extends BrowserSandboxTool { - Logger logger = Logger.getLogger(NavigateBackTool.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(NavigateBackTool.class); public NavigateBackTool() { super("browser_navigate_back", "browser", "Navigate back in browser history"); @@ -51,8 +52,7 @@ public String browser_navigate_back() { throw new RuntimeException("Only BrowserSandbox supported in browser navigate back tool"); } catch (Exception e) { String errorMsg = "Browser Navigate Back Error: " + e.getMessage(); - logger.severe(errorMsg); - e.printStackTrace(); + logger.error(errorMsg); return errorMsg; } } diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/NavigateForwardTool.java b/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/NavigateForwardTool.java index 11b3bea2..13e0ce18 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/NavigateForwardTool.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/NavigateForwardTool.java @@ -18,16 +18,17 @@ import io.agentscope.runtime.sandbox.box.BrowserSandbox; import io.agentscope.runtime.sandbox.box.Sandbox; import io.agentscope.runtime.sandbox.tools.SandboxTool; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.HashMap; -import java.util.logging.Logger; /** * Browser forward navigation tool */ public class NavigateForwardTool extends BrowserSandboxTool { - Logger logger = Logger.getLogger(NavigateForwardTool.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(NavigateForwardTool.class); public NavigateForwardTool() { super("browser_navigate_forward", "browser", "Navigate forward in browser history"); @@ -51,8 +52,7 @@ public String browser_navigate_forward() { throw new RuntimeException("Only BrowserSandbox supported in browser navigate forward tool"); } catch (Exception e) { String errorMsg = "Browser Navigate Forward Error: " + e.getMessage(); - logger.severe(errorMsg); - e.printStackTrace(); + logger.error(errorMsg); return errorMsg; } } diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/NavigateTool.java b/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/NavigateTool.java index 0489df21..73c3e462 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/NavigateTool.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/NavigateTool.java @@ -18,16 +18,16 @@ import io.agentscope.runtime.sandbox.box.BrowserSandbox; import io.agentscope.runtime.sandbox.box.Sandbox; import io.agentscope.runtime.sandbox.tools.SandboxTool; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.logging.Logger; public class NavigateTool extends BrowserSandboxTool { - Logger logger = Logger.getLogger(NavigateTool.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(NavigateTool.class); public NavigateTool() { super("browser_navigate", "browser", "Navigate to a URL in the browser"); @@ -40,7 +40,7 @@ public NavigateTool() { Map properties = new HashMap<>(); properties.put("url", urlProperty); - List required = Arrays.asList("url"); + List required = List.of("url"); schema.put("type", "object"); schema.put("properties", properties); @@ -62,8 +62,7 @@ public String browser_navigate(String url) { throw new RuntimeException("Only BrowserSandbox supported in browser navigate tool"); } catch (Exception e) { String errorMsg = "Browser Navigate Error: " + e.getMessage(); - logger.severe(errorMsg); - e.printStackTrace(); + logger.error(errorMsg); return errorMsg; } } diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/NetworkRequestsTool.java b/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/NetworkRequestsTool.java index 3487d034..a03485c0 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/NetworkRequestsTool.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/NetworkRequestsTool.java @@ -18,16 +18,17 @@ import io.agentscope.runtime.sandbox.box.BrowserSandbox; import io.agentscope.runtime.sandbox.box.Sandbox; import io.agentscope.runtime.sandbox.tools.SandboxTool; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.HashMap; -import java.util.logging.Logger; /** * Browser network requests tool */ public class NetworkRequestsTool extends BrowserSandboxTool { - Logger logger = Logger.getLogger(NetworkRequestsTool.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(NetworkRequestsTool.class); public NetworkRequestsTool() { super("browser_network_requests", "browser", "Get network requests from the browser"); @@ -51,8 +52,7 @@ public String browser_network_requests() { throw new RuntimeException("Only BrowserSandbox supported in browser network requests tool"); } catch (Exception e) { String errorMsg = "Browser Network Requests Error: " + e.getMessage(); - logger.severe(errorMsg); - e.printStackTrace(); + logger.error(errorMsg); return errorMsg; } } diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/PdfSaveTool.java b/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/PdfSaveTool.java index f0ca7bf0..4110d717 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/PdfSaveTool.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/PdfSaveTool.java @@ -18,17 +18,18 @@ import io.agentscope.runtime.sandbox.box.BrowserSandbox; import io.agentscope.runtime.sandbox.box.Sandbox; import io.agentscope.runtime.sandbox.tools.SandboxTool; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; -import java.util.logging.Logger; /** * Browser PDF save tool */ public class PdfSaveTool extends BrowserSandboxTool { - Logger logger = Logger.getLogger(PdfSaveTool.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(PdfSaveTool.class); public PdfSaveTool() { super("browser_pdf_save", "browser", "Save the current page as PDF"); @@ -60,8 +61,7 @@ public String browser_pdf_save(String filename) { throw new RuntimeException("Only BrowserSandbox supported in browser pdf save tool"); } catch (Exception e) { String errorMsg = "Browser PDF Save Error: " + e.getMessage(); - logger.severe(errorMsg); - e.printStackTrace(); + logger.error(errorMsg); return errorMsg; } } diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/PressKeyTool.java b/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/PressKeyTool.java index 1b901ac6..958e67e3 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/PressKeyTool.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/PressKeyTool.java @@ -18,19 +18,19 @@ import io.agentscope.runtime.sandbox.box.BrowserSandbox; import io.agentscope.runtime.sandbox.box.Sandbox; import io.agentscope.runtime.sandbox.tools.SandboxTool; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.logging.Logger; /** * Browser key press tool */ public class PressKeyTool extends BrowserSandboxTool { - Logger logger = Logger.getLogger(PressKeyTool.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(PressKeyTool.class); public PressKeyTool() { super("browser_press_key", "browser", "Press a key in the browser"); @@ -43,7 +43,7 @@ public PressKeyTool() { Map properties = new HashMap<>(); properties.put("key", keyProperty); - List required = Arrays.asList("key"); + List required = List.of("key"); schema.put("type", "object"); schema.put("properties", properties); @@ -65,8 +65,7 @@ public String browser_press_key(String key) { throw new RuntimeException("Only BrowserSandbox supported in browser press key tool"); } catch (Exception e) { String errorMsg = "Browser Press Key Error: " + e.getMessage(); - logger.severe(errorMsg); - e.printStackTrace(); + logger.error(errorMsg); return errorMsg; } } diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/ResizeTool.java b/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/ResizeTool.java index 3ab5f05b..af9dc894 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/ResizeTool.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/ResizeTool.java @@ -18,16 +18,17 @@ import io.agentscope.runtime.sandbox.box.BrowserSandbox; import io.agentscope.runtime.sandbox.box.Sandbox; import io.agentscope.runtime.sandbox.tools.SandboxTool; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.logging.Logger; public class ResizeTool extends BrowserSandboxTool { - Logger logger = Logger.getLogger(ResizeTool.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(ResizeTool.class); public ResizeTool() { super("browser_resize", "browser", "Resize the browser window"); @@ -67,8 +68,7 @@ public String browser_resize(Double width, Double height) { throw new RuntimeException("Only BrowserSandbox supported in browser resize tool"); } catch (Exception e) { String errorMsg = "Browser Resize Error: " + e.getMessage(); - logger.severe(errorMsg); - e.printStackTrace(); + logger.error(errorMsg); return errorMsg; } } diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/SelectOptionTool.java b/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/SelectOptionTool.java index c14e486c..b64b3cfa 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/SelectOptionTool.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/SelectOptionTool.java @@ -18,19 +18,20 @@ import io.agentscope.runtime.sandbox.box.BrowserSandbox; import io.agentscope.runtime.sandbox.box.Sandbox; import io.agentscope.runtime.sandbox.tools.SandboxTool; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.logging.Logger; /** * Browser dropdown selection tool */ public class SelectOptionTool extends BrowserSandboxTool { - Logger logger = Logger.getLogger(SelectOptionTool.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(SelectOptionTool.class); public SelectOptionTool() { super("browser_select_option", "browser", "Select option(s) from a dropdown in the browser"); @@ -75,8 +76,7 @@ public String browser_select_option(String element, String ref, String[] values) throw new RuntimeException("Only BrowserSandbox supported in browser select option tool"); } catch (Exception e) { String errorMsg = "Browser Select Option Error: " + e.getMessage(); - logger.severe(errorMsg); - e.printStackTrace(); + logger.error(errorMsg); return errorMsg; } } diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/SnapshotTool.java b/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/SnapshotTool.java index ea434642..1a28d064 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/SnapshotTool.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/SnapshotTool.java @@ -18,13 +18,14 @@ import io.agentscope.runtime.sandbox.box.BrowserSandbox; import io.agentscope.runtime.sandbox.box.Sandbox; import io.agentscope.runtime.sandbox.tools.SandboxTool; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.HashMap; -import java.util.logging.Logger; public class SnapshotTool extends BrowserSandboxTool { - Logger logger = Logger.getLogger(SnapshotTool.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(SnapshotTool.class); public SnapshotTool() { super("browser_snapshot", "browser", "Take a snapshot of the current browser state"); @@ -48,8 +49,7 @@ public String browser_snapshot() { throw new RuntimeException("Only BrowserSandbox supported in browser snapshot tool"); } catch (Exception e) { String errorMsg = "Browser Snapshot Error: " + e.getMessage(); - logger.severe(errorMsg); - e.printStackTrace(); + logger.error(errorMsg); return errorMsg; } } diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/TabCloseTool.java b/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/TabCloseTool.java index 84f3e5b7..bb2dd3e4 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/TabCloseTool.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/TabCloseTool.java @@ -18,14 +18,15 @@ import io.agentscope.runtime.sandbox.box.BrowserSandbox; import io.agentscope.runtime.sandbox.box.Sandbox; import io.agentscope.runtime.sandbox.tools.SandboxTool; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; -import java.util.logging.Logger; public class TabCloseTool extends BrowserSandboxTool { - Logger logger = Logger.getLogger(TabCloseTool.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(TabCloseTool.class); public TabCloseTool() { super("browser_tab_close", "browser", "Close a browser tab"); @@ -57,8 +58,7 @@ public String browser_tab_close(Integer index) { throw new RuntimeException("Only BrowserSandbox supported in browser tab close tool"); } catch (Exception e) { String errorMsg = "Browser Tab Close Error: " + e.getMessage(); - logger.severe(errorMsg); - e.printStackTrace(); + logger.error(errorMsg); return errorMsg; } } diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/TabListTool.java b/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/TabListTool.java index 2a5d837c..c3be8818 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/TabListTool.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/TabListTool.java @@ -18,16 +18,17 @@ import io.agentscope.runtime.sandbox.box.BrowserSandbox; import io.agentscope.runtime.sandbox.box.Sandbox; import io.agentscope.runtime.sandbox.tools.SandboxTool; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.HashMap; -import java.util.logging.Logger; /** * Browser tab list tool */ public class TabListTool extends BrowserSandboxTool { - Logger logger = Logger.getLogger(TabListTool.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(TabListTool.class); public TabListTool() { super("browser_tab_list", "browser", "List all browser tabs"); @@ -51,8 +52,7 @@ public String browser_tab_list() { throw new RuntimeException("Only BrowserSandbox supported in browser tab list tool"); } catch (Exception e) { String errorMsg = "Browser Tab List Error: " + e.getMessage(); - logger.severe(errorMsg); - e.printStackTrace(); + logger.error(errorMsg); return errorMsg; } } diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/TabNewTool.java b/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/TabNewTool.java index 5708601a..60bdaae2 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/TabNewTool.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/TabNewTool.java @@ -18,14 +18,15 @@ import io.agentscope.runtime.sandbox.box.BrowserSandbox; import io.agentscope.runtime.sandbox.box.Sandbox; import io.agentscope.runtime.sandbox.tools.SandboxTool; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; -import java.util.logging.Logger; public class TabNewTool extends BrowserSandboxTool { - Logger logger = Logger.getLogger(TabNewTool.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(TabNewTool.class); public TabNewTool() { super("browser_tab_new", "browser", "Open a new browser tab"); @@ -57,8 +58,7 @@ public String browser_tab_new(String url) { throw new RuntimeException("Only BrowserSandbox supported in browser tab new tool"); } catch (Exception e) { String errorMsg = "Browser Tab New Error: " + e.getMessage(); - logger.severe(errorMsg); - e.printStackTrace(); + logger.error(errorMsg); return errorMsg; } } diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/TabSelectTool.java b/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/TabSelectTool.java index 5ee80d38..ca44546a 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/TabSelectTool.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/TabSelectTool.java @@ -18,16 +18,16 @@ import io.agentscope.runtime.sandbox.box.BrowserSandbox; import io.agentscope.runtime.sandbox.box.Sandbox; import io.agentscope.runtime.sandbox.tools.SandboxTool; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.logging.Logger; public class TabSelectTool extends BrowserSandboxTool { - Logger logger = Logger.getLogger(TabSelectTool.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(TabSelectTool.class); public TabSelectTool() { super("browser_tab_select", "browser", "Select a browser tab by index"); @@ -40,7 +40,7 @@ public TabSelectTool() { Map properties = new HashMap<>(); properties.put("index", indexProperty); - List required = Arrays.asList("index"); + List required = List.of("index"); schema.put("type", "object"); schema.put("properties", properties); @@ -62,8 +62,7 @@ public String browser_tab_select(Integer index) { throw new RuntimeException("Only BrowserSandbox supported in browser tab select tool"); } catch (Exception e) { String errorMsg = "Browser Tab Select Error: " + e.getMessage(); - logger.severe(errorMsg); - e.printStackTrace(); + logger.error(errorMsg); return errorMsg; } } diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/TakeScreenshotTool.java b/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/TakeScreenshotTool.java index a88a990c..4e118e3e 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/TakeScreenshotTool.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/TakeScreenshotTool.java @@ -18,13 +18,14 @@ import io.agentscope.runtime.sandbox.box.BrowserSandbox; import io.agentscope.runtime.sandbox.box.Sandbox; import io.agentscope.runtime.sandbox.tools.SandboxTool; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; -import java.util.logging.Logger; public class TakeScreenshotTool extends BrowserSandboxTool { - Logger logger = Logger.getLogger(TakeScreenshotTool.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(TakeScreenshotTool.class); public TakeScreenshotTool() { super("browser_take_screenshot", "browser", "Take a screenshot of the browser"); @@ -71,8 +72,7 @@ public String browser_take_screenshot(Boolean raw, String filename, String eleme throw new RuntimeException("Only BrowserSandbox supported in browser take screenshot tool"); } catch (Exception e) { String errorMsg = "Browser Take Screenshot Error: " + e.getMessage(); - logger.severe(errorMsg); - e.printStackTrace(); + logger.error(errorMsg); return errorMsg; } } diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/TypeTool.java b/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/TypeTool.java index 4a3791ee..00cff92c 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/TypeTool.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/TypeTool.java @@ -18,16 +18,17 @@ import io.agentscope.runtime.sandbox.box.BrowserSandbox; import io.agentscope.runtime.sandbox.box.Sandbox; import io.agentscope.runtime.sandbox.tools.SandboxTool; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.logging.Logger; public class TypeTool extends BrowserSandboxTool { - Logger logger = Logger.getLogger(TypeTool.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(TypeTool.class); public TypeTool() { super("browser_type", "browser", "Type text into an element in the browser"); @@ -82,8 +83,7 @@ public String browser_type(String element, String ref, String text, Boolean subm throw new RuntimeException("Only BrowserSandbox supported in browser type tool"); } catch (Exception e) { String errorMsg = "Browser Type Error: " + e.getMessage(); - logger.severe(errorMsg); - e.printStackTrace(); + logger.error(errorMsg); return errorMsg; } } diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/WaitForTool.java b/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/WaitForTool.java index dc0e873c..af4825a7 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/WaitForTool.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/tools/browser/WaitForTool.java @@ -21,14 +21,15 @@ import io.agentscope.runtime.sandbox.box.BrowserSandbox; import io.agentscope.runtime.sandbox.box.Sandbox; import io.agentscope.runtime.sandbox.tools.SandboxTool; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; -import java.util.logging.Logger; public class WaitForTool extends BrowserSandboxTool { - Logger logger = Logger.getLogger(WaitForTool.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(WaitForTool.class); public WaitForTool() { super("browser_wait_for", "browser", "Wait for a condition in the browser"); @@ -70,8 +71,7 @@ public String browser_wait_for(Double time, String text, String textGone) { throw new RuntimeException("Only BrowserSandbox supported in browser wait for tool"); } catch (Exception e) { String errorMsg = "Browser Wait For Error: " + e.getMessage(); - logger.severe(errorMsg); - e.printStackTrace(); + logger.error(errorMsg); return errorMsg; } } diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/tools/fs/CreateDirectoryTool.java b/core/src/main/java/io/agentscope/runtime/sandbox/tools/fs/CreateDirectoryTool.java index aecac743..670d4dd1 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/tools/fs/CreateDirectoryTool.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/tools/fs/CreateDirectoryTool.java @@ -18,16 +18,16 @@ import io.agentscope.runtime.sandbox.box.FilesystemSandbox; import io.agentscope.runtime.sandbox.box.Sandbox; import io.agentscope.runtime.sandbox.tools.SandboxTool; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.logging.Logger; public class CreateDirectoryTool extends FsSandboxTool { - Logger logger = Logger.getLogger(CreateDirectoryTool.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(CreateDirectoryTool.class); public CreateDirectoryTool() { super("fs_create_directory", "filesystem", "Create a new directory"); @@ -39,7 +39,7 @@ public CreateDirectoryTool() { Map properties = new HashMap<>(); properties.put("path", pathProperty); - List required = Arrays.asList("path"); + List required = List.of("path"); schema.put("type", "object"); schema.put("properties", properties); @@ -61,8 +61,7 @@ public String fs_create_directory(String path) { throw new RuntimeException("Only FilesystemSandbox supported in create directory tool"); } catch (Exception e) { String errorMsg = "Create Directory Error: " + e.getMessage(); - logger.severe(errorMsg); - e.printStackTrace(); + logger.error(errorMsg); return errorMsg; } } diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/tools/fs/DirectoryTreeTool.java b/core/src/main/java/io/agentscope/runtime/sandbox/tools/fs/DirectoryTreeTool.java index a3c2b605..09631e94 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/tools/fs/DirectoryTreeTool.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/tools/fs/DirectoryTreeTool.java @@ -18,16 +18,16 @@ import io.agentscope.runtime.sandbox.box.FilesystemSandbox; import io.agentscope.runtime.sandbox.box.Sandbox; import io.agentscope.runtime.sandbox.tools.SandboxTool; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.logging.Logger; public class DirectoryTreeTool extends FsSandboxTool { - Logger logger = Logger.getLogger(DirectoryTreeTool.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(DirectoryTreeTool.class); public DirectoryTreeTool() { super("fs_directory_tree", "filesystem", "Get directory tree structure"); @@ -39,7 +39,7 @@ public DirectoryTreeTool() { Map properties = new HashMap<>(); properties.put("path", pathProperty); - List required = Arrays.asList("path"); + List required = List.of("path"); schema.put("type", "object"); schema.put("properties", properties); @@ -61,8 +61,7 @@ public String fs_directory_tree(String path) { throw new RuntimeException("Only FilesystemSandbox supported in directory tree tool"); } catch (Exception e) { String errorMsg = "Directory Tree Error: " + e.getMessage(); - logger.severe(errorMsg); - e.printStackTrace(); + logger.error(errorMsg); return errorMsg; } } diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/tools/fs/EditFileTool.java b/core/src/main/java/io/agentscope/runtime/sandbox/tools/fs/EditFileTool.java index dd2f22ff..396ee6cc 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/tools/fs/EditFileTool.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/tools/fs/EditFileTool.java @@ -18,16 +18,17 @@ import io.agentscope.runtime.sandbox.box.FilesystemSandbox; import io.agentscope.runtime.sandbox.box.Sandbox; import io.agentscope.runtime.sandbox.tools.SandboxTool; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.logging.Logger; public class EditFileTool extends FsSandboxTool { - Logger logger = Logger.getLogger(EditFileTool.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(EditFileTool.class); public EditFileTool() { super("fs_edit_file", "filesystem", "Edit a file with find-replace operations"); @@ -67,8 +68,7 @@ public String fs_edit_file(String path, Map[] edits) { throw new RuntimeException("Only FilesystemSandbox supported in edit file tool"); } catch (Exception e) { String errorMsg = "Edit File Error: " + e.getMessage(); - logger.severe(errorMsg); - e.printStackTrace(); + logger.error(errorMsg); return errorMsg; } } diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/tools/fs/GetFileInfoTool.java b/core/src/main/java/io/agentscope/runtime/sandbox/tools/fs/GetFileInfoTool.java index 1c9234bb..790a5111 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/tools/fs/GetFileInfoTool.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/tools/fs/GetFileInfoTool.java @@ -18,16 +18,16 @@ import io.agentscope.runtime.sandbox.box.FilesystemSandbox; import io.agentscope.runtime.sandbox.box.Sandbox; import io.agentscope.runtime.sandbox.tools.SandboxTool; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.logging.Logger; public class GetFileInfoTool extends FsSandboxTool { - Logger logger = Logger.getLogger(GetFileInfoTool.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(GetFileInfoTool.class); public GetFileInfoTool() { super("fs_get_file_info", "filesystem", "Get information about a file or directory"); @@ -39,7 +39,7 @@ public GetFileInfoTool() { Map properties = new HashMap<>(); properties.put("path", pathProperty); - List required = Arrays.asList("path"); + List required = List.of("path"); schema.put("type", "object"); schema.put("properties", properties); @@ -61,8 +61,7 @@ public String fs_get_file_info(String path) { throw new RuntimeException("Only FilesystemSandbox supported in get file info tool"); } catch (Exception e) { String errorMsg = "Get File Info Error: " + e.getMessage(); - logger.severe(errorMsg); - e.printStackTrace(); + logger.error(errorMsg); return errorMsg; } } diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/tools/fs/ListAllowedDirectoriesTool.java b/core/src/main/java/io/agentscope/runtime/sandbox/tools/fs/ListAllowedDirectoriesTool.java index 8527a0ca..3f08e33b 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/tools/fs/ListAllowedDirectoriesTool.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/tools/fs/ListAllowedDirectoriesTool.java @@ -18,14 +18,15 @@ import io.agentscope.runtime.sandbox.box.FilesystemSandbox; import io.agentscope.runtime.sandbox.box.Sandbox; import io.agentscope.runtime.sandbox.tools.SandboxTool; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Map; -import java.util.logging.Logger; public class ListAllowedDirectoriesTool extends FsSandboxTool { - Logger logger = Logger.getLogger(ListAllowedDirectoriesTool.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(ListAllowedDirectoriesTool.class); public ListAllowedDirectoriesTool() { super("fs_list_allowed_directories", "filesystem", "List allowed directories for the current session"); @@ -52,8 +53,7 @@ public String fs_list_allowed_directories() { throw new RuntimeException("Only FilesystemSandbox supported in list allowed directories tool"); } catch (Exception e) { String errorMsg = "List Allowed Directories Error: " + e.getMessage(); - logger.severe(errorMsg); - e.printStackTrace(); + logger.error(errorMsg); return errorMsg; } } diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/tools/fs/ListDirectoryTool.java b/core/src/main/java/io/agentscope/runtime/sandbox/tools/fs/ListDirectoryTool.java index a81e7963..84161092 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/tools/fs/ListDirectoryTool.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/tools/fs/ListDirectoryTool.java @@ -18,16 +18,16 @@ import io.agentscope.runtime.sandbox.box.FilesystemSandbox; import io.agentscope.runtime.sandbox.box.Sandbox; import io.agentscope.runtime.sandbox.tools.SandboxTool; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.logging.Logger; public class ListDirectoryTool extends FsSandboxTool { - Logger logger = Logger.getLogger(ListDirectoryTool.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(ListDirectoryTool.class); public ListDirectoryTool() { super("fs_list_directory", "filesystem", "List contents of a directory"); @@ -39,7 +39,7 @@ public ListDirectoryTool() { Map properties = new HashMap<>(); properties.put("path", pathProperty); - List required = Arrays.asList("path"); + List required = List.of("path"); schema.put("type", "object"); schema.put("properties", properties); @@ -61,8 +61,7 @@ public String fs_list_directory(String path) { throw new RuntimeException("Only FilesystemSandbox supported in list directory tool"); } catch (Exception e) { String errorMsg = "List Directory Error: " + e.getMessage(); - logger.severe(errorMsg); - e.printStackTrace(); + logger.error(errorMsg); return errorMsg; } } diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/tools/fs/MoveFileTool.java b/core/src/main/java/io/agentscope/runtime/sandbox/tools/fs/MoveFileTool.java index 43979225..2eb9029d 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/tools/fs/MoveFileTool.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/tools/fs/MoveFileTool.java @@ -18,16 +18,17 @@ import io.agentscope.runtime.sandbox.box.FilesystemSandbox; import io.agentscope.runtime.sandbox.box.Sandbox; import io.agentscope.runtime.sandbox.tools.SandboxTool; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.logging.Logger; public class MoveFileTool extends FsSandboxTool { - Logger logger = Logger.getLogger(MoveFileTool.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(MoveFileTool.class); public MoveFileTool() { super("fs_move_file", "filesystem", "Move or rename a file or directory"); @@ -67,8 +68,7 @@ public String fs_move_file(String source, String destination) { throw new RuntimeException("Only FilesystemSandbox supported in move file tool"); } catch (Exception e) { String errorMsg = "Move File Error: " + e.getMessage(); - logger.severe(errorMsg); - e.printStackTrace(); + logger.error(errorMsg); return errorMsg; } } diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/tools/fs/ReadFileTool.java b/core/src/main/java/io/agentscope/runtime/sandbox/tools/fs/ReadFileTool.java index 0dc86109..f07ec616 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/tools/fs/ReadFileTool.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/tools/fs/ReadFileTool.java @@ -18,16 +18,16 @@ import io.agentscope.runtime.sandbox.box.FilesystemSandbox; import io.agentscope.runtime.sandbox.box.Sandbox; import io.agentscope.runtime.sandbox.tools.SandboxTool; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.logging.Logger; public class ReadFileTool extends FsSandboxTool { - Logger logger = Logger.getLogger(ReadFileTool.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(ReadFileTool.class); public ReadFileTool() { super("fs_read_file", "filesystem", "Read contents of a file"); @@ -39,7 +39,7 @@ public ReadFileTool() { Map properties = new HashMap<>(); properties.put("path", pathProperty); - List required = Arrays.asList("path"); + List required = List.of("path"); schema.put("type", "object"); schema.put("properties", properties); @@ -61,8 +61,7 @@ public String fs_read_file(String path) { throw new RuntimeException("Only FilesystemSandbox supported in read file tool"); } catch (Exception e) { String errorMsg = "Read File Error: " + e.getMessage(); - logger.severe(errorMsg); - e.printStackTrace(); + logger.error(errorMsg); return errorMsg; } } diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/tools/fs/ReadMultipleFilesTool.java b/core/src/main/java/io/agentscope/runtime/sandbox/tools/fs/ReadMultipleFilesTool.java index 22370e58..07226c04 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/tools/fs/ReadMultipleFilesTool.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/tools/fs/ReadMultipleFilesTool.java @@ -18,16 +18,16 @@ import io.agentscope.runtime.sandbox.box.FilesystemSandbox; import io.agentscope.runtime.sandbox.box.Sandbox; import io.agentscope.runtime.sandbox.tools.SandboxTool; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; -import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.logging.Logger; public class ReadMultipleFilesTool extends FsSandboxTool { - Logger logger = Logger.getLogger(ReadMultipleFilesTool.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(ReadMultipleFilesTool.class); public ReadMultipleFilesTool() { super("fs_read_multiple_files", "filesystem", "Read contents of multiple files"); @@ -40,7 +40,7 @@ public ReadMultipleFilesTool() { Map properties = new HashMap<>(); properties.put("paths", pathsProperty); - List required = Arrays.asList("paths"); + List required = List.of("paths"); schema.put("type", "object"); schema.put("properties", properties); @@ -62,8 +62,7 @@ public String fs_read_multiple_files(String[] paths) { throw new RuntimeException("Only FilesystemSandbox supported in read multiple files tool"); } catch (Exception e) { String errorMsg = "Read Multiple Files Error: " + e.getMessage(); - logger.severe(errorMsg); - e.printStackTrace(); + logger.error(errorMsg); return errorMsg; } } diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/tools/fs/SearchFilesTool.java b/core/src/main/java/io/agentscope/runtime/sandbox/tools/fs/SearchFilesTool.java index 9893cc6c..8c0d5bd1 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/tools/fs/SearchFilesTool.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/tools/fs/SearchFilesTool.java @@ -18,16 +18,17 @@ import io.agentscope.runtime.sandbox.box.FilesystemSandbox; import io.agentscope.runtime.sandbox.box.Sandbox; import io.agentscope.runtime.sandbox.tools.SandboxTool; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.logging.Logger; public class SearchFilesTool extends FsSandboxTool { - Logger logger = Logger.getLogger(SearchFilesTool.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(SearchFilesTool.class); public SearchFilesTool() { super("fs_search_files", "filesystem", "Search for files matching a pattern"); @@ -72,8 +73,7 @@ public String fs_search_files(String path, String pattern, String[] excludePatte throw new RuntimeException("Only FilesystemSandbox supported in search files tool"); } catch (Exception e) { String errorMsg = "Search Files Error: " + e.getMessage(); - logger.severe(errorMsg); - e.printStackTrace(); + logger.error(errorMsg); return errorMsg; } } diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/tools/fs/WriteFileTool.java b/core/src/main/java/io/agentscope/runtime/sandbox/tools/fs/WriteFileTool.java index 02697d9b..8608437f 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/tools/fs/WriteFileTool.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/tools/fs/WriteFileTool.java @@ -18,16 +18,17 @@ import io.agentscope.runtime.sandbox.box.FilesystemSandbox; import io.agentscope.runtime.sandbox.box.Sandbox; import io.agentscope.runtime.sandbox.tools.SandboxTool; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.logging.Logger; public class WriteFileTool extends FsSandboxTool { - Logger logger = Logger.getLogger(WriteFileTool.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(WriteFileTool.class); public WriteFileTool() { super("fs_write_file", "filesystem", "Write content to a file"); @@ -67,8 +68,7 @@ public String fs_write_file(String path, String content) { throw new RuntimeException("Only FilesystemSandbox supported in write file tool"); } catch (Exception e) { String errorMsg = "Write File Error: " + e.getMessage(); - logger.severe(errorMsg); - e.printStackTrace(); + logger.error(errorMsg); return errorMsg; } } diff --git a/web/src/main/java/io/agentscope/runtime/LocalDeployManager.java b/web/src/main/java/io/agentscope/runtime/LocalDeployManager.java index 10d45598..fe509a11 100644 --- a/web/src/main/java/io/agentscope/runtime/LocalDeployManager.java +++ b/web/src/main/java/io/agentscope/runtime/LocalDeployManager.java @@ -20,6 +20,9 @@ import io.agentscope.runtime.engine.Runner; import io.agentscope.runtime.protocol.Protocol; import io.agentscope.runtime.protocol.ProtocolConfig; +import org.jetbrains.annotations.NotNull; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.boot.WebApplicationType; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.builder.SpringApplicationBuilder; @@ -34,11 +37,10 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.logging.Logger; import java.util.function.Consumer; public class LocalDeployManager implements DeployManager { - Logger logger = Logger.getLogger(LocalDeployManager.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(LocalDeployManager.class); private ConfigurableApplicationContext applicationContext; @@ -73,7 +75,7 @@ public synchronized void deploy(Runner runner) { serverProps.put("server.address", this.host); } - logger.info("Starting streaming deployment for endpoint: " + endpointName); + logger.info("Starting streaming deployment for endpoint: {}", endpointName); this.applicationContext = new SpringApplicationBuilder() .sources(LocalDeployConfig.class) @@ -101,7 +103,7 @@ public synchronized void deploy(Runner runner) { if (corsConfigurer != null) { ctx.registerBean(WebMvcConfigurer.class, () -> new WebMvcConfigurer() { @Override - public void addCorsMappings(CorsRegistry registry) { + public void addCorsMappings(@NotNull CorsRegistry registry) { corsConfigurer.accept(registry); } }); @@ -110,7 +112,7 @@ public void addCorsMappings(CorsRegistry registry) { }) .run(); - logger.info("Streaming deployment completed for endpoint: " + endpointName); + logger.info("Streaming deployment completed for endpoint: {}", endpointName); } /** diff --git a/web/src/main/java/io/agentscope/runtime/autoconfigure/controller/SandboxManagerController.java b/web/src/main/java/io/agentscope/runtime/autoconfigure/controller/SandboxManagerController.java index f015d39a..94d06cc3 100644 --- a/web/src/main/java/io/agentscope/runtime/autoconfigure/controller/SandboxManagerController.java +++ b/web/src/main/java/io/agentscope/runtime/autoconfigure/controller/SandboxManagerController.java @@ -17,6 +17,8 @@ package io.agentscope.runtime.autoconfigure.controller; import io.agentscope.runtime.engine.Runner; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -33,7 +35,6 @@ import java.lang.reflect.Parameter; import java.util.HashMap; import java.util.Map; -import java.util.logging.Logger; import javax.annotation.PostConstruct; @@ -45,7 +46,7 @@ @RequestMapping("/sandbox") public class SandboxManagerController { - private static final Logger logger = Logger.getLogger(SandboxManagerController.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(SandboxManagerController.class); private final Map endpointRegistry = new HashMap<>(); @@ -56,9 +57,9 @@ public class SandboxManagerController { public void registerEndpoints() { Class clazz = SandboxManager.class; - logger.info("Scanning class: " + clazz.getName()); + logger.info("Scanning class: {}", clazz.getName()); Method[] methods = clazz.getDeclaredMethods(); - logger.info("Found " + methods.length + " methods in SandboxManager"); + logger.info("Found {} methods in SandboxManager", methods.length); for (Method method : methods) { RemoteWrapper annotation = method.getAnnotation(RemoteWrapper.class); @@ -73,12 +74,11 @@ public void registerEndpoints() { MethodInfo methodInfo = new MethodInfo(method, annotation); endpointRegistry.put(path, methodInfo); - logger.info("Registered endpoint: " + annotation.method() + " " + path + - " -> " + method.getName()); + logger.info("Registered endpoint: {} {} -> {}", annotation.method(), path, method.getName()); } } - logger.info("Total endpoints registered: " + endpointRegistry.size()); + logger.info("Total endpoints registered: {}", endpointRegistry.size()); } /** @@ -141,21 +141,19 @@ private ResponseEntity> handleRequest( // Todo: fix this SandboxManager sandboxManager = runner.getSandboxManager(); - logger.info("Handling " + httpMethod + " request for path: " + path); + logger.info("Handling {} request for path: {}", httpMethod, path); MethodInfo methodInfo = endpointRegistry.get(path); if (methodInfo == null) { - logger.warning("No endpoint found for path: " + path); + logger.warn("No endpoint found for path: {}", path); Map errorResponse = new HashMap<>(); errorResponse.put("error", "Endpoint not found: " + path); return ResponseEntity.status(HttpStatus.NOT_FOUND).body(errorResponse); } if (!methodInfo.annotation.method().name().equals(httpMethod.name())) { - logger.warning("HTTP method mismatch for path: " + path + - " (expected: " + methodInfo.annotation.method() + - ", got: " + httpMethod + ")"); + logger.warn("HTTP method mismatch for path: {} (expected: {}, got: {})", path, methodInfo.annotation.method(), httpMethod); Map errorResponse = new HashMap<>(); errorResponse.put("error", "Method not allowed"); return ResponseEntity.status(HttpStatus.METHOD_NOT_ALLOWED).body(errorResponse); @@ -178,8 +176,7 @@ private ResponseEntity> handleRequest( return ResponseEntity.ok(response); } catch (Exception e) { - logger.severe("Error processing request: " + e.getMessage()); - e.printStackTrace(); + logger.error("Error processing request: {}", e.getMessage()); Map errorResponse = new HashMap<>(); errorResponse.put("error", "Error: " + e.getMessage()); @@ -255,7 +252,7 @@ private Object convertValue(Object value, Class targetType) { Object enumConstant = Enum.valueOf((Class) targetType, enumValue); return enumConstant; } catch (IllegalArgumentException e) { - logger.warning("Invalid enum value '" + enumValue + "' for type " + targetType.getName()); + logger.warn("Invalid enum value '{}' for type {}", enumValue, targetType.getName()); return null; } } diff --git a/web/src/main/java/io/agentscope/runtime/protocol/a2a/GraphAgentExecutor.java b/web/src/main/java/io/agentscope/runtime/protocol/a2a/GraphAgentExecutor.java index 944c0a16..2b5e3b87 100644 --- a/web/src/main/java/io/agentscope/runtime/protocol/a2a/GraphAgentExecutor.java +++ b/web/src/main/java/io/agentscope/runtime/protocol/a2a/GraphAgentExecutor.java @@ -28,6 +28,8 @@ import io.agentscope.runtime.engine.schemas.*; import io.agentscope.runtime.protocol.a2a.controller.ContextKeys; import org.reactivestreams.Subscription; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import reactor.core.publisher.Flux; import java.util.HashMap; @@ -36,14 +38,13 @@ import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; -import java.util.logging.Logger; public class GraphAgentExecutor implements AgentExecutor { private final Runner runner; private final Map subscriptions; - Logger logger = Logger.getLogger(GraphAgentExecutor.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(GraphAgentExecutor.class); public GraphAgentExecutor(Runner runner) { this.runner = runner; @@ -59,9 +60,9 @@ public void execute(RequestContext context, EventQueue eventQueue) throws JSONRP Task task = context.getTask(); if (task == null) { task = newTask(context.getMessage()); - logger.info("Created new task: " + task.getId()); + logger.info("Created new task: {}", task.getId()); } else { - logger.info("Using existing task: " + task.getId()); + logger.info("Using existing task: {}", task.getId()); } if (isBlockRequest(context)) { processTaskBlocking(context, eventQueue, task, resultFlux); @@ -73,7 +74,7 @@ public void execute(RequestContext context, EventQueue eventQueue) throws JSONRP logger.info("Agent execution completed successfully"); } catch (Exception e) { - logger.severe("Agent execution failed" + e.getMessage()); + logger.error("Agent execution failed: {}", e.getMessage()); eventQueue.enqueueEvent(A2A.toAgentMessage("Agent execution failed: " + e.getMessage())); } } @@ -151,8 +152,8 @@ private void processTaskBlocking(RequestContext context, EventQueue eventQueue, if (output instanceof TextContent text) { String content = text.getText(); accumulatedOutput.append(content); - logger.info("Appended content chunk (" + content.length() + " chars), total so far: " - + accumulatedOutput.length()); + logger.info("Appended content chunk ({} chars), total so far: {}", + content.length(), accumulatedOutput.length()); } } // Todo: need to know whether the blocking mode should also handle tool calls and responses @@ -210,7 +211,7 @@ else if (output instanceof Message message) { eventQueue.enqueueEvent(errorMessage); }) .doFinally(signal -> { - logger.info("Subscribe and process stream output terminated: " + signal); + logger.info("Subscribe and process stream output terminated: {}", signal); subscriptions.remove(context.getTaskId()); }) .blockLast(); @@ -223,9 +224,9 @@ private void processTaskNonBlocking(RequestContext context, EventQueue eventQueu eventQueue.enqueueEvent(task); logger.info("Starting streaming output processing"); processStreamingOutput(resultFlux, taskUpdater, accumulatedOutput); - logger.info("Streaming output processing completed. Total output length: " + accumulatedOutput.length()); + logger.info("Streaming output processing completed. Total output length: {}", accumulatedOutput.length()); } catch (Exception e) { - logger.severe("Error processing streaming output" + e.getMessage()); + logger.error("Error processing streaming output: {}", e.getMessage()); taskUpdater.fail(taskUpdater.newAgentMessage( List.of(new TextPart("Error processing streaming output: " + e.getMessage())), Map.of() @@ -266,8 +267,8 @@ private void processStreamingOutput(Flux resultFlux, TaskUpdater taskUpda false ); accumulatedOutput.append(content); - logger.info("Appended content chunk (" + content.length() + " chars), total so far: " - + accumulatedOutput.length()); + logger.info("Appended content chunk ({} chars), total so far: {}", + content.length(), accumulatedOutput.length()); } } } else if (output instanceof Message message) { @@ -340,7 +341,7 @@ private void processStreamingOutput(Flux resultFlux, TaskUpdater taskUpda taskUpdater.fail(errorMessage); }) .doFinally(signal -> { - logger.info("Subscribe and process stream output terminated: " + signal); + logger.info("Subscribe and process stream output terminated: {}", signal); subscriptions.remove(taskUpdater.getTaskId()); }) .blockLast(); diff --git a/web/src/main/java/io/agentscope/runtime/protocol/a2a/controller/A2aController.java b/web/src/main/java/io/agentscope/runtime/protocol/a2a/controller/A2aController.java index ecd83739..5e8b28ac 100644 --- a/web/src/main/java/io/agentscope/runtime/protocol/a2a/controller/A2aController.java +++ b/web/src/main/java/io/agentscope/runtime/protocol/a2a/controller/A2aController.java @@ -27,6 +27,8 @@ import io.agentscope.runtime.protocol.a2a.JSONRPCHandler; import jakarta.servlet.http.HttpServletRequest; import org.reactivestreams.FlowAdapters; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.ObjectProvider; import org.springframework.http.MediaType; import org.springframework.http.codec.ServerSentEvent; @@ -39,13 +41,12 @@ import java.util.HashSet; import java.util.Map; import java.util.concurrent.Flow; -import java.util.logging.Logger; @RestController @RequestMapping("/a2a") public class A2aController { - Logger logger = Logger.getLogger(A2aController.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(A2aController.class); private final JSONRPCHandler jsonRpcHandler; @@ -70,7 +71,7 @@ public Object handleRequest(@RequestBody String body, HttpServletRequest httpReq logger.info("Handling non-streaming request, returning JSON response"); } } catch (JsonProcessingException e) { - logger.severe("JSON parsing error: " + e.getMessage()); + logger.error("JSON parsing error: {}", e.getMessage()); result = new JSONRPCErrorResponse(null, new JSONParseError()); } return result; @@ -118,7 +119,7 @@ private ServerSentEvent convertToSSE(JSONRPCResponse response) { } return builder.build(); } catch (Exception e) { - logger.severe("Error converting response to SSE: " + e.getMessage()); + logger.error("Error converting response to SSE: {}", e.getMessage()); return ServerSentEvent.builder().data("{\"error\":\"Internal conversion error\"}").event("error") .build(); } diff --git a/web/src/main/java/io/agentscope/runtime/protocol/responseapi/ResponseApiHandler.java b/web/src/main/java/io/agentscope/runtime/protocol/responseapi/ResponseApiHandler.java index 4f52df6e..616408b7 100644 --- a/web/src/main/java/io/agentscope/runtime/protocol/responseapi/ResponseApiHandler.java +++ b/web/src/main/java/io/agentscope/runtime/protocol/responseapi/ResponseApiHandler.java @@ -23,18 +23,19 @@ import io.agentscope.runtime.engine.schemas.*; import io.agentscope.runtime.protocol.responseapi.model.*; import io.agentscope.runtime.protocol.responseapi.model.Error; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import reactor.core.publisher.Flux; import java.time.Instant; import java.util.*; -import java.util.logging.Logger; /** * Handler for OpenAI Responses API requests. */ public class ResponseApiHandler { - private static final Logger logger = Logger.getLogger(ResponseApiHandler.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(ResponseApiHandler.class); private static final ObjectMapper objectMapper = new ObjectMapper(); private final Runner runner; @@ -63,7 +64,7 @@ public Flux handleStreamingResponse(ResponseApiRequest requ return handleStreamingFlux(eventFlux); } catch (Exception e) { - logger.severe("Error handling chat completion: " + e.getMessage()); + logger.error("Error handling chat completion: {}", e.getMessage()); return Flux.just(createErrorEvent("Error: " + e.getMessage(), "internal_error")); } } @@ -90,7 +91,7 @@ public Flux handleStreamingFlux(Flux eventFlux) { return Flux.empty(); } }).onErrorResume(e -> { - logger.severe("Streaming error: " + e.getMessage()); + logger.error("Streaming error: {}", e.getMessage()); return Flux.just(createErrorEvent("Streaming error: " + e.getMessage(), "internal_error")); }) .concatWith(Flux.just( @@ -167,7 +168,7 @@ public ResponseApiResponse handleNonStreamingResponse(ResponseApiRequest request response.setUsage(buildUsagePlaceholder()); } catch (Exception e) { - logger.severe("Error handling non-streaming response: " + e.getMessage()); + logger.error("Error handling non-streaming response: {}", e.getMessage()); Error error = new Error(); error.setMessage(e.getMessage()); error.setCode("internal_error"); @@ -246,8 +247,7 @@ private List buildContentPayload(List events) { if (output instanceof TextContent text) { String content = text.getText(); accumulatedOutput.append(content); - logger.info("Appended content chunk (" + content.length() + " chars), total so far: " - + accumulatedOutput.length()); + logger.info("Appended content chunk ({} chars), total so far: {}", content.length(), accumulatedOutput.length()); } } // Todo: need to know whether the blocking mode should also handle tool calls and responses diff --git a/web/src/main/java/io/agentscope/runtime/protocol/responseapi/controller/ResponseApiController.java b/web/src/main/java/io/agentscope/runtime/protocol/responseapi/controller/ResponseApiController.java index 4f2f5d28..15cad58d 100644 --- a/web/src/main/java/io/agentscope/runtime/protocol/responseapi/controller/ResponseApiController.java +++ b/web/src/main/java/io/agentscope/runtime/protocol/responseapi/controller/ResponseApiController.java @@ -21,12 +21,12 @@ import io.agentscope.runtime.protocol.responseapi.ResponseApiHandler; import io.agentscope.runtime.protocol.responseapi.ResponseApiHandlerConfiguration; import io.agentscope.runtime.protocol.responseapi.model.ResponseApiRequest; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.ObjectProvider; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; -import java.util.logging.Logger; - /** * REST controller for OpenAI Responses API protocol endpoints. */ @@ -34,7 +34,7 @@ @RequestMapping("/compatible-mode/v1") public class ResponseApiController { - private static final Logger logger = Logger.getLogger(ResponseApiController.class.getName()); + private static final Logger logger = LoggerFactory.getLogger(ResponseApiController.class); private final ResponseApiHandler responseApiHandler; From e37ed6c93e5922acde141680a78da01b796391cd Mon Sep 17 00:00:00 2001 From: xuehuitian45 <13069167198@163.com> Date: Mon, 29 Dec 2025 14:23:38 +0800 Subject: [PATCH 2/2] fix: remove unused imports --- .../runtime/sandbox/tools/base/RunShellCommandTool.java | 1 - 1 file changed, 1 deletion(-) diff --git a/core/src/main/java/io/agentscope/runtime/sandbox/tools/base/RunShellCommandTool.java b/core/src/main/java/io/agentscope/runtime/sandbox/tools/base/RunShellCommandTool.java index a7fc3562..a498032f 100644 --- a/core/src/main/java/io/agentscope/runtime/sandbox/tools/base/RunShellCommandTool.java +++ b/core/src/main/java/io/agentscope/runtime/sandbox/tools/base/RunShellCommandTool.java @@ -21,7 +21,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map;