Search code examples
javagradlespring-bootlog4jprofiles

How to configure gradle to use different log4j.properties files in different environments?


I have 3 profiles local, dev, prod profiles and 3 different log4j.properties files. How to configure gradle to use different properties files? I need something similar to this How to configure maven to use different log4j.properties files in different environments


Solution

  • I would recommend you read the section on Logging within the Spring boot reference. You really shouldn't be building an application that is environment specific. You should be using the same artifact and specifying environment variables to specify unique characteristics for that environment (The Twelve-Factor App - Build, Release, Run). In this case you would create one application and then in the situations when you are using local, dev, or prod you could specify an environment variable for the logging.config that points at the different log4j.properties file similar to how you specify the spring.profiles.active property.

    There is even a special section in the reference for Logback to do the logging differently per profile. I know your original question said the log4j.properties but maybe this need warrents a look at logback. Under the section for Profile-Specific Configuration it shows that you can customise the logging.config file with sections for the different profiles. The example:

    <springProfile name="staging">
        <!-- configuration to be enabled when the "staging" profile is active -->
    </springProfile>
    
    <springProfile name="dev, staging">
        <!-- configuration to be enabled when the "dev" or "staging" profiles are active -->
    </springProfile>
    
    <springProfile name="!production">
        <!-- configuration to be enabled when the "production" profile is not active -->
    </springProfile>