0

I'd like to set dynamically the fileName where the FileAppender will write. I'll provide an example of my configuration.

log4j2.yml

...

  Appenders:

    Console:

      name: Console_Appender

      target: SYSTEM_OUT

      PatternLayout:

        pattern: "[%-5level] %d{dd-MM-yyyy HH:mm:ss.SSS} [%t] %c{1} - %msg%n"

    File:

      name: File_Appender

      fileName: ${log-path}/fileLog.log


      PatternLayout:

        pattern: "[%-5level] %d{dd-MM-yyyy HH:mm:ss.SSS} [%t] %c{1} - %msg%n"
...

I'd like fileLog${javaVariable}.log where javaVariable is dynamic. Is this possible?

Thank you :)

EDIT: To be clear I need that if the method that I intercept with @Around annotation is called by the user0 I have to write the (single) log in "user0.log"; if is called by user1 -> "user1.log". I can create users at any time so I need a dynamic filename.

  • I think it might help were you to be more specific about 'dynamic'. You mean as in "decided as a parameter to the app to be run" or "set inside the code at runtime"… – g00se Jul 06 '21 at 12:42
  • [Using system environment variables in log4j xml configuration](https://stackoverflow.com/questions/201188/using-system-environment-variables-in-log4j-xml-configuration) – Lei Yang Jul 06 '21 at 13:01
  • @g00se Dynamic = set inside the code at runtime – Daniele Lupo Jul 06 '21 at 14:35
  • @LeiYang I need to use yml :( However, I have already used _${sys:logFile}_ and in java _System.setProperty("logFile", "theFileName")_ but doesn't work. Are you sure that works with yml? – Daniele Lupo Jul 06 '21 at 14:35
  • i think yaml is same. how about `${logFile}` in yaml, and `java -DlogFile=xyz`? – Lei Yang Jul 06 '21 at 14:44
  • @LeiYang I need to set the variable runtime not boottime :( – Daniele Lupo Jul 06 '21 at 14:48
  • i think you need code, not config. [Configuring Log4j Loggers Programmatically](https://stackoverflow.com/questions/8965946/configuring-log4j-loggers-programmatically) – Lei Yang Jul 06 '21 at 14:53
  • In that case you can look at the api and [examples](https://howtodoinjava.com/log4j/how-to-programmatically-configure-appenders-in-log4j/) – g00se Jul 06 '21 at 15:39
  • @g00se Ok. Logger.getRootLogger() is undefined. Log4j2 is not log4j – Daniele Lupo Jul 06 '21 at 16:37
  • I was going to say, but forgot sorry, that the code there is old. It's now `LogManager` that gets `Logger`s – g00se Jul 06 '21 at 17:42
  • @g00se there are a lot of setter that doesn't exists... However, if I can create a file appender and etc, how can I say "write this with this logger"? The method FileAppender.append needs LogEvent and I don't know how to create it... I have edited the answer so now it's more specific. Can you read again, please? – Daniele Lupo Jul 06 '21 at 19:45

1 Answers1

0

The solution is MDC. I've used this guide where you can use Routing to select the file according to a variable in the Thread context.