DEV Community

Query Filter
Query Filter

Posted on

bridge-9

import java.util.logging.LogManager;
import java.io.File;
import java.util.Enumeration;

public static String resolveLogDirViaLogger() {
    try {
        LogManager manager = LogManager.getLogManager();
        Enumeration<String> propertyNames = manager.getPropertyNames();

        while (propertyNames.hasMoreElements()) {
            String key = propertyNames.nextElement();

            // Look for any logging handler pattern property (e.g., java.util.logging.FileHandler.pattern)
            if (key.endsWith(".pattern")) {
                String patternValue = manager.getProperty(key);

                if (patternValue != null && !patternValue.trim().isEmpty()) {
                    String cleanPattern = patternValue.trim();

                    // Replace standard JUL standard generation tokens if they exist in the path string
                    cleanPattern = cleanPattern.replace("%h", System.getProperty("user.home"))
                                               .replace("%t", System.getProperty("java.io.tmpdir"));

                    File logFilePattern = new File(cleanPattern);
                    File logDir = logFilePattern.getParentFile();

                    if (logDir != null) {
                        // Create the directory if it doesn't exist yet
                        if (!logDir.exists()) {
                            logDir.mkdirs();
                        }
                        System.out.println("[PROFILER-AGENT] Dynamically caught target log directory: " + logDir.getAbsolutePath());
                        return logDir.getAbsolutePath();
                    }
                }
            }
        }
    } catch (Exception e) {
        System.err.println("[PROFILER-AGENT] Warning: Exception while inspecting LogManager properties: " + e.getMessage());
    }

    // Hard fallback if something prevents reading the property keys
    System.out.println("[PROFILER-AGENT] Falling back to standard local execution workspace context: ./logs");
    return "./logs";
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)