2

I need to store log files in C:\.DS\logs in windows and in /.DS/logs in Linux.

I found the way to do that: I need to use System.setProperty("logs.dir", ...) and use ${logs.dir} in log4j config file.

Yet, the problem is, log4j is already initialized at this point and it doesn't pick up my system property.

Is there a more straightforward way to do this, whithout me needing to manually re-init log4j?

Thanks

SMSk
  • 693
  • 8
  • 25

1 Answers1

2

Use property lookups in log4j2.xml configuration

Available system properties https://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html

<Properties> //defined in log4j2 config
<Property name="LS">${sys:file.separator}</Property>
<Property name="LOG_DIR">partial_path${LS}partial_path${LS}</Property>
</Properties>

https://logging.apache.org/log4j/2.x/manual/configuration.html#PropertySubstitution

then in path to file

<RollingFile name="FILE_LOG" fileName="${LOG_DIR}file.log"
alan7678
  • 2,223
  • 17
  • 29
  • That would be incredibly helpful if there was an "if" statement in log4j configs, so I could check ${sys:os.name}.toLower().contains("win") and set my root path to "C:\" or "/". Is there? :) – SMSk Jul 06 '15 at 23:50
  • Sorry i thought the issue was just the line separator. You could create a default property /. If you run your program on windows pass in a parameter on the command line -DrootPath="C:\" it will override the default value if you lookup the value with ${sys:rootPath}. It doesn't avoid the command line argument unfortunately though. – alan7678 Jul 07 '15 at 14:54
  • http://stackoverflow.com/questions/24140359/xml-conditional-code-in-log4j2-xml according to this post there isn't support for logic in the config :/ – alan7678 Jul 07 '15 at 14:57
  • In the end I've decided to store logs in ${user.home}\.DS\logs. I've accepted your answer, but you should probably edit "path.separator" to "file.separator" -- path.separator is ";" on Windows and ":" on Linux – SMSk Jul 08 '15 at 10:39
  • Questions like this will be better if they asked with examples like "C:\foo\bar", "/var/bar/foo". – raxetul Dec 01 '19 at 08:01