package log4j; import org.apache.log4j.*; // How to use log4j public class TestLogging { // Initialize a logging category. Here, we get THE ROOT CATEGORY //static Category cat = Category.getRoot(); // Or, get a custom category static Category cat = Category.getInstance(TestLogging.class.getName()); // From here on, log away! Methods are: cat.debug(your_message_string), // cat.info(...), cat.warn(...), cat.error(...), cat.fatal(...) public static void main(String args[]) { // Try a few logging methods PropertyConfigurator.configure ( "log4j.properties" ) ; cat.debug("Start of main()"); cat.info("Just testing a log message with priority set to INFO"); cat.warn("Just testing a log message with priority set to WARN"); cat.error("Just testing a log message with priority set to ERROR"); cat.fatal("Just testing a log message with priority set to FATAL"); // Alternate but INCONVENIENT form cat.log(Priority.DEBUG, "Calling init()"); new TestLogging().init(); } public void init() { java.util.Properties prop = System.getProperties(); java.util.Enumeration enum = prop.propertyNames(); cat.info("***System Environment As Seen By Java***"); cat.debug("***Format: PROPERTY = VALUE***"); while (enum.hasMoreElements()) { String key = (String) enum.nextElement(); cat.info(key + " = " + System.getProperty(key)); } } } xml格式的log4j配置文件概述 xml格式的log4j配置文件需要使用org.apache.log4j.html.DOMConfigurator.configure()方法来 读入.对xml文件的语法定义可以在log4j的发布包中找到:org/apache/log4j/xml/log4j.dtd. Xml的一个配置文件:sample1.xml 说明: ①xml配置文件的头部包括两个部分:xml声明和dtd声明.头部的格式如下: