如何让Log4j使用stdout?

Bom*_*e_A 6 java log4j

我正在使用log4j在一些我正在进行调试的代码中.我一直在运行我的代码java -jar test.jar | tee file.txt来登录到一个文件,但现在我希望能够在我仍在运行时切换我正在登录的文件,这是tee无法做到的.现在我正在这样做

private static final Logger log = LoggerFactory.getLogger(Test.class);

public void main() {
File file = new File(/path/to/file);
System.setOut(new PrintStream(file));
System.out.println("hello world"); //This works.
log.info("hello world"); //this doesn't.
Run Code Online (Sandbox Code Playgroud)

由于某种原因,Logger输出不会进入我的文件,它会进入我的控制台,但println()工作正常.有谁知道为什么会这样,以及如何解决这个问题?

谢谢.

编辑:这是我的log4j.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

    <appender name="console" class="org.apache.log4j.ConsoleAppender">
        <layout class="org.apache.log4j.PatternLayout">
            <!--<param name="ConversionPattern" value="%d %-5p [%c] %m%n" />-->
            <param name="ConversionPattern" value="%d %-5p [%c:%L] %m%n" />
        </layout>
    </appender>
    <logger name="com.company">
        <level value="trace" />
    </logger>
    <logger name="org.springframework">
        <level value="debug" />
    </logger>
    <logger name="com.company.Selenium">
        <level value="debug" />
    </logger>    
    <logger name="org.springframework">
        <level value="warn" />
    </logger>
    <root>
        <priority value="warn" />
        <appender-ref ref="console" />
    </root>
</log4j:configuration>
Run Code Online (Sandbox Code Playgroud)

另外,当我运行我的项目时,我收到以下错误

log4j:WARN No appenders could be found for logger (org.eclipse.jetty.util.log).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Run Code Online (Sandbox Code Playgroud)

Nar*_*mar 5

请将其添加到您的log4j.properties文件中

# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
Run Code Online (Sandbox Code Playgroud)


MAD*_*MAD 4

取自此链接的示例Using Log4j for debug in Java。您可能缺少 BasicConfigurator.configure();

public class Log4jTest {
  // Initialize logger for instance Log4jTest
  static Logger log  = Logger.getLogger(Log4jTest.class);

  public static void main (String[] args) {
     // Basic configurator to log debug messages to the console
     BasicConfigurator.configure();         
      
     // Add some log messages
     log.debug("This is a debug message");
     log.trace("This is a trace message");         
 }
}
Run Code Online (Sandbox Code Playgroud)