'How to Config Log4J2 in a Java Web Application - TomCat

Actually i'm Working in a Java Web Application Created in 2006 (Really old) but it was actualized.

I'm trying to update the Log4J - 1.2.15 to Log4J2 - 2.17.2 This project implements log4j in a basic way, so for this (I think) it wasn't hard. I just changed the library and replaced the imports and that solved all the problems just with a little changes in the main Log class. The main Log class is named "LogUtil"

package ibope.rhProducao.resources;

import java.io.InputStream;
import java.util.Properties;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.config.Configuration;
//Antiguos imports para LOG4J 
//import org.apache.log4j.Level;
//import org.apache.log4j.Logger;
//import org.apache.log4j.PropertyConfigurator;



/** 
* Classe para setar as propriedades do Log4J
* através do arquivo log4j.properties
*
*  @author Ederaildo Fontes
*  @version 1.0 
*/ 
public class LogUtil
{
    public static Logger LOGGER;
    
    public Logger getLogger(Class classe){
            
            
            //Properties log4jProp = load("log4j.properties");
            //PropertyConfigurator.configure(log4jProp);
            
            LOGGER = LogManager.getLogger(classe);
            setLogLevel(Level.DEBUG);
            //LOGGER.atLevel(Level.OFF);
            
/*      JDBCAppender app = (JDBCAppender) logger.getParent().getAppender("JDBC2");
        logger.addAppender(app);
*/
            return LOGGER;
    }
    
        public static void setLogLevel(Level l) 
        {
            LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
            Configuration conf = ctx.getConfiguration();
            conf.getLoggerConfig(LogManager.ROOT_LOGGER_NAME).setLevel(l);
            ctx.updateLoggers(conf);
        }
        
    /**
     * Método auxiliar que carrega o arquivo de propriedades
     * @param nomeArquivo
     * @return objeto Properties 
     */
      public Properties load(String nomeArquivo){
        Properties prop = new Properties();
    
        String propertiesPath = "";
        propertiesPath = nomeArquivo;
        boolean gotProps = false;
        try {
            InputStream stream = (getClass()).getResourceAsStream(propertiesPath);
            if (stream != null) {
                prop.load(stream);
            } else {
                System.out.println("arquivo properties nao encontrado");
            }
        } catch (java.io.IOException ioe) {
            System.out.println("erro carregando properties " + propertiesPath);
        }
        
        return prop;
      }
    
}

As you can see the class is not clean, but it works! Well... the main problem is that Log4J2 is not recognizing the Log4J2.xml ubicated in WEB-INF and i say this because in the console is working.

Code ViewConsole View

Reading the Log4J2 documentation i found that Log4J search in WEB-INF for files named "log4j2-x.xml" and the first that is find is used.

WEB-INF View

I've been trying so much ways of configuration and moving the files but nothing works. I'm just trying to create a file.log

log4j2-RhProducao.xml

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn" name="MyApp" packages="">
    <Appenders>
        <RollingFile name="rollingFile"
            fileName="log/application.log" filePattern="log/application-%d{yyyy-MM-dd-HH-mm}-%i.log">
            <PatternLayout>
                <Pattern>%d{yyyy-MM-dd-HH:mm:ss} %-5p %m%n</Pattern>
            </PatternLayout>
            <Policies>
                <SizeBasedTriggeringPolicy size="1KB" />
            </Policies>
        </RollingFile>
    </Appenders>
    <Loggers>
        <Root level="trace">
            <AppenderRef ref="rollingFile" />
        </Root>
    </Loggers>
</Configuration>

log4j2.json

{
    "configuration":
            {
                "appenders": {
                    "RandomAccessFile": {
                        "name": "FILE",
                        "fileName": "app.log",
                        "PatternLayout": {
                            "pattern": "%d %p %c{1.} [%t] %m%n"
                        }
                    },
                    "Console": {
                        "name": "STDOUT",
                        "PatternLayout": {
                            "pattern": "%highlight{[%-5level] - [%t] - .%c{1}: %msg%n}"
                        }
                    }
                },
                "loggers": {
                    "root": {
                        "level": "all",
                        "AppenderRef": [
                            {
                                "ref": "FILE"
                            }
                        ]
                    }
                }
            }
}

These are the libraries Libraries implemented Well... the "log4j-web" just was a desesperated try to solve it... I don't know if affects in something.

This is the package where is the "LogUtil.java" file. enter image description here

As you can see even here i have other tries of files recognition. I know that for many reaons the project is not clean but are just the multiple-tries for solve this.

Even i added this in the web.xml

Web.xml View

This project doesn't use Maven.

Jdk: 11 Servlet 3.1 Tomcat 8.5.73

I really need help :( Excuses for my english*

I tried all the things that i was finding in Internet.



Solution 1:[1]

In netbeans, you can modify the TomCat propertiesHere

And there we can find the "Platform" section. In the VM Options we can write -Dlog4j2.debug=true

for see the Log4J -> Log! and find our error.

Finally... With this code we can add system properties defining the (xml, json or yalm file)

String path = Thread.currentThread().getContextClassLoader().getResource("/").toURI().resolve("../log4j2.json").getPath();
URL mFile = new File(path).toURI().toURL();
System.setProperty("log4j2.configurationFile", mFile.getPath());

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Brayan Estiven CaƱon Moreno