Log4J creates log file but does not write to it

前端 未结 3 1189
执笔经年
执笔经年 2021-01-02 07:50

I\'m trying to configure log4j to log messages to a file. Right now, the file does get created with the name I provide, but the logs are not written to the file. My code:

相关标签:
3条回答
  • 2021-01-02 08:21

    The output seems to be of the default format that Java's standard logging framework (JUL) would emit.

    So, there are two possibilities (that come to mind):

    1. Your code imports java.util.logging.Logger, rather than org.apache.log4j.Logger.
    2. There exists a library of some sort, in your classpath, that intercepts Log4J calls and converts them to JUL calls.
    0 讨论(0)
  • 2021-01-02 08:38

    I have the same problem, and i solved it. When I changed level form INFO to DEBUG in properties file - line:

    log4j.rootLogger=DEBUG, file, stdout
    

    and than I wrote in script:

    logger.debug("Hello world");

    everything was saved in file.

    0 讨论(0)
  • 2021-01-02 08:45

    I had the same problem as you. File was created, but without any loggs in it just in console. And it was because of incorrect dependencies in maven project in my case.

    My log4j.properties file was:

    # Root logger option
    log4j.rootLogger=DEBUG, file
    
    # Direct log messages to a log file
    # configuration to print into file
    log4j.appender.file=org.apache.log4j.RollingFileAppender
    log4j.appender.file.MaxFileSize=1MB
    log4j.appender.file.MaxBackupIndex=10
    # Define the layout for file appender
    log4j.appender.file.layout=org.apache.log4j.PatternLayout
    #log4j.appender.file.layout.ConversionPattern=[%t] %-5p %c %x - %m%n
    log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
    # Set the name of the file
    log4j.appender.file.File=C:\\log\\logging.log
    # Set the append to false, overwrite
    log4j.appender.file.Append=false
    

    And I used in POM:

    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-simple</artifactId>
      <version>1.6.2</version>
    </dependency>
    
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>
    

    Yes, it created for me file where I needed it, but logs were in console. Then I changed it to another dependency like:

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.5</version>
    </dependency>
    

    And I finally got it in file instead of console. Even without any explicit commands like PropertyConfigurator.configure().

    0 讨论(0)
提交回复
热议问题