فهرست منبع

refactor: continue replacing std::cout/std::cerr with structured logging

- Replace critical error messages in main.cpp with LOG_ERROR/LOG_WARNING
- Replace configuration output in main.cpp with structured logging
- Replace initialization and shutdown messages in main.cpp with LOG_INFO
- Replace error messages in generation_queue.cpp with LOG_ERROR/LOG_WARNING
- Maintain backward compatibility and systemd compatibility

This continues the refactoring to eliminate uncontrolled terminal output
and provide better structured logging throughout the application.
Fszontagh 3 ماه پیش
والد
کامیت
00c2f67c5f
4فایلهای تغییر یافته به همراه75 افزوده شده و 72 حذف شده
  1. 1 0
      auth/api_keys.json
  2. 1 0
      auth/users.json
  3. 9 10
      src/generation_queue.cpp
  4. 64 62
      src/main.cpp

+ 1 - 0
auth/api_keys.json

@@ -0,0 +1 @@
+{}

+ 1 - 0
auth/users.json

@@ -0,0 +1 @@
+{}

+ 9 - 10
src/generation_queue.cpp

@@ -467,8 +467,7 @@ public:
         std::error_code ec;
         std::filesystem::create_directories(jobOutputDir, ec);
         if (ec) {
-            std::cerr << "Failed to create output directory " << jobOutputDir
-                      << ": " << ec.message() << std::endl;
+            LOG_ERROR("Failed to create output directory " + jobOutputDir + ": " + ec.message());
             return "";
         }
 
@@ -481,20 +480,20 @@ public:
 
         // Check if image data is valid
         if (image.data.empty() || image.width <= 0 || image.height <= 0) {
-            std::cerr << "Invalid image data for " << requestId << "_" << index
-                      << ": width=" << image.width
-                      << ", height=" << image.height
-                      << ", channels=" << image.channels
-                      << ", data_size=" << image.data.size() << std::endl;
+            LOG_ERROR("Invalid image data for " + requestId + "_" + std::to_string(index) +
+                     ": width=" + std::to_string(image.width) +
+                     ", height=" + std::to_string(image.height) +
+                     ", channels=" + std::to_string(image.channels) +
+                     ", data_size=" + std::to_string(image.data.size()));
             return "";
         }
 
         // Validate image data integrity
         const size_t expectedDataSize = static_cast<size_t>(image.width) * image.height * image.channels;
         if (image.data.size() != expectedDataSize) {
-            std::cerr << "Image data size mismatch for " << requestId << "_" << index
-                      << ": expected=" << expectedDataSize
-                      << ", actual=" << image.data.size() << std::endl;
+            LOG_WARNING("Image data size mismatch for " + requestId + "_" + std::to_string(index) +
+                     ": expected=" + std::to_string(expectedDataSize) +
+                     ", actual=" + std::to_string(image.data.size()));
             // Continue anyway, but log the warning
         }
 

+ 64 - 62
src/main.cpp

@@ -143,7 +143,7 @@ ServerConfig parseArguments(int argc, char* argv[]) {
             } else if (method == "optional") {
                 config.auth.authMethod = AuthMethod::OPTIONAL;
             } else {
-                std::cerr << "Invalid auth method: " << method << std::endl;
+                LOG_ERROR("Invalid auth method: " + method);
                 exit(1);
             }
         } else if (arg == "--jwt-secret" && i + 1 < argc) {
@@ -266,16 +266,16 @@ ServerConfig parseArguments(int argc, char* argv[]) {
                       << std::endl;
             exit(0);
         } else {
-            std::cerr << "Unknown argument: " << arg << std::endl;
-            std::cerr << "Use --help for usage information" << std::endl;
+            LOG_ERROR("Unknown argument: " + arg);
+            LOG_ERROR("Use --help for usage information");
             exit(1);
         }
     }
 
     // Validate required parameters
     if (!modelsDirSet) {
-        std::cerr << "Error: --models-dir is required" << std::endl;
-        std::cerr << "Use --help for usage information" << std::endl;
+        LOG_ERROR("Error: --models-dir is required");
+        LOG_ERROR("Use --help for usage information");
         exit(1);
     }
 
@@ -353,35 +353,35 @@ int main(int argc, char* argv[]) {
     }
 
     if (config.verbose) {
-        std::cout << "\n=== Configuration ===" << std::endl;
-        std::cout << "Version: " << sd_rest::VERSION_INFO.version_full << " (" << sd_rest::VERSION_INFO.version_type << ")" << std::endl;
-        std::cout << "Commit: " << sd_rest::VERSION_INFO.commit_short << (sd_rest::VERSION_INFO.is_clean ? "" : " (dirty)") << std::endl;
-        std::cout << "Build time: " << sd_rest::VERSION_INFO.build_time << std::endl;
-        std::cout << std::endl;
-        std::cout << "Server:" << std::endl;
-        std::cout << "  Host: " << config.host << std::endl;
-        std::cout << "  Port: " << config.port << std::endl;
-        std::cout << "  Max concurrent generations: " << config.maxConcurrentGenerations << std::endl;
-        std::cout << "  Queue directory: " << config.queueDir << std::endl;
-        std::cout << "  Output directory: " << config.outputDir << std::endl;
-        std::cout << "\nModel Directories:" << std::endl;
-        std::cout << "  Base models directory: " << config.modelsDir << std::endl;
-        std::cout << "  Checkpoints:  " << config.checkpoints << std::endl;
-        std::cout << "  ControlNet:   " << config.controlnetDir << std::endl;
-        std::cout << "  Embeddings:   " << config.embeddingsDir << std::endl;
-        std::cout << "  ESRGAN:       " << config.esrganDir << std::endl;
-        std::cout << "  LoRA:         " << config.loraDir << std::endl;
-        std::cout << "  TAESD:        " << config.taesdDir << std::endl;
-        std::cout << "  VAE:          " << config.vaeDir << std::endl;
-        std::cout << "  Diffusion:    " << config.diffusionModelsDir << std::endl;
-        std::cout << std::endl;
+        LOG_INFO("\n=== Configuration ===");
+        LOG_INFO("Version: " + std::string(sd_rest::VERSION_INFO.version_full) + " (" + std::string(sd_rest::VERSION_INFO.version_type) + ")");
+        LOG_INFO("Commit: " + std::string(sd_rest::VERSION_INFO.commit_short) + (sd_rest::VERSION_INFO.is_clean ? "" : " (dirty)"));
+        LOG_INFO("Build time: " + std::string(sd_rest::VERSION_INFO.build_time));
+        LOG_INFO("");
+        LOG_INFO("Server:");
+        LOG_INFO("  Host: " + config.host);
+        LOG_INFO("  Port: " + std::to_string(config.port));
+        LOG_INFO("  Max concurrent generations: " + std::to_string(config.maxConcurrentGenerations));
+        LOG_INFO("  Queue directory: " + config.queueDir);
+        LOG_INFO("  Output directory: " + config.outputDir);
+        LOG_INFO("\nModel Directories:");
+        LOG_INFO("  Base models directory: " + config.modelsDir);
+        LOG_INFO("  Checkpoints:  " + config.checkpoints);
+        LOG_INFO("  ControlNet:   " + config.controlnetDir);
+        LOG_INFO("  Embeddings:   " + config.embeddingsDir);
+        LOG_INFO("  ESRGAN:       " + config.esrganDir);
+        LOG_INFO("  LoRA:         " + config.loraDir);
+        LOG_INFO("  TAESD:        " + config.taesdDir);
+        LOG_INFO("  VAE:          " + config.vaeDir);
+        LOG_INFO("  Diffusion:    " + config.diffusionModelsDir);
+        LOG_INFO("");
     }
 
     // Validate directory paths
     auto validateDirectory = [](const std::string& path, const std::string& name, bool required) -> bool {
         if (path.empty()) {
             if (required) {
-                std::cerr << "Error: " << name << " directory is required but not specified" << std::endl;
+                LOG_ERROR("Error: " + name + " directory is required but not specified");
                 return false;
             }
             return true;  // Empty path is valid for optional directories
@@ -390,16 +390,16 @@ int main(int argc, char* argv[]) {
         std::filesystem::path dirPath(path);
         if (!std::filesystem::exists(dirPath)) {
             if (required) {
-                std::cerr << "Error: " << name << " directory does not exist: " << path << std::endl;
+                LOG_ERROR("Error: " + name + " directory does not exist: " + path);
                 return false;
             } else {
-                std::cerr << "Warning: " << name << " directory does not exist: " << path << std::endl;
+                LOG_WARNING("Warning: " + name + " directory does not exist: " + path);
                 return true;  // Optional directory can be missing
             }
         }
 
         if (!std::filesystem::is_directory(dirPath)) {
-            std::cerr << "Error: " << name << " path is not a directory: " << path << std::endl;
+            LOG_ERROR("Error: " + name + " path is not a directory: " + path);
             return false;
         }
 
@@ -427,7 +427,7 @@ int main(int argc, char* argv[]) {
     // Validate UI directory if specified
     if (!config.uiDir.empty()) {
         if (!validateDirectory(config.uiDir, "Web UI", false)) {
-            std::cerr << "\nError: Web UI directory is invalid" << std::endl;
+            LOG_ERROR("Error: Web UI directory is invalid");
             return 1;
         }
 
@@ -435,12 +435,12 @@ int main(int argc, char* argv[]) {
         std::filesystem::path uiPath(config.uiDir);
         if (!std::filesystem::exists(uiPath / "index.html") &&
             !std::filesystem::exists(uiPath / "index.htm")) {
-            std::cerr << "Warning: Web UI directory does not contain an index.html or index.htm file: " << config.uiDir << std::endl;
+            LOG_WARNING("Warning: Web UI directory does not contain an index.html or index.htm file: " + config.uiDir);
         }
     }
 
     if (!allValid) {
-        std::cerr << "\nError: Base models directory is invalid or missing" << std::endl;
+        LOG_ERROR("Error: Base models directory is invalid or missing");
         return 1;
     }
 
@@ -451,7 +451,7 @@ int main(int argc, char* argv[]) {
     try {
         // Initialize authentication system
         if (config.verbose) {
-            std::cout << "Initializing authentication system..." << std::endl;
+            LOG_INFO("Initializing authentication system...");
         }
 
         auto userManager = std::make_shared<UserManager>(config.auth.dataDir,
@@ -460,40 +460,42 @@ int main(int argc, char* argv[]) {
                                                          config.defaultAdminPassword,
                                                          config.defaultAdminEmail);
         if (!userManager->initialize()) {
-            std::cerr << "Error: Failed to initialize user manager" << std::endl;
+            LOG_ERROR("Error: Failed to initialize user manager");
             return 1;
         }
 
-        if (config.verbose) {
-            std::cout << "User manager initialized" << std::endl;
-            std::cout << "Authentication method: ";
+if (config.verbose) {
+            LOG_INFO("User manager initialized");
+            std::string authMethod;
             switch (config.auth.authMethod) {
                 case AuthMethod::NONE:
-                    std::cout << "None";
+                    authMethod = "None";
                     break;
                 case AuthMethod::JWT:
-                    std::cout << "JWT";
+                    authMethod = "JWT";
                     break;
                 case AuthMethod::API_KEY:
-                    std::cout << "API Key";
+                    authMethod = "API Key";
                     break;
                 case AuthMethod::UNIX:
-                    std::cout << "Unix";
+                    authMethod = "Unix";
                     break;
                 case AuthMethod::OPTIONAL:
-                    std::cout << "Optional";
+                    authMethod = "Optional";
                     break;
                 case AuthMethod::PAM:
-                    std::cout << "PAM";
+                    authMethod = "PAM";
                     break;
+                default:
+                    authMethod = "Unknown";
             }
-            std::cout << std::endl;
+            LOG_INFO("Authentication method: " + authMethod);
         }
 
         // Initialize authentication middleware
         auto authMiddleware = std::make_shared<AuthMiddleware>(config.auth, userManager);
         if (!authMiddleware->initialize()) {
-            std::cerr << "Error: Failed to initialize authentication middleware" << std::endl;
+            LOG_ERROR("Error: Failed to initialize authentication middleware");
             return 1;
         }
 
@@ -514,42 +516,42 @@ int main(int argc, char* argv[]) {
 
         // Configure model manager with directory parameters
         if (config.verbose) {
-            std::cout << "Configuring model manager..." << std::endl;
+            LOG_INFO("Configuring model manager...");
         }
         if (!modelManager->configureFromServerConfig(config)) {
-            std::cerr << "Error: Failed to configure model manager with server config" << std::endl;
+            LOG_ERROR("Error: Failed to configure model manager with server config");
             return 1;
         }
 
         if (config.verbose) {
-            std::cout << "Model manager configured with per-type directories" << std::endl;
+            LOG_INFO("Model manager configured with per-type directories");
         }
 
         // Scan models directory
         if (config.verbose) {
-            std::cout << "Scanning models directory..." << std::endl;
+            LOG_INFO("Scanning models directory...");
         }
         if (!modelManager->scanModelsDirectory()) {
-            std::cerr << "Warning: Failed to scan models directory" << std::endl;
+            LOG_WARNING("Warning: Failed to scan models directory");
         } else if (config.verbose) {
-            std::cout << "Found " << modelManager->getAvailableModelsCount() << " models" << std::endl;
+            LOG_INFO("Found " + std::to_string(modelManager->getAvailableModelsCount()) + " models");
         }
 
         // Start the generation queue
         generationQueue->start();
         if (config.verbose) {
-            std::cout << "Generation queue started" << std::endl;
+            LOG_INFO("Generation queue started");
         }
 
         // Start the HTTP server
         if (!server->start(config.host, config.port)) {
-            std::cerr << "Failed to start server" << std::endl;
+            LOG_ERROR("Failed to start server");
             return 1;
         }
 
-        std::cout << "Server initialized successfully" << std::endl;
-        std::cout << "Server listening on " << config.host << ":" << config.port << std::endl;
-        std::cout << "Press Ctrl+C to stop the server" << std::endl;
+        LOG_INFO("Server initialized successfully");
+        LOG_INFO("Server listening on " + config.host + ":" + std::to_string(config.port));
+        LOG_INFO("Press Ctrl+C to stop the server");
 
         // Give server a moment to start
         std::this_thread::sleep_for(std::chrono::milliseconds(100));
@@ -560,13 +562,13 @@ int main(int argc, char* argv[]) {
         }
 
         // Graceful shutdown
-        std::cout << "Shutting down server..." << std::endl;
+        LOG_INFO("Shutting down server...");
 
         // Stop the server first to stop accepting new requests
         server->stop();
 
         // Unload all models to ensure contexts are properly freed
-        std::cout << "Unloading all models..." << std::endl;
+        LOG_INFO("Unloading all models...");
         modelManager->unloadAllModels();
 
         // Stop the generation queue
@@ -578,10 +580,10 @@ int main(int argc, char* argv[]) {
         // Clear global server pointer
         g_server = nullptr;
 
-        std::cout << "Server shutdown complete" << std::endl;
+        LOG_INFO("Server shutdown complete");
 
     } catch (const std::exception& e) {
-        std::cerr << "Error: " << e.what() << std::endl;
+        LOG_ERROR("Error: " + std::string(e.what()));
         return 1;
     }