The environment is the same as in the article I wrote earlier. Prepare the execution environment of Tomcat in IntelliJ Community
To summarize it roughly, it looks like the following.
type | software |
---|---|
language | Java SE 8 |
Server API | JavaEE |
Log API | Log4j2 |
IDE | IntelliJ Community |
Build tool | Gradle |
container | Tomcat |
If it is a JavaEE project, it may have already been created, but create a directory as follows.
Also, create directories "classes" and "lib" in WEB-INF.
Add the following to the dependencies of build.gradle.
dependencies {
//Make log4j available
compile group: 'org.apache.logging.log4j', name: 'log4j-api', version: '2.11.1'
compile group: 'org.apache.logging.log4j', name: 'log4j-core', version: '2.11.1'
compile group: 'org.apache.logging.log4j', name: 'log4j-web', version: '2.11.1'
}
When writing Log, it is troublesome to write the preparation code every time, so create a wrap class as follows. For the code, I referred to the link below. Small diameter of Spring MVC, a little detour, small diameter of logging
import org.apache.logging.log4j.LogManager;
import java.io.File;
/**
*Perform logging process
*/
public class Log4j {
private static Log4j logger = null;
private Log4j() {
}
public static synchronized Log4j getInstance() {
if (logger == null) {
logger = new Log4j();
}
return logger;
}
private String getMessage(final String msg) {
String thisClassName = this.getClass().getName();
//Get class name
String SuperClassName = Logger.class.getName();
Thread t = Thread.currentThread();
StackTraceElement[] stackTraceElements = t.getStackTrace();
int pos = 0;
for (StackTraceElement stackTraceElement : stackTraceElements) {
String steClassName = stackTraceElement.getClassName();
if (thisClassName.equals(steClassName) || SuperClassName.equals(steClassName)){
break;
}
pos++;
}
pos += 2;
StackTraceElement m = stackTraceElements[pos];
return m.getClassName() + ":" + m.getMethodName() + "() \n" + msg;
}
private String getErrorMessage(final Exception e) {
StringBuilder sb = new StringBuilder();
StackTraceElement[] st = e.getStackTrace();
if (st != null && st.length > 0) {
sb.append("Class:")
.append(e.getClass().getName())
.append("¥n")
.append("Detail:")
.append(e.getMessage())
.append("¥n");
for (StackTraceElement s : st) {
sb.append(s.toString())
.append("¥n");
}
}
return sb.toString();
}
public void debug(final String msg) {
LogManager.getLogger(this.getClass()).debug(getMessage(msg));
}
public void info(final String msg) {
LogManager.getLogger(this.getClass()).info(getMessage(msg));
}
public void info(final Object obj, final String msg) {
LogManager.getLogger(obj.getClass()).info(msg);
}
public void warn(final String msg) {
LogManager.getLogger(this.getClass()).warn(getMessage(msg));
}
public void error(final Exception e) {
LogManager.getLogger(e.getClass()).error(getErrorMessage(e));
}
public void trace(final String msg) {
LogManager.getLogger(this.getClass()).trace(getMessage(msg));
}
public void fatal(final String msg) {
LogManager.getLogger(this.getClass()).fatal(getMessage(msg));
}
}
In EndPoint, call and use as follows.
Log4j logger = Log4j.getInstance();
logger.info("Write the log contents here");
The following levels of logs are prepared in log4j, and the wrap method is defined accordingly.
fatal > error > warn > info > debug > trace
The log4j2 configuration file is described in an xml file named "log4j2.xml". Also, in Tomcat, you can load it automatically by placing it in the webapp-> WEB-INF-> classes folder. Here is an example of how to fill in log4j2.xml.
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="off">
<Properties>
<Property name="loglayout">[%d{yyyy-MM-dd HH:mm:ss.SSS}], %-5p, %t, %c, %m%n</Property>
</Properties>
<Appenders>
<!--
fileName:File name to output the log
filePattern:File pattern to compress when logs are accumulated
-->
<RollingFile name="rolling" fileName="./log/webapp.log" filePattern="./log/webapp-%d{yyyy-MM-dd}-%i.zip">
<PatternLayout pattern="${loglayout}"/>
<Policies>
<OnStartupTriggeringPolicy/>
<SizeBasedTriggeringPolicy size="20 MB"/>
<TimeBasedTriggeringPolicy/>
</Policies>
<DefaultRolloverStrategy max="10"/>
</RollingFile>
<Console name="console" target="SYSTEM_OUT">
<PatternLayout pattern="${ptn}" />
</Console>
</Appenders>
<Loggers>
<!--
name:Package name for log output
level:Log output level
additivity:Whether to output the upper log
-->
<Logger name="Logger" level="info" additivity="true">
<AppenderRef ref="rolling"/>
</Logger>
</Loggers>
</Configuration>
More information can be found at the links below.
In the Gradle project, the relative path is directly under the project, so the file directory
. -> log
However, in Tomcat, the root of the relative path is the tomcat installation folder, so
.-> webapps->
Actually, add the following code to build.gradle.
//Run before running the war task
war.doFirst {
//Get child files
java.io.File[] flist = (new java.io.File("./src/main/webapp/WEB-INF/classes")).listFiles();
for(i in flist) {
//File name judgment
switch (i.getName()) {
case "log4j2.xml":
//rename
i.renameTo(new java.io.File("./src/main/webapp/WEB-INF/classes/log4j2_test.xml"));
break;
case "log4j2_exe.xml":
i.renameTo(new java.io.File("./src/main/webapp/WEB-INF/classes/log4j2.xml"));
break;
}
}
}
//Run after war task execution
war.doLast {
java.io.File[] flist = (new java.io.File("./src/main/webapp/WEB-INF/classes")).listFiles();
for(i in flist) {
switch (i.getName()) {
case "log4j2_test.xml":
i.renameTo(new java.io.File("./src/main/webapp/WEB-INF/classes/log4j2.xml"));
break;
case "log4j2.xml":
i.renameTo(new java.io.File("./src/main/webapp/WEB-INF/classes/log4j2_exe.xml"));
break;
}
}
}
When I create a file for each war task execution, it is not recognized as a managed file by git -> You should be able to set it in one xml
Recommended Posts