Hi, On Fri, Aug 10, 2018 at 10:48 AM Rajvinder Pal <rajvinder....@gmail.com> wrote: > > Hi, > > I have a query regarding log4j2 initialization from external location. Why > cannot i initialize log4j2 by specifying System Property in Application > server as > > log4j.configurationFile : file:///d:/log4j2.xml > > and get Logger in Java files. > > Why do i need log4j-web-2.9.1.jar? what extra functionality does this jar > provide? I Just want to understand if first way is sufficient for a web > application. >
as far as I am concerned, there is absolutely no reason, why you shouldn't simply use log4j2-core, and log4j2-api in a web application, like you should do in any other application. There are a few things to consider, though: - Assuming, that you want your log4j configuration per web app: Make sure, that the log4j files are in WEB-INF/lib. Do *not* use the containers libraries, if there are any. And, do *not* add the log4j jars to the containers class path, for example by putting them into <TOMCAT_HOME>/lib, or whatever. - You should use a ServletContextInitializer to add log4j. This could look roughly like the following: private LoggerContext loggerContext; public void contextInitialized(ServletContext pContext) { final String log4jXmlPath = System.getProperty("log4j.configurationFile"); final File log4jXmlFile = new File(log4jXmlPath); try (InputStream in = new FileInputStream(log4jXmlFile)) { ConfigurationSource cs = new ConfigurationSource(in, log4jXmlFile); loggerContext = Configurator.initialize(cs, Thread.currentThread.getContextClassLoader()); } } public void contextDestroyed(ServletContext pContext) { loggerContext.close(); } - It is another matter, how to access the loggerContext to create loggers. In particular, something like this won't work: private static final Logger log = LogManager.getLogger(MyClass); because this cannot access the loggerContext. (That is, perhaps, something that log4j-web does for you. So, this still might be your best option.) My typical approach to work around that problem would be to have loggers injected by Guice, or Spring, and make sure that the respective framework uses the loggerContext when creating those loggers. Jochen --------------------------------------------------------------------- To unsubscribe, e-mail: log4j-user-unsubscr...@logging.apache.org For additional commands, e-mail: log4j-user-h...@logging.apache.org