Dragomirus
Dragomirus

Reputation: 449

Log4j reading configuration from string

is it possible to read log4j configuration from string instead of URI? Or how to convert String to URI. I've someting like this:

String robotId = "robot23";
FileHandle file = new FileHandle(new File("./log4j2.xml"));
String fileAsString = file.readString(); //LibGDX method
fileAsString = fileAsString.replace("log.log", robotId + "-log.log");

And now how can I convert fileAsString to configuration for log4j like this

LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
ctx.setConfigLocation(configUri);

Note that fileAsString contains xml configuration. Thanks for any help :)

Upvotes: 1

Views: 249

Answers (1)

Anton Balaniuc
Anton Balaniuc

Reputation: 11739

Are you trying to change some of the log4j2 properties dynamically? You don't need to do it programmatically. You can use Property Substitution:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn" name="MyApp" packages="">
  <Appenders>
    <File name="MyFile" fileName="logs/${sys:robotId}-log.log">
      <PatternLayout>
        <Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
      </PatternLayout>
    </File>
  </Appenders>
  <Loggers>
    <Root level="error">
      <AppenderRef ref="MyFile"/>
    </Root>
  </Loggers>
</Configuration>

Where ${sys:robotId} is a system property, which you can set.

Upvotes: 1

Related Questions