5

I want to have different log4j2 log directories based on the current active profile. But it does not work.

#application.properties:
spring.profiles.active=dev
log.path=d:/${spring.profiles.active}

#log4j2.xml:
<Properties>
  <property name="path">${bundle:application:log.path}</property>
</Properties>

Result: a folder is created on d:/ called ${spring.profiles.active} instead of resolving to the real spring profile name. Why?

1

3 Answers 3

3

I solved it as follows: log4j2.xml: ${main:spring.profiles.active}

MainMapLookup.setMainArguments(new String[] {"spring.profiles.active", "dev"});
SpringApplication.run(source, args);

You can get the vmargs as follows, and set the profile dynamically before running the spring app: ManagementFactory.getRuntimeMXBean().getInputArguments()


Or even better, coming back to this after years: use ${sys:spring.profiles.active}, as any arguments given with -D count as SystemProperties. You don't need the MainMapLookup in this case.


As an alternative: just logging to the classpath logs dir, and setting a soft link inside the execution directory, eg ln -s /var/log logs to redirect the log directory by the running system.

1

Result: a folder is created on d:/ called ${spring.profiles.active} instead of resolving to the real spring profile name. Why?

There's no relation between log4j2 and Spring. The placeholder you have in your application.properties is for Spring to parse and replace. Log4j2 is not aware of it.

2
  • Hm, so is there any other chance I could derive my loging path by spring profile property? Feb 27, 2015 at 15:50
  • @membersound There might be some integration possible, but none that I am aware of. Feb 27, 2015 at 15:50
1

You can use logging.config to set log4j2 path in application.yaml, like

---
spring:
   profiles: test
logging.config: classpath:log4j2.test.yaml
---
spring:
   profiles: online
logging.config: classpath:log4j2.online.yaml

with log4j2.test.yaml and log4j.online.yaml, you can set different log4j2 config in different env.

1
  • This doesn't works . If I specify logging.config=classpath:log4j2.xml in application.properties and logging.config=classpath:log4j2-local.xml in application-local.properties and I start app with -Dspring.profiles.active:local . It still looks for log4j2.xml instead of log4j2-local.xml .
    – Satyendra
    Apr 1, 2021 at 14:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.