java - 如何创建log4j文件并运行程序

标签 java log4j

现在我正在学习 log4j,请指导我如何逐步创建和运行简单的示例。

最佳答案

来自Log4J Java - A simple Log4J example

package com.devdaily.log4jdemo;

import org.apache.log4j.Category;
import org.apache.log4j.PropertyConfigurator;
import java.util.Properties;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * A simple Java Log4j example class.
 * @author alvin alexander, devdaily.com
 */
public class Log4JExample
{
  // our log4j category reference
  static final Category log = Category.getInstance(Log4JDemo.class);
  static final String LOG_PROPERTIES_FILE = "lib/Log4J.properties";

  public static void main(String[] args)
  {
    // call our constructor
    new Log4JExample();

    // Log4J is now loaded; try it
    log.info("leaving the main method of Log4JDemo");
  }

  public Log4JExample()
  {
    initializeLogger();
    log.info( "Log4JExample - leaving the constructor ..." );
  }

  private void initializeLogger()
  {
    Properties logProperties = new Properties();

    try
    {
      // load our log4j properties / configuration file
      logProperties.load(new FileInputStream(LOG_PROPERTIES_FILE));
      PropertyConfigurator.configure(logProperties);
      log.info("Logging initialized.");
    }
    catch(IOException e)
    {
      throw new RuntimeException("Unable to load logging property " +
                                  LOG_PROPERTIES_FILE);
    }
  }
}

关于java - 如何创建log4j文件并运行程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4163653/

相关文章:

java - (找不到符号 - 方法 inputString(java.lang.String) 帮助为什么会出现此错误?

java - 混合 log4j 1.x 和 log4j 2

java - Logback:选择性屏蔽语句和谨慎模式

java - quartz 调度器 : Log output of separate jobs to different log files

java - 如何将 log4j 添加到使用 OSGI bundle 的 Web 应用程序

java - 在另一个线程中同步运行一个函数

java - while循环中的递增操作(java)

java - 如何在 Maven 多模块 Spring Web 应用程序中 Autowiring 类?

java - 深入研究 Android JSON 数据数组

java - log4j,只需要在日志文件中显示INFO和ERROR信息