Original address: http://www.hankcs.com/program/java/log4j-2-console-color-configuration-with-intellij-idea.html
If you are ready to open a large project, the log system is essential. LOG4J is the best log component on the Java platform, and the log4j 2 upgrades a lot of APIs and is more scalable. log4j 2 Installation
Requires two jars: Log4j-api-2.0-rc1.jar and Log4j-core-2.0-rc1. People with obsessive-compulsive disorder like me have to take doc and sources.
One of the simplest tests
Import Org.apache.logging.log4j.LogManager; Import Org.apache.logging.log4j.Logger; public class HelloWorld {private static Logger Logger = Logmanager.getlogger ("HelloWorld"); public static void Main (string[] args) {Logger.debug ("would not show."); Logger.error ("Hello, world!"); } }
Can be seen in the console
20:35:34.712 [main] ERROR Com.hankcs.main-hello, world!
configuration file Log4j2.xml
The default configuration only outputs logs of error and above to the console, and you can customize it by creating a log4j2.xml in the root directory:
<?xml version= "1.0" encoding= "UTF-8"?> <configuration status= "OFF" > <appenders> <console Name= "Console" target= "System_out" > <patternlayout pattern= "%d{hh:mm:ss. SSS} [%t]%-5level%logger{36}-%msg%n "/> </Console> </appenders> <loggers> <root level= "Trace" > <appender-ref ref= "Console"/> </root> </loggers> < /configuration>
Then come to a more complex test:
package com.hankcs; import org.apache.logging.log4j.level; import org.apache.logging.log4j.logmanager; Public class main { public static Org.apache.logging.log4j.logger logger = logmanager.getlogger (); public static void main (String[] args) { add (1,&NBSP;2); } public static int add (int a , &NBSP;INT&NBSP;B) { logger.entry (A, &NBSP;B); logger.info ("I am info info"); logger.warn ("I am warn information"); logger.error ("I am the error message"); logger.fatal ("I am fatal Information"); logger.printf (level.trace, "%d+%d=%d", a, b, a + &NBSP;B); logger.exit (A&NBSP;+&NBSP;B); return a + b; }}
Output: