Cannot enable spring debug logging using log4j

2019-08-09 11:06发布

问题:

This is my log4j.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"  debug="true">
<appender name="FILE" class="org.apache.log4j.DailyRollingFileAppender">
    <param name="File" value="${catalina.base}/logs/server.log" />
    <param name="Append" value="true" />
    <param name="Threshold" value="INFO" />
    <param name="DatePattern" value="'.'yyyy-MM-dd" />
    <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" value="%d{ABSOLUTE}#%X{requestId}#%X{uid}#%X{agentId}#%X{agentName} %-5p [%c{1}] - %m%n" />
    </layout>
</appender>
<logger name="org.springframework" level="DEBUG">
    <appender-ref ref="FILE"/>
</logger>

I am making a JSON request to a controller and getting 400 Bad request request is syntactically incorrect. I want to get some more info on this. I read about enabling spring debugging and followed instructions but it doesn't work. I have checked my request and it seems completely fine. How can I see more information about this in server.log file? Why does the above configuration not work? PS: I have removed the other loggers and appenders for clarity

回答1:

This fixed it

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">
<!-- Rolling file Appender -->
<appender name="FILE" class="org.apache.log4j.DailyRollingFileAppender">
    <param name="File" value="${catalina.base}/logs/server.log" />
    <param name="Append" value="true" />
    <!-- changed to DEBUG-->
    <param name="Threshold" value="DEBUG" />
    <param name="DatePattern" value="'.'yyyy-MM-dd" />
    <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" value="%d{ABSOLUTE}#%X{requestId}#%X{uid}#%X{agentId}#%X{agentName} %-5p [%c{1}] - %m%n" />
    </layout>
</appender>
<!-- added this-->
<category name="org.springframework.beans">
    <priority value="debug" />
</category>



回答2:

Here is the dependencies:

compile group: 'org.apache.logging.log4j', name: 'log4j-core', version: '2.1'
compile group: 'org.apache.logging.log4j', name: 'log4j-api', version: '2.1'

Here is the log4j2 configuration:

Bellow configuration is for windows machine. You can change only the log path for linux.

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn" strict="true">
    <Properties>
        <Property name="filename">D:/CommonLogFile/YOUR_LOG_FILE_NAME.log
        </Property>
        <Property name="backupFilePattern">
            D:/CommonLogFile/PROJECT_NAME-%d{yyyy-MM-dd HH_mm}-%i.log
        </Property>
        <Property name="logPatternConsole">
            %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %highlight{%-5level} %logger{35} - %msg%n{INFO=cyan, ERROR=red}
        </Property>
        <Property name="logPatternFile">
            %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{35} - %msg%n
        </Property>
    </Properties>

    <Appenders>
        <Console name="STDOUT" target="SYSTEM_OUT">
            <PatternLayout pattern="${logPatternConsole}"/>
        </Console>

        <RollingFile name="MyRollingFile" fileName="${filename}" filePattern="${backupFilePattern}">
            <PatternLayout pattern="${logPatternFile}"/>
            <Policies>
                <SizeBasedTriggeringPolicy size="10 MB"/>
            </Policies>
            <DefaultRolloverStrategy max="10"/>
        </RollingFile>

    </Appenders>
    <Loggers>
        <Logger name="com.dmoney" level="trace" additivity="false">
            <AppenderRef ref="STDOUT"/>
            <AppenderRef ref="MyRollingFile"/>
        </Logger>
        <Root level="trace">
            <AppenderRef ref="STDOUT"/>
        </Root>
    </Loggers>
</Configuration>

Here contains some keyNote:

<Property name="filename">D:/CommonLogFile/YOUR_LOG_NAME.log
        </Property>

Here, filename is the name of the log file.

<Property name="logPatternConsole">
            %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %highlight{%-5level} %logger{35} - %msg%n{INFO=cyan, ERROR=red}
        </Property>

Here, logPatternConsole has the time pattern.

In Appender section, it has

<Policies>
                <SizeBasedTriggeringPolicy size="10 MB"/>
            </Policies>

here SizeBasedTriggeringPolicy defins when new log file will created. Here, after 10MB it will create new logFile

Here is the log implementation:

static LogWriterUtility logWriterUtility = new LogWriterUtility(YOUR_CLASS_NAME.class);
logWriterUtility.trace(UUID.randomUUID().toString(),"Here is the log message");

Check bellow for LogWriterUtility class:

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class LogWriterUtility {

    Logger log;

    public LogWriterUtility(Class<?> clazz) {
        log = LogManager.getLogger(clazz);
    }

    public void trace(String requestId, String message) {
        log.trace("REQUESTID:" + requestId + ":" + message);
    }

    public void debug(String requestId, String message) {
        log.debug("REQUESTID:" + requestId + ":" + message);
    }

    public void error(String requestId, String message) {
        log.error("REQUESTID:" + requestId + ":" + message);
    }

    public void error(String requestId, Throwable t) {
        log.error("REQUESTID:" + requestId + ":");
        log.error(t);
    }

    public void info(String requestId, String message) {
        log.info("REQUESTID:" + requestId + ":" + message);
    }

    public void error(String requestId, Exception exception) {
        log.warn("REQUESTID:" + requestId + ":" + exception.getStackTrace());
    }
    public void errorWithAnalysis(String requestId, Exception exception) {

        if(exception==null)
            return;
        String message="No Message on error";
        StackTraceElement[] stackTrace = exception.getStackTrace();
        if(stackTrace!=null && stackTrace.length>0) {
            message="";
            for (StackTraceElement e : stackTrace) {
                message += "\n" + e.toString();
            }
        }
        log.error("REQUESTID:" + requestId + ":" +message);


    }
    public void warn(String requestId, String message) {
        log.error(requestId,message);
    }

    public boolean isTraceEnabled() {
        return log.isTraceEnabled();
    }

}

Thanks :)