Loading...

Debug Environment Variables and System Properties in Java

:heavy_exclamation_mark: This post is older than a year. Consider some information might not be accurate anymore. :heavy_exclamation_mark:

Having problems it comes to debugging of the environment variables and system properties. This snippet prints all known environment variables and system properties in alphabetical order. Makes it easier to compare :wink:.

private String readSystemEnvironment() {
    StringBuilder sb = new StringBuilder();
    String logFormat = "%s=%s\n";
    sb.append("==================\n");
    sb.append("Environment variables:\n");
    sb.append("======================\n");
    Map<String, String> map = System.getenv();
    SortedSet<String> keys = new TreeSet<>(map.keySet());
    for (String key : keys) {
        sb.append(String.format(logFormat, key, map.get(key)));
    }
    sb.append("==================\n");
    sb.append("System properties:\n");
    sb.append("==================\n");
    // Get all system properties
    Properties props = System.getProperties();
    SortedSet<String> propNames = new TreeSet<>(props.stringPropertyNames());
    for (String propName : propNames) {
        // Get property value
        String propValue = (String) props.get(propName);
        sb.append(String.format(logFormat, propName, propValue));
    }
    return sb.toString();
}