It is not appropriate to attribute this to Struts2, because log4j is an open source code project, not only can be used on Struts2.
Let's introduce log4j: by using log4j, we can output some information to the console, text file, html file, etc.
First, create a Java project, we create a lib directory, and then import log4j-1.2.15.jar or other versions of the package and add it to the path.
Then, we define a simple logic class UserDao. Java
- package cn.com;
- import org.apache.log4j.Logger;
- publicclass UserDao {
- publicstaticfinal Logger logger = Logger.getLogger(UserDao.class);
- publicvoid add(){
- logger.debug( "This is the debug level" );
- logger.info( "This is the info level" );
- logger.warn( "This is the warn level" );
- logger.error( "This is the error level" );
- logger.fatal( "This is the fatal level" );
- }
- }
As you can see, in the code, we first create a Logger object and add the class to output the log
Then, create in the src directory: log4j.properties
- log4j.appender.stout=org.apache.log4j.ConsoleAppender
- log4j.appender.stout.layout=org.apache.log4j.PatternLayout
- log4j.appender.stout.layout.ConversionPattern=[%p][%l]-->%m(%d)%n
- log4j.rootLogger=DEBUG,stout
Let's analyze the steps of the above operation:
- 1. Import the package
- 2. Create a Logger object
- //public static final Logger logger = Logger.getLogger(UserDao.class);
- 3. Write the corresponding log
- /** You can set different levels for logging, in log4j:
- debug<info<warn<error<fatal **/
- logger.debug("This is the debug level");
- logger.info("This is info level");
- logger.warn("This is the warn level");
- logger.error("This is the error level");
- logger.fatal("This is the fatal level");
- 4. Write the configuration file of the log to illustrate the display mode and level of the log (create the log4j.properties file in the src directory)
- 4.1 First create Append
- log4j.appender.stout=org.apache.log4j.ConsoleAppender
- 4.2 Explain the layout of the display
- log4j.appender.stout.layout=org.apache.log4j.PatternLayout
- Indicate which layout to use for display, commonly used PatternLayout to display
- 4.3 Explain what format is used to complete the display
- log4j.appender.stout.layout.ConversionPattern==[%p][%l]-->%m(%d)
- The format used is [what level of log] [where the log occurs] --> log information (log time)
- 5. When to output the log
- log4j.rootLogger=DEBUG,stout
- rootLogger is the Logger of the root directory. The classpath of each project is the root directory. As long as it runs to the location of the output log, and the log level is greater than DEBUG, it will output
Then, we create a class to test:
- package cn.junit;
- import cn.com.UserDao;
- public class TestLog {
- publicstaticvoid main(String[] args) {
- UserDao u = new UserDao ();
- u.add();
- }
- }
Run the main function of this class, the console will print out the corresponding log information