简体   繁体   English

将log4j2用于多个类

[英]Use log4j2 for multiple classes

I found many link that helped me building the logger. 我发现许多链接可以帮助我构建记录器。 Some here in SO and others in other pages. 一些在SO中,其他在其他页面中。

This answer here: https://stackoverflow.com/questions/7624895/how-to-use-log4j-with-multiple-classes# = is the best that I have found. 这个答案在这里: https : //stackoverflow.com/questions/7624895/how-to-use-log4j-with-multiple-classes# =是我发现的最好的。 It is already some years old thought and some things now are different. 已经有几年的历史了,现在有些事情有所不同了。

My goal is to have one single logger shared among all of the java classes that print messages to the log, both console and file. 我的目标是在所有将消息打印到日志(包括控制台和文件)的java类中共享一个记录器。

I am using LOG4J2: http://logging.apache.org/log4j/2.x/manual/configuration.html 我正在使用LOG4J2: http ://logging.apache.org/log4j/2.x/manual/configuration.html

main() : main()

import org.apache.logging.log4j.Logger;

public class App {
    private static final Logger LOGGER = Logger.getLogger("GLOBAL");
    public static void main(){
        ...calling other classes
  }
}

anyOtherClass : anyOtherClass

import org.apache.logging.log4j.Logger;
public class secondClass {
    private final Logger LOGGER = Logger.getLogger("GLOBAL");
    public void writeLog(){
      LOGGER.log(Level.INFO, "A simple string");
  }
}

log4j.xml 的log4j.xml

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn">
    <Properties>
        <Property name="basePath">/var/log</Property>
    </Properties>

    <Appenders>
        <RollingFile name="fileLogger" fileName="${basePath}/myApp.log" filePattern="${basePath}/myApp-%d{yyyy-MM-dd}.log">
            <PatternLayout pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n" />
            <Policies>
                <TimeBasedTriggeringPolicy interval="1" modulate="true" />
            </Policies>
        </RollingFile>

       <Console name="console" target="SYSTEM_OUT">
            <PatternLayout pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n" />
        </Console>
    </Appenders>
    <Loggers>
        <Logger name="java.util.logging.Logger" level="ALL" additivity="true">
            <appender-ref ref="fileLogger" level="ALL" />
        </Logger>
        <Root level="ALL" additivity="false">
            <appender-ref ref="console" />
        </Root>
    </Loggers>
</Configuration>

I (more or less) know that I should use LogManager, truth is I should call it as: 我(或多或少)知道我应该使用LogManager,事实是我应该将其称为:

private static final Logger logger = LogManager.getLogger(MyApp.class);

or, in the main() , probably like this: 或者,在main()中 ,可能像这样:

private static Logger LOGGER = null;

@BeforeClass
public static void setLogger() {
    System.setProperty("log4j.configurationFile","log4j.xml");
    LOGGER = LogManager.getLogger();
}

Because, I believe, using LogManager I can point the Log to the xml file for its settings. 因为,我相信,使用LogManager可以将Log指向xml文件进行设置。 But when I build it and run it, the CLI rage quits at the first ever LOG, reporting: Exception in thread "main" java.lang.NullPointerException at myapp.modules.Database.<init>(Database.java:67) 但是,当我构建并运行它时,CLI愤怒在有史以来的第一个日志中退出,并报告: Exception in thread "main" java.lang.NullPointerException at myapp.modules.Database.<init>(Database.java:67)

Expected Result : All I want to do is being able to have the log on all of my classes and that this is written to a file. 预期结果 :我要做的就是能够记录所有类,并将其写入文件中。 I just can't get this working. 我就是无法正常工作。 And when I do not use LogManager, I only see the logs on console but no file is created. 而且当我不使用LogManager时,我只会在控制台上看到日志,但没有创建文件。 I'm using both Windows and Linux (that's why /var/log/ but I change it to C:\\ too). 我同时使用Windows和Linux(这就是/ var / log /的原因,但我也将其更改为C:\\)。

Other website I used : https://howtodoinjava.com/log4j2/configure-log4j2-for-junit/ 我使用的其他网站https : //howtodoinjava.com/log4j2/configure-log4j2-for-junit/

Log4J loggers for different classes <-- did not help me 不同类的Log4J记录器 <-对我没有帮助

..And many other search results are more than 6 years old. ..以及许多其他搜索结果已有6年以上的历史了。

POM.xml : POM.xml

<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-api</artifactId>
    <version>2.10.0</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.10.0</version>
</dependency>

You're wrong on several levels: you're mixing JDK's logger with Log4j2's Logger, you're not logging to several appenders, etc. 您在多个级别上是错误的:您将JDK的记录器与Log4j2的记录器混合使用,没有记录到多个附加程序等。

Here's what you should do: 这是您应该做的:

/pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>log4j2test</artifactId>
    <version>0.1</version>
    <packaging>jar</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.10.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.10.0</version>
        </dependency>
    </dependencies>
</project>

This is basically the only place where you have no error. 基本上,这是唯一没有错误的地方。

/src/main/java/so47656300/App.java

package so47656300;

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

public class App {

  private static final Logger logger = LogManager.getLogger(App.class);

  public static void main(String[] args) {
    logger.info("App.main - starting");
    new SecondClass();
    logger.info("App.main - ending");
  }
}

Here, your error was to use java.util.logger.Logger instead of org.apache.logging.log4j.Logger . 在这里,您的错误是使用java.util.logger.Logger而不是org.apache.logging.log4j.Logger

/src/main/java/so47656300/SecondClass.java

package so47656300;

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

public class SecondClass {

  private static final Logger logger = LogManager.getLogger(SecondClass.class);

  public SecondClass() {
    logger.info("SecondClass - starting");
    logger.info("SecondClass - ending");
  }
}

Here, your error was also to use the wrong Logger class. 在这里,您的错误还在于使用了错误的Logger类。 Use only classes from org.apache.logging.log4j.* . 仅使用org.apache.logging.log4j.*类。

/src/main/resources/log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Properties>
        <Property name="basePath">/var/log</Property>
    </Properties>
    <Appenders>
        <RollingFile name="fileLogger" fileName="${basePath}/myApp.log" filePattern="${basePath}/myApp-%d{yyyy-MM-dd}.log">
            <PatternLayout pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n" />
            <Policies>
                <TimeBasedTriggeringPolicy interval="1" modulate="true" />
            </Policies>
        </RollingFile>

        <Console name="console" target="SYSTEM_OUT">
            <PatternLayout pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n" />
        </Console>
    </Appenders>
    <Loggers>
        <Root level="INFO">
            <AppenderRef ref="console"/>
            <AppenderRef ref="fileLogger"/>
        </Root>
    </Loggers>
</Configuration>

Here, your errors are the following: 在这里,您的错误如下:

  1. Wrong file name: Log4J 2 requires a name log4j2.xml . 文件名错误: Log4J 2需要名称log4j2.xml For your tests, create a file /src/test/resources/log4j2-test.xml . 为了进行测试,请创建一个文件/src/test/resources/log4j2-test.xml
  2. You want only one logger, so use only one: the root one. 您只需要一个记录器,因此仅使用一个:根记录器。 You created several, but you don't need them. 您创建了几个,但不需要它们。
  3. Add appenders to the logger (the Root-one) 将附加器添加到记录器(根目录一)

Output 产量

Console 安慰

[INFO ] 2017-12-05 16:52:32.218 [main] App - App.main - starting
[INFO ] 2017-12-05 16:52:32.221 [main] SecondClass - SecondClass - starting
[INFO ] 2017-12-05 16:52:32.222 [main] SecondClass - SecondClass - ending
[INFO ] 2017-12-05 16:52:32.222 [main] App - App.main - ending

/var/log/myApp.log

[INFO ] 2017-12-05 16:52:32.218 [main] App - App.main - starting
[INFO ] 2017-12-05 16:52:32.221 [main] SecondClass - SecondClass - starting
[INFO ] 2017-12-05 16:52:32.222 [main] SecondClass - SecondClass - ending
[INFO ] 2017-12-05 16:52:32.222 [main] App - App.main - ending

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM