Log file not being updated/created using log4j in

2019-07-14 07:39发布

I am trying to capture the logs using log4j in Java. The executeable is in linux envirnment and it displays the logging message, however, it is not writing into the log file. I am using log4j.xml and this is what I have so far

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

  <appender name="LocalFileAppender" class="org.apache.log4j.RollingFileAppender">
    <param name="File"   value="logs/error.log" />
    <param name="Append" value="true" />
    <param name="MaxFileSize" value="500KB" />
    <param name="maxBackupIndex" value="1" />
      <layout class="org.apache.log4j.PatternLayout">
         <param name="ConversionPattern" value="%d %-5p [%c] - %m%n"/>
      </layout>
  </appender>

  <appender name="ConsoleAppender" class="org.apache.log4j.ConsoleAppender">
    <layout class="org.apache.log4j.SimpleLayout"/>
  </appender>

  <root>
    <priority value ="Debug" />
    <appender-ref ref="console" /> 
  </root>
</log4j:configuration>

I am not clear how the java program knows where the xml file is located. I think that is the problem. And, this is how I setup in the code,

log = Logger.getLogger(MyClass.class);

BasicConfigurator.configure();

Any help would be appreicate it. Thanks.

标签: java log4j
2条回答
做个烂人
2楼-- · 2019-07-14 08:13

You can place the log4j.xml file on the classpath of your application and log4j will find it automatically to configure itself with the very first time you use log4j.

However, by calling BasicConfigurator.configure(), you are undoing any configuration done by the XML file - as this sets up a console appender to the root logger only.

Run your java program with -Dlog4j.debug to have log4j output a bunch of information about where it is looking for the configuration files when it starts up.

查看更多
虎瘦雄心在
3楼-- · 2019-07-14 08:13

1) On the Windows env , Even if all the parameters are right , need to make sure that the path to the file is absolute and that is separated by " / " rather than the normal "\" .

While deciding on the path , "\" are ignored and so it becomes one large name .

And hence it might seem that nothing's been written , it actually is that it's getting written at a different place . :)

2) And on Eclipse , to try out the option that the previous answer by "matt B" suggests..

Go to RUN > RUN Configurations > Arguments [tab ] and put in the value in the VM arguments > Apply and RUN . Obviously your file should have main..

查看更多
登录 后发表回答