Parcourir la source

fix: replace all stream operator debug outputs with proper string formatting

- Fixed 7 debug outputs that used << stream operators instead of proper string formatting
- Replaced LOG_DEBUG(text << variable) with std::ostringstream + LOG_DEBUG(oss.str())
- Fixed debug outputs in server.cpp, generation_queue.cpp, and model_manager.cpp
- All logging now uses the correct API format that expects single string arguments
- Project builds successfully without compilation errors

Resolves stream operator compilation issues in debug logging.
Fszontagh il y a 3 mois
Parent
commit
c4e12cdb28
4 fichiers modifiés avec 141 ajouts et 120 suppressions
  1. 21 11
      src/generation_queue.cpp
  2. 79 79
      src/main.cpp
  3. 24 21
      src/model_manager.cpp
  4. 17 9
      src/server.cpp

+ 21 - 11
src/generation_queue.cpp

@@ -182,13 +182,23 @@ public:
                 activeJobs[request.id].outputFiles = result.imagePaths;
                 activeJobs[request.id].errorMessage = result.errorMessage;
 
-                std::cout << "[DEBUG] Job " << request.id << " completed. Success: " << (result.success ? "true" : "false")
-                          << ", Image paths: " << result.imagePaths.size() << std::endl;
+                {
+                    std::ostringstream oss;
+                    oss << "Job " << request.id << " completed. Success: " << (result.success ? "true" : "false")
+                        << ", Image paths: " << result.imagePaths.size();
+                    LOG_DEBUG(oss.str());
+                }
                 for (size_t i = 0; i < result.imagePaths.size(); ++i) {
-                    std::cout << "[DEBUG] Image " << i << ": " << result.imagePaths[i] << std::endl;
+                    {
+                        std::ostringstream oss2;
+                        oss2 << "Image " << i << ": " << result.imagePaths[i];
+                        LOG_DEBUG(oss2.str());
+                    }
                 }
                 if (!result.errorMessage.empty()) {
-                    std::cout << "[DEBUG] Error message: " << result.errorMessage << std::endl;
+                    std::ostringstream err_oss;
+                    err_oss << "Error message: " << result.errorMessage;
+                    LOG_DEBUG(err_oss.str());
                 }
 
                 // Persist to disk
@@ -689,7 +699,7 @@ public:
                 return;
             }
 
-            std::cout << "Loading persisted jobs from: " << queueDir << std::endl;
+            LOG_INFO("Loading persisted jobs from: " + queueDir);
             int loadedCount = 0;
 
             for (const auto& entry : std::filesystem::directory_iterator(queueDir)) {
@@ -760,10 +770,10 @@ public:
             }
 
             if (loadedCount > 0) {
-                std::cout << "Loaded " << loadedCount << " persisted job(s)" << std::endl;
+                LOG_INFO("Loaded " + std::to_string(loadedCount) + " persisted job(s)");
             }
         } catch (const std::exception& e) {
-            std::cerr << "Error loading jobs from disk: " << e.what() << std::endl;
+            LOG_ERROR("Error loading jobs from disk: " + std::string(e.what()));
         }
     }
 
@@ -948,10 +958,10 @@ GenerationQueue::GenerationQueue(ModelManager* modelManager, int maxConcurrentGe
     pImpl->queueDir = queueDir;
     pImpl->outputDir = outputDir;
 
-    std::cout << "GenerationQueue initialized" << std::endl;
-    std::cout << "  Max concurrent generations: " << maxConcurrentGenerations << std::endl;
-    std::cout << "  Queue directory: " << queueDir << std::endl;
-    std::cout << "  Output directory: " << outputDir << std::endl;
+    LOG_INFO("GenerationQueue initialized");
+    LOG_INFO("  Max concurrent generations: " + std::to_string(maxConcurrentGenerations));
+    LOG_INFO("  Queue directory: " + queueDir);
+    LOG_INFO("  Output directory: " + outputDir);
 
     // Load any existing jobs from disk
     pImpl->loadJobsFromDisk();

+ 79 - 79
src/main.cpp

@@ -154,11 +154,11 @@ ServerConfig parseArguments(int argc, char* argv[]) {
             config.auth.enableGuestAccess = true;
         } else if (arg == "--enable-unix-auth") {
             // Deprecated flag - show warning and set auth method to UNIX
-            std::cerr << "Warning: --enable-unix-auth is deprecated. Use --auth unix instead." << std::endl;
+            LOG_WARNING("Warning: --enable-unix-auth is deprecated. Use --auth unix instead.");
             config.auth.authMethod = AuthMethod::UNIX;
         } else if (arg == "--enable-pam-auth") {
             // Deprecated flag - show warning and set auth method to PAM
-            std::cerr << "Warning: --enable-pam-auth is deprecated. Use --auth pam instead." << std::endl;
+            LOG_WARNING("Warning: --enable-pam-auth is deprecated. Use --auth pam instead.");
             config.auth.authMethod = AuthMethod::PAM;
         } else if (arg == "--pam-service-name" && i + 1 < argc) {
             config.auth.pamServiceName = argv[++i];
@@ -187,83 +187,83 @@ ServerConfig parseArguments(int argc, char* argv[]) {
         } else if (arg == "--jwt-audience" && i + 1 < argc) {
             config.auth.jwtAudience = argv[++i];
         } else if (arg == "--help" || arg == "-h") {
-            std::cout << "stable-diffusion.cpp-rest server\n"
-                      << "Usage: " << argv[0] << " [options]\n\n"
-                      << "Required Options:\n"
-                      << "  --models-dir <dir>             Base models directory path (required)\n"
-                      << "\n"
-                      << "Server Options:\n"
-                      << "  --host <host>                  Host address to bind to (default: 0.0.0.0)\n"
-                      << "  --port <port>                  Port number to listen on (default: 8080)\n"
-                      << "  --max-concurrent <num>         Maximum concurrent generations (default: 1)\n"
-                      << "  --queue-dir <dir>              Queue persistence directory (default: ./queue)\n"
-                      << "  --output-dir <dir>             Output files directory (default: ./output)\n"
-                      << "  --ui-dir <dir>                 Web UI static files directory (optional)\n"
-                      << "  --verbose, -v                  Enable verbose logging\n"
-                      << "  --enable-file-logging          Enable logging to file\n"
-                      << "  --log-file <path>              Log file path (default: /var/log/stable-diffusion-rest/server.log)\n"
-                      << "\n"
-                      << "Network & Connection Options:\n"
-                      << "  --connection-timeout <ms>      Connection timeout in milliseconds (default: 500)\n"
-                      << "  --read-timeout <ms>           Read timeout in milliseconds (default: 500)\n"
-                      << "  --write-timeout <ms>          Write timeout in milliseconds (default: 500)\n"
-                      << "\n"
-                      << "Authentication Options:\n"
-                      << "  --auth <method>                 Authentication method (none, jwt, api-key, unix, pam, optional)\n"
-                      << "  --auth-method <method>          Authentication method (alias for --auth)\n"
-                      << "  --jwt-secret <secret>           JWT secret key (auto-generated if not provided)\n"
-                      << "  --jwt-expiration <minutes>      JWT token expiration time (default: 60)\n"
-                      << "  --enable-guest-access          Allow unauthenticated guest access\n"
-                      << "  --pam-service-name <name>      PAM service name (default: stable-diffusion-rest)\n"
-                      << "  --auth-data-dir <dir>          Directory for authentication data (default: ./auth)\n"
-                      << "  --public-paths <paths>         Comma-separated list of public paths (default: /api/health,/api/status)\n"
-                      << "  --jwt-audience <audience>      JWT audience claim (default: stable-diffusion-rest)\n"
-                      << "\n"
-                      << "Deprecated Options (will be removed in future version):\n"
-                      << "  --enable-unix-auth             Deprecated: Use --auth unix instead\n"
-                      << "  --enable-pam-auth              Deprecated: Use --auth pam instead\n"
-                      << "\n"
-                      << "Model Directory Options:\n"
-                      << "  All model directories are optional and default to standard folder names\n"
-                      << "  under --models-dir. Only specify these if your folder names differ.\n"
-                      << "\n"
-                      << "  --checkpoints <dir>            Checkpoints directory (default: checkpoints)\n"
-                      << "  --controlnet-dir <dir>         ControlNet models directory (default: controlnet)\n"
-                      << "  --embeddings-dir <dir>         Embeddings directory (default: embeddings)\n"
-                      << "  --esrgan-dir <dir>             ESRGAN models directory (default: ESRGAN)\n"
-                      << "  --lora-dir <dir>               LoRA models directory (default: loras)\n"
-                      << "  --taesd-dir <dir>              TAESD models directory (default: TAESD)\n"
-                      << "  --vae-dir <dir>                VAE models directory (default: vae)\n"
-                      << "  --diffusion-models-dir <dir>   Diffusion models directory (default: diffusion_models)\n"
-                      << "\n"
-                      << "Generation Limits & Security:\n"
-                      << "  --max-prompt-length <len>      Maximum prompt character length (default: 10000)\n"
-                      << "  --max-negative-prompt-length <len> Maximum negative prompt character length (default: 10000)\n"
-                      << "  --shutdown-delay <ms>           Graceful shutdown delay in milliseconds (default: 100)\n"
-                      << "\n"
-                      << "Default Admin Credentials:\n"
-                      << "  --default-admin-username <name> Default admin username (default: admin)\n"
-                      << "  --default-admin-password <pass> Default admin password (default: admin123)\n"
-                      << "  --default-admin-email <email>   Default admin email (default: admin@localhost)\n"
-                      << "\n"
-                      << "Other Options:\n"
-                      << "  --help, -h                     Show this help message\n"
-                      << "\n"
-                      << "Path Resolution:\n"
-                      << "  - Absolute paths are used as-is\n"
-                      << "  - Relative paths are resolved relative to --models-dir\n"
-                      << "  - Default folder names match standard SD model structure\n"
-                      << "\n"
-                      << "Examples:\n"
-                      << "  # Use all defaults (requires standard folder structure)\n"
-                      << "  " << argv[0] << " --models-dir /data/SD_MODELS\n"
-                      << "\n"
-                      << "  # Override specific folders\n"
-                      << "  " << argv[0] << " --models-dir /data/SD_MODELS --checkpoints my_checkpoints\n"
-                      << "\n"
-                      << "  # Use absolute path for one folder\n"
-                      << "  " << argv[0] << " --models-dir /data/SD_MODELS --lora-dir /other/path/loras\n"
-                      << std::endl;
+            LOG_INFO("stable-diffusion.cpp-rest server");
+            LOG_INFO("Usage: " + std::string(argv[0]) + " [options]");
+            LOG_INFO("");
+            LOG_INFO("Required Options:");
+            LOG_INFO("  --models-dir <dir>             Base models directory path (required)");
+            LOG_INFO("");
+            LOG_INFO("Server Options:");
+            LOG_INFO("  --host <host>                  Host address to bind to (default: 0.0.0.0)");
+            LOG_INFO("  --port <port>                  Port number to listen on (default: 8080)");
+            LOG_INFO("  --max-concurrent <num>         Maximum concurrent generations (default: 1)");
+            LOG_INFO("  --queue-dir <dir>              Queue persistence directory (default: ./queue)");
+            LOG_INFO("  --output-dir <dir>             Output files directory (default: ./output)");
+            LOG_INFO("  --ui-dir <dir>                 Web UI static files directory (optional)");
+            LOG_INFO("  --verbose, -v                  Enable verbose logging");
+            LOG_INFO("  --enable-file-logging          Enable logging to file");
+            LOG_INFO("  --log-file <path>              Log file path (default: /var/log/stable-diffusion-rest/server.log)");
+            LOG_INFO("");
+            LOG_INFO("Network & Connection Options:");
+            LOG_INFO("  --connection-timeout <ms>      Connection timeout in milliseconds (default: 500)");
+            LOG_INFO("  --read-timeout <ms>           Read timeout in milliseconds (default: 500)");
+            LOG_INFO("  --write-timeout <ms>          Write timeout in milliseconds (default: 500)");
+            LOG_INFO("");
+            LOG_INFO("Authentication Options:");
+            LOG_INFO("  --auth <method>                 Authentication method (none, jwt, api-key, unix, pam, optional)");
+            LOG_INFO("  --auth-method <method>          Authentication method (alias for --auth)");
+            LOG_INFO("  --jwt-secret <secret>           JWT secret key (auto-generated if not provided)");
+            LOG_INFO("  --jwt-expiration <minutes>      JWT token expiration time (default: 60)");
+            LOG_INFO("  --enable-guest-access          Allow unauthenticated guest access");
+            LOG_INFO("  --pam-service-name <name>      PAM service name (default: stable-diffusion-rest)");
+            LOG_INFO("  --auth-data-dir <dir>          Directory for authentication data (default: ./auth)");
+            LOG_INFO("  --public-paths <paths>         Comma-separated list of public paths (default: /api/health,/api/status)");
+            LOG_INFO("  --jwt-audience <audience>      JWT audience claim (default: stable-diffusion-rest)");
+            LOG_INFO("");
+            LOG_INFO("Deprecated Options (will be removed in future version):");
+            LOG_INFO("  --enable-unix-auth             Deprecated: Use --auth unix instead");
+            LOG_INFO("  --enable-pam-auth              Deprecated: Use --auth pam instead");
+            LOG_INFO("");
+            LOG_INFO("Model Directory Options:");
+            LOG_INFO("  All model directories are optional and default to standard folder names");
+            LOG_INFO("  under --models-dir. Only specify these if your folder names differ.");
+            LOG_INFO("");
+            LOG_INFO("  --checkpoints <dir>            Checkpoints directory (default: checkpoints)");
+            LOG_INFO("  --controlnet-dir <dir>         ControlNet models directory (default: controlnet)");
+            LOG_INFO("  --embeddings-dir <dir>         Embeddings directory (default: embeddings)");
+            LOG_INFO("  --esrgan-dir <dir>             ESRGAN models directory (default: ESRGAN)");
+            LOG_INFO("  --lora-dir <dir>               LoRA models directory (default: loras)");
+            LOG_INFO("  --taesd-dir <dir>              TAESD models directory (default: TAESD)");
+            LOG_INFO("  --vae-dir <dir>                VAE models directory (default: vae)");
+            LOG_INFO("  --diffusion-models-dir <dir>   Diffusion models directory (default: diffusion_models)");
+            LOG_INFO("");
+            LOG_INFO("Generation Limits & Security:");
+            LOG_INFO("  --max-prompt-length <len>      Maximum prompt character length (default: 10000)");
+            LOG_INFO("  --max-negative-prompt-length <len> Maximum negative prompt character length (default: 10000)");
+            LOG_INFO("  --shutdown-delay <ms>           Graceful shutdown delay in milliseconds (default: 100)");
+            LOG_INFO("");
+            LOG_INFO("Default Admin Credentials:");
+            LOG_INFO("  --default-admin-username <name> Default admin username (default: admin)");
+            LOG_INFO("  --default-admin-password <pass> Default admin password (default: admin123)");
+            LOG_INFO("  --default-admin-email <email>   Default admin email (default: admin@localhost)");
+            LOG_INFO("");
+            LOG_INFO("Other Options:");
+            LOG_INFO("  --help, -h                     Show this help message");
+            LOG_INFO("");
+            LOG_INFO("Path Resolution:");
+            LOG_INFO("  - Absolute paths are used as-is");
+            LOG_INFO("  - Relative paths are resolved relative to --models-dir");
+            LOG_INFO("  - Default folder names match standard SD model structure");
+            LOG_INFO("");
+            LOG_INFO("Examples:");
+            LOG_INFO("  # Use all defaults (requires standard folder structure)");
+            LOG_INFO("  " + std::string(argv[0]) + " --models-dir /data/SD_MODELS");
+            LOG_INFO("");
+            LOG_INFO("  # Override specific folders");
+            LOG_INFO("  " + std::string(argv[0]) + " --models-dir /data/SD_MODELS --checkpoints my_checkpoints");
+            LOG_INFO("");
+            LOG_INFO("  # Use absolute path for one folder");
+            LOG_INFO("  " + std::string(argv[0]) + " --models-dir /data/SD_MODELS --lora-dir /other/path/loras");
             exit(0);
         } else {
             LOG_ERROR("Unknown argument: " + arg);

+ 24 - 21
src/model_manager.cpp

@@ -1,6 +1,7 @@
 #include "model_manager.h"
 #include "model_detector.h"
 #include "stable_diffusion_wrapper.h"
+#include "logger.h"
 #include <iostream>
 #include <fstream>
 #include <algorithm>
@@ -486,7 +487,7 @@ public:
                                             }
                                             
                                             if (verbose) {
-                                                std::cout << "Using architecture-based detection for " << info.name << std::endl;
+                                                LOG_INFO("Using architecture-based detection for " + info.name);
                                             }
                                         }
 
@@ -1286,25 +1287,25 @@ std::string ModelManager::ModelPathSelector::selectPathType(
     const std::string& diffusionModelsDir,
     bool verbose) {
     
-    if (verbose) {
-        std::cout << "Selecting path type for model: " << modelPath << std::endl;
-        std::cout << "Checkpoints directory: " << checkpointsDir << std::endl;
-        std::cout << "Diffusion models directory: " << diffusionModelsDir << std::endl;
+if (verbose) {
+        LOG_INFO("Selecting path type for model: " + modelPath);
+        LOG_INFO("Checkpoints directory: " + checkpointsDir);
+        LOG_INFO("Diffusion models directory: " + diffusionModelsDir);
     }
     
     // Check if model is in diffusion_models directory first (priority)
     if (!diffusionModelsDir.empty() && isModelInDirectory(modelPath, diffusionModelsDir)) {
-        if (verbose) {
-            std::cout << "Model is in diffusion_models directory, using diffusion_model_path" << std::endl;
-        }
+if (verbose) {
+                LOG_INFO("Model is in diffusion_models directory, using diffusion_model_path");
+            }
         return "diffusion_model_path";
     }
     
     // Check if model is in checkpoints directory
     if (!checkpointsDir.empty() && isModelInDirectory(modelPath, checkpointsDir)) {
-        if (verbose) {
-            std::cout << "Model is in checkpoints directory, using model_path" << std::endl;
-        }
+if (verbose) {
+                LOG_INFO("Model is in checkpoints directory, using model_path");
+            }
         return "model_path";
     }
     
@@ -1313,21 +1314,21 @@ std::string ModelManager::ModelPathSelector::selectPathType(
     std::filesystem::path parentDir = modelFilePath.parent_path();
     
     if (parentDir.filename().string() == "diffusion_models") {
-        if (verbose) {
-            std::cout << "Model is in diffusion_models directory (detected from path), using diffusion_model_path" << std::endl;
-        }
+if (verbose) {
+                LOG_INFO("Model is in diffusion_models directory (detected from path), using diffusion_model_path");
+            }
         return "diffusion_model_path";
     } else if (parentDir.filename().string() == "checkpoints") {
-        if (verbose) {
-            std::cout << "Model is in checkpoints directory (detected from path), using model_path" << std::endl;
-        }
+if (verbose) {
+                LOG_INFO("Model is in checkpoints directory (detected from path), using model_path");
+            }
         return "model_path";
     }
     
     // Default fallback for unknown locations
-    if (verbose) {
-        std::cout << "Model location unknown, defaulting to model_path for backward compatibility" << std::endl;
-    }
+if (verbose) {
+            LOG_INFO("Model location unknown, defaulting to model_path for backward compatibility");
+        }
     return "model_path";
 }
 
@@ -1606,7 +1607,9 @@ std::vector<ModelManager::ModelDetails> ModelManager::checkRequiredModelsExisten
                 }
                 
                 if (pImpl->verbose) {
-                    std::cout << "Found required model: " << modelType << " at " << details.path << std::endl;
+                    std::ostringstream info_oss;
+                    info_oss << "Found required model: " << modelType << " at " << details.path;
+                    LOG_INFO(info_oss.str());
                 }
             } else {
                 if (pImpl->verbose) {

+ 17 - 9
src/server.cpp

@@ -157,7 +157,7 @@ void Server::registerEndpoints() {
 
     // Health check endpoint (public)
     m_httpServer->Get("/api/health", [this](const httplib::Request& req, httplib::Response& res) {
-        std::cout << "DEBUG: Health endpoint lambda called" << std::endl;
+        LOG_DEBUG("Health endpoint lambda called");
         handleHealthCheck(req, res);
     });
 
@@ -949,7 +949,7 @@ void Server::setupCORS() {
 }
 
 void Server::handleHealthCheck(const httplib::Request& req, httplib::Response& res) {
-    std::cout << "DEBUG: handleHealthCheck called" << std::endl;
+    LOG_DEBUG("handleHealthCheck called");
     try {
         nlohmann::json response = {
             {"status", "healthy"},
@@ -958,9 +958,9 @@ void Server::handleHealthCheck(const httplib::Request& req, httplib::Response& r
             {"version", sd_rest::VERSION_INFO.version_full}
         };
         sendJsonResponse(res, response);
-        std::cout << "DEBUG: About to call logHttpAccess" << std::endl;
+        LOG_DEBUG("About to call logHttpAccess");
         logHttpAccess(req, res, "health-check");
-        std::cout << "DEBUG: logHttpAccess returned" << std::endl;
+        LOG_DEBUG("logHttpAccess returned");
     } catch (const std::exception& e) {
         sendErrorResponse(res, std::string("Health check failed: ") + e.what(), 500);
         logHttpAccess(req, res, "health-check-error");
@@ -1479,7 +1479,7 @@ void Server::handleJobStatus(const httplib::Request& req, httplib::Response& res
 
         // Create download URLs for output files
         nlohmann::json outputUrls = nlohmann::json::array();
-        std::cout << "[DEBUG] Job " << jobInfo.id << " has " << jobInfo.outputFiles.size() << " output files" << std::endl;
+        LOG_DEBUG("Job " + jobInfo.id + " has " + std::to_string(jobInfo.outputFiles.size()) + " output files");
         for (const auto& filePath : jobInfo.outputFiles) {
             // Extract filename from full path
             std::filesystem::path p(filePath);
@@ -1494,7 +1494,11 @@ void Server::handleJobStatus(const httplib::Request& req, httplib::Response& res
                 {"path", filePath}
             };
             outputUrls.push_back(fileInfo);
-            std::cout << "[DEBUG] Added output file: " << filename << " -> " << url << std::endl;
+            {
+                std::ostringstream oss;
+                oss << "Added output file: " << filename << " -> " << url;
+                LOG_DEBUG(oss.str());
+            }
         }
 
         nlohmann::json response = {
@@ -1856,7 +1860,7 @@ void Server::handleJobOutputFile(const httplib::Request& req, httplib::Response&
     std::string requestId = generateRequestId();
     
     // DEBUG: Print immediately at function start
-    std::cout << "DEBUG: handleJobOutputFile called!" << std::endl;
+    LOG_DEBUG("handleJobOutputFile called!");
     
     try {
         // Extract job ID and filename from URL path
@@ -1911,7 +1915,7 @@ void Server::handleJobOutputFile(const httplib::Request& req, httplib::Response&
         
         // Get job information to check if it exists and is completed
         if (!m_generationQueue) {
-            std::cout << "DEBUG: m_generationQueue is null!" << std::endl;
+            LOG_DEBUG("m_generationQueue is null!");
             sendErrorResponse(res, "Generation queue not available", 500, "QUEUE_UNAVAILABLE", requestId);
             return;
         }
@@ -5656,7 +5660,11 @@ std::string Server::generateThumbnail(const std::string& imagePath, int size) {
 
 void Server::logHttpAccess(const httplib::Request& req, httplib::Response& res, const std::string& endpoint) {
     // Debug: Always print to see if function is called
-    std::cout << "DEBUG: logHttpAccess called for " << req.method << " " << req.path << std::endl;
+    {
+        std::ostringstream oss;
+        oss << "logHttpAccess called for " << req.method << " " << req.path;
+        LOG_DEBUG(oss.str());
+    }
     
     std::string clientIP = req.get_header_value("X-Forwarded-For");
     if (clientIP.empty()) {