-
Notifications
You must be signed in to change notification settings - Fork 18
Dynamic configuration
Tomasz Kowalczewski edited this page Jul 15, 2021
·
1 revision
This page contains example of configuring Log4j2 (including Tjahzi) in a dynamic way. E.g. you might want to enable some part of configuration based on environment property.
This mode of configuration if described in log4j docs. Below follows excerpt from this test.
Click to expand
ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();
builder.setConfigurationName("loki-programmatically");
builder.setStatusLevel(Level.ALL);
builder.setPackages("pl.tkowalcz.tjahzi.log4j2");
builder.add(
builder.newRootLogger(Level.ALL)
.add(builder.newAppenderRef("Loki"))
);
AppenderComponentBuilder lokiAppenderBuilder = builder.newAppender("Loki", "Loki")
.addAttribute("host", "${sys:loki.host}")
.addAttribute("port", "${sys:loki.port}")
.add(
builder
.newFilter("ThresholdFilter", Filter.Result.ACCEPT, Filter.Result.DENY)
.addAttribute("level", "ALL")
)
.add(
builder
.newLayout("PatternLayout")
.addAttribute("pattern", "%X{tid} [%t] %d{MM-dd HH:mm:ss.SSS} %5p %c{1} - %m%n%exception{full}")
)
.addComponent(
builder.newComponent("Header")
.addAttribute("name", "server")
.addAttribute("value", "127.0.0.1")
)
.addComponent(
builder.newComponent("Label")
.addAttribute("name", "server")
.addAttribute("value", "127.0.0.1")
);
builder.add(lokiAppenderBuilder);
Configurator.reconfigure(builder.build());
You can also verify resulting configuration using builder.writeXmlConfiguration(...);
The RoutingAppender evaluates LogEvents and then routes them to a subordinate Appender.
Example (courtesy of https://github.com/tkowalcz/tjahzi/issues/64#issuecomment-880207646):
<Routing name="ROUTER">
<Routes pattern="$${env:LOG_TO:-CONSOLE}">
<Route ref="LOKI" key="LOKI" />
<Route ref="CONSOLE" key="CONSOLE" />
</Routes>
</Routing>