java 在 Netbeans 中使用 Log4J

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26490156/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 10:00:36  来源:igfitidea点击:

Using Log4J In Netbeans

javanetbeanslog4j

提问by Chui Tey

I am trying to use Log4J in Netbeans, however I am having a very hard time understanding the tutorials. Many of them say "do this" and assume I know what they are talking about. I do not. If you would, I'd like step-by-step instructions on where to find the correct libraries for Log4J, where to put them in a project, and an example program using Log4J.

我正在尝试在 Netbeans 中使用 Log4J,但是我很难理解这些教程。他们中的许多人说“这样做”并假设我知道他们在说什么。我不。如果您愿意,我想要有关在何处找到 Log4J 的正确库、将它们放在项目中的何处以及使用 Log4J 的示例程序的分步说明。

回答by Chui Tey

log4j 2.x

log4j 2.x

Similar to below, but the name of the filename needs to be log4j2.properties. (Also note that old examples of log4j.properties configuration don't actually seem to do anything useful in Log4j 2, so make sure to copy your initial configuration from a tutorial dedicated to Log4j 2, and not the older v1.)

类似于下面,但文件名的名称需要是log4j2.properties. (另请注意,旧的 log4j.properties 配置示例在 Log4j 2 中实际上似乎并没有做任何有用的事情,因此请确保从专用于 Log4j 2 的教程中复制您的初始配置,而不是旧版 v1。)

Thanks @bobulous

谢谢@bobulous

log4j 1.x

log4j 1.x

If you get log4j:WARN No appenders could be found for loggermessage, then it is most likely that you haven't included the log4j.properties file in your project. Here's a screenshot of how you should include it in NetBeans.

如果您收到log4j:WARN No appenders could be found for logger消息,则很可能您尚未在项目中包含 log4j.properties 文件。这是您应该如何将它包含在 NetBeans 中的屏幕截图。

log4j.properties NetBeans

log4j.properties NetBeans

回答by Adz

http://www.tutorialspoint.com/log4j/log4j_sample_program.htm-

http://www.tutorialspoint.com/log4j/log4j_sample_program.htm-

Download the jar from here: https://logging.apache.org/log4j/1.2/download.html

从这里下载 jar:https: //logging.apache.org/log4j/1.2/download.html

Add this file in your path:

将此文件添加到您的路径中:

log4j.properties

log4j.properties

# Define the root logger with appender file
log = /usr/home/log4j
log4j.rootLogger = DEBUG, FILE

# Define the file appender
log4j.appender.FILE=org.apache.log4j.FileAppender

# Here is the location output of the file!
log4j.appender.FILE.File=${log}/log.out

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

Then run this:

然后运行这个:

log4jExample.java

log4jExample.java

import org.apache.log4j.Logger;

import java.io.*;
import java.sql.SQLException;
import java.util.*;

public class log4jExample{
  /* Get actual class name to be printed on */
  static Logger log = Logger.getLogger(
                      log4jExample.class.getName());

  public static void main(String[] args)
                throws IOException,SQLException{

     log.debug("Hello this is an debug message");
     log.info("Hello this is an info message");
  }
}

回答by StevenWernerCS

This very comprehensive working example for log4j2has nearly everything, duplicated here incase the link breaks

这个非常全面的 log4j2 工作示例几乎包含所有内容,此处复制以防链接中断

To get a working example, create a new maven java applicationin netbeans (or any IDE)

要获得一个工作示例,请在 netbeans(或任何 IDE)中创建一个新的 maven java 应用程序

New Project -> Maven -> Java Application

新建项目 -> Maven -> Java 应用程序

In your new maven project there is a pom.xmlunder 'project files' in netbeans, you need to add this dependency:

在您的新 maven 项目中,netbeans 的“项目文件”下有一个pom.xml,您需要添加此依赖项:

I tested this with log4j version 2.11.1, check for latest here

我用 log4j 版本 2.11.1 对此进行了测试,请在此处查看最新版本

   ... 
   </properties>
   <dependencies>
       <dependency>
           <groupId>org.apache.logging.log4j</groupId>
           <artifactId>log4j-core</artifactId>
           <version>2.11.1</version>
       </dependency>
   </dependencies>
</project>

Create a src/main/resources/log4j2.properties(this exact path and name is required)

创建一个src/main/resources/log4j2.properties(需要这个确切的路径和名称)

you can later customize the print layout using thisas a reference

您可以稍后使用作为参考自定义打印布局

status = error
name = PropertiesConfig

filters = threshold
filter.threshold.type = ThresholdFilter
filter.threshold.level = debug

appenders = console
appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = %d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

rootLogger.level = debug
rootLogger.appenderRefs = stdout
rootLogger.appenderRef.stdout.ref = STDOUT

Create a new class: Log4j2HelloWorldExample.java

创建一个新类:Log4j2HelloWorldExample.java

package com.howtodoinjava.log4j2.examples;   

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;


public class Log4j2HelloWorldExample {

    private static final Logger LOGGER = LogManager.getLogger(Log4j2HelloWorldExample.class.getName());

    public static void main(String[] args) {
        LOGGER.debug("Debug Message Logged !!!");
        LOGGER.info("Info Message Logged !!!");
        LOGGER.error("Error Message Logged !!!", new NullPointerException("NullError"));
    }
}

When you run the class you will get his output:

当你运行这个类时,你会得到他的输出

 2016-06-16 13:41:27 DEBUG Log4j2HelloWorldExample:12 - Debug Message Logged !!!
 2016-06-16 13:41:27 INFO  Log4j2HelloWorldExample:13 - Info Message Logged !!!
 2016-06-16 13:41:27 ERROR Log4j2HelloWorldExample:14 - Error Message Logged !!!
 java.lang.NullPointerException: NullError
     at com.howtodoinjava.log4j2.examples.Log4j2HelloWorldExample.main(Log4j2HelloWorldExample.java:14)
    [classes/:?]


If the above example works stand alone, but not when you integrate it into your project there might be some dependency interference

如果上面的例子独立工作,但当你把它集成到你的项目中时,可能会有一些依赖干扰

Run mvn dependency:treeand exclude all interfering log4j dependencies, I needed to exclude these:

运行mvn dependency:tree并排除所有干扰 log4j 的依赖项,我需要排除这些:

<exclusion>
    <!-- 
        [INFO] |  +- log4j:log4j:jar:1.2.17:compile
        [INFO] |  +- org.slf4j:slf4j-log4j12:jar:1.7.16:compile
    -->
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
</exclusion>
<exclusion>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
</exclusion>

To bridge existing slf4j code to my newly added log4j2, I had to include this dependency I found here

为了将现有的 slf4j 代码桥接到我新添加的 log4j2,我必须包含我在这里找到的这个依赖项

   <dependency>
      <groupId>org.apache.logging.log4j</groupId>
      <artifactId>log4j-slf4j-impl</artifactId>
      <version>2.9.0</version>
   </dependency>

I still saw this:

我还是看到了这个:

log4j:WARN No appenders could be found for logger
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.

I also needed to ensure the log4j2.property file had my OS specific line endings, I was using Cygwin to create property files and running netbeans from windows and it failed to find appenders due to the property file all being read as a single line by Windows

我还需要确保 log4j2.property 文件具有我的操作系统特定的行结尾,我使用 Cygwin 创建属性文件并从 Windows 运行 netbeans,但由于属性文件全部被 Windows 读取为一行,因此无法找到附加程序