java - Better way to initialize log4j2 (TWO) programmatically -
this i'm doing load log4j2.xml file, specifying log file location property file keep configuration simple support purposes:
myproperties props = myproperties.getinstance(); system.setproperty(myconstants.audit_log_env_var, props.getauditlogfilename()); configurationsource source = new configurationsource(new fileinputstream(new file( system.getproperty(myconstants.properties_file_env_var) + "/log4j2.xml"))); configurator.initialize(null, source);
and log4j2 pick , use file name because i've specified in appender using envvar substitution:
<file name="auditlogger" filename="${sys:audit_log}"> <patternlayout pattern="datetime %d{yyyy-mm-dd hh:mm:ss:sss zzz}%n%msg%n" /> </file>
however don't because there's smell pushing file name value out system environment before reading in again on next line of code.
i configure log4j2 programmatically using configurationfactory there doesn't seem similar way build more on top of log4j2.xml file - or there?
generally log4j2 team not recommend programmatic configuration: separation between api , core jars give developers clear separation between api , implementation. programmatic configuration relies on implementation details may break in future release.
if there's cannot done configuration please let know can improve this.
for particular use case: looks want set system property value before log4j2 initializes based on value. if standalone app, 1 way avoid depending on log4j2 implementation details set necessary system properties before referencing log4j2 classes:
public class mainwrapper { public static void main(string[] args) { system.setproperty("key", "value"); // ... actualmain.main(args); // delegate actual start of application } }
an alternative draw attention creating own custom lookup. can accomplished in few lines of code log4j2 plugin. relies on implementation details, result more powerful , reusable.
package com.mycompany; import org.apache.logging.log4j.core.logevent; import org.apache.logging.log4j.core.config.plugins.plugin; import org.apache.logging.log4j.core.lookup.abstractlookup; import org.apache.logging.log4j.core.lookup.strlookup; /** looks keys in myproperties singleton. */ @plugin(name = "myproperties", category = strlookup.category) public class mypropertieslookup extends abstractlookup { @override public string lookup(final logevent event, final string key) { return myproperties.getinstance().getvalue(key); } }
then, in configuration can use custom lookup instead of system properties:
<file name="auditlogger" filename="${myproperties:audit_log}"> <patternlayout pattern="datetime %d{yyyy-mm-dd hh:mm:ss:sss zzz}%n%msg%n" /> </file>
Comments
Post a Comment