Spring 简明教程

Spring - Logging with Log4J

这是一个非常易于使用的 Spring 应用程序中的 Log4J 功能。以下示例将引导你完成一些简单的步骤,以解释 Log4J 和 Spring 之间的简单集成。

This is a very easy-to-use Log4J functionality inside Spring applications. The following example will take you through simple steps to explain the simple integration between Log4J and Spring.

我们假设你已在机器上安装了 log4J 。如果没有,则可以从 https://logging.apache.org/ 下载它,然后只需将压缩文件解压到任意文件夹中。我们只会在我们的项目中使用 log4j-x.y.z.jar

We assume you already have log4J installed on your machine. If you do not have it then you can download it from https://logging.apache.org/ and simply extract the zipped file in any folder. We will use only log4j-x.y.z.jar in our project.

接下来,让我们准备一个运行中的 Eclipse IDE,并按照以下步骤使用 Spring Web 框架开发基于动态表单的 Web 应用程序:

Next, let us have a working Eclipse IDE in place and take the following steps to develop a Dynamic Form-based Web Application using Spring Web Framework −

Steps

Description

1

Create a project with a name SpringExample and create a package com.tutorialspoint under the src folder in the created project.

2

Add required Spring libraries using Add External JARs option as explained in the Spring Hello World Example chapter.

3

Add log4j library log4j-x.y.z.jar as well in your project using using Add External JARs.

4

Create Java classes HelloWorld and MainApp under the com.tutorialspoint package.

5

Create Beans configuration file Beans.xml under the src folder.

6

Create log4J configuration file log4j.properties under the src folder.

7

The final step is to create the content of all the Java files and Bean Configuration file and run the application as explained below.

以下是 HelloWorld.java 文件的内容

Here is the content of HelloWorld.java file

package com.tutorialspoint;

public class HelloWorld {
   private String message;

   public void setMessage(String message){
      this.message  = message;
   }
   public void getMessage() {
      System.out.println("Your Message : " + message);
   }
}

以下是第二个文件的内容 MainApp.java

Following is the content of the second file MainApp.java

package com.tutorialspoint;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.apache.log4j.Logger;

public class MainApp {
   static Logger log = Logger.getLogger(MainApp.class.getName());

   public static void main(String[] args) {
      ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
      log.info("Going to create HelloWord Obj");
      HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
      obj.getMessage();

      log.info("Exiting the program");
   }
}

您可以像生成信息消息一样生成 debugerror 信息。现在让我们看看 Beans.xml 文件的内容

You can generate debug and error message in a similar way as we have generated info messages. Now let us see the content of Beans.xml file

<?xml version = "1.0" encoding = "UTF-8"?>

<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

   <bean id = "helloWorld" class = "com.tutorialspoint.HelloWorld">
      <property name = "message" value = "Hello World!"/>
   </bean>

</beans>

以下是 log4j.properties 的内容,它定义了 Log4J 生成日志消息所需的标准规则

Following is the content of log4j.properties which defines the standard rules required for Log4J to produce log messages

# Define the root logger with appender file
log4j.rootLogger = DEBUG, FILE

# Define the file appender
log4j.appender.FILE=org.apache.log4j.FileAppender
# Set the name of the file
log4j.appender.FILE.File=C:\\log.out

# Set the immediate flush to true (default)
log4j.appender.FILE.ImmediateFlush=true

# Set the threshold to debug mode
log4j.appender.FILE.Threshold=debug

# Set the append to false, overwrite
log4j.appender.FILE.Append=false

# Define the layout for file appender
log4j.appender.FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.FILE.layout.conversionPattern=%m%n

在您创建源文件和 bean 配置文件后,让我们运行应用程序。如果您的应用程序一切正常,它将在 Eclipse 控制台中打印以下消息:

Once you are done with creating source and bean configuration files, let us run the application. If everything is fine with your application, this will print the following message in Eclipse console −

Your Message : Hello World!

如果您检查 C:\\ 驱动器,那么您应该会发现日志文件 log.out ,其中包含各个日志消息,如下所示:

If you check your C:\\ drive, then you should find your log file log.out with various log messages, like something as follows −

<!-- initialization log messages -->

Going to create HelloWord Obj
Returning cached instance of singleton bean 'helloWorld'
Exiting the program

Jakarta Commons Logging (JCL) API

或者,您可以使用 Jakarta Commons Logging (JCL) API 在 Spring 应用程序中生成日志。可以从 https://jakarta.apache.org/commons/logging/ 下载 JCL。在该软件包之外,我们唯一在技术上需要的就是 commons-logging-x.y.z.jar 文件,该文件需要以与在上述示例中放置 log4j-x.y.z.jar 相同的方式置于您的类路径中。

Alternatively you can use Jakarta Commons Logging (JCL) API to generate a log in your Spring application. JCL can be downloaded from the https://jakarta.apache.org/commons/logging/. The only file we technically need out of this package is the commons-logging-x.y.z.jar file, which needs to be placed in your classpath in a similar way as you had put log4j-x.y.z.jar in the above example.

要使用日志记录功能,您需要 org.apache.commons.logging.Log 对象,然后您可以根据需求调用以下方法之一:

To use the logging functionality you need a org.apache.commons.logging.Log object and then you can call one of the following methods as per your requirment −

  1. fatal(Object message)

  2. error(Object message)

  3. warn(Object message)

  4. info(Object message)

  5. debug(Object message)

  6. trace(Object message)

以下是 MainApp.java 的替换内容,它使用 JCL API

Following is the replacement of MainApp.java, which makes use of JCL API

package com.tutorialspoint;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.apache.commons.logging. Log;
import org.apache.commons.logging. LogFactory;

public class MainApp {
   static Log log = LogFactory.getLog(MainApp.class.getName());

   public static void main(String[] args) {
      ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
      log.info("Going to create HelloWord Obj");
      HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
      obj.getMessage();

      log.info("Exiting the program");
   }
}

您必须确保在编译和运行程序之前已将 commons-logging-x.y.z.jar 文件包含在您的项目中。

You have to make sure that you have included commons-logging-x.y.z.jar file in your project, before compiling and running the program.

现在,在上述示例中保持其余的配置和内容不变,如果您编译并运行应用程序,您将获得与使用 Log4J API 相似的结果。

Now keeping the rest of the configuration and content unchanged in the above example, if you compile and run your application, you will get a similar result as what you got using Log4J API.