How to configure log4j and logback to log into one single file properly?

Viewed 5986

I have a java web app that uses logback with slf4j for logging. And this project has a dependency jar (which is a sub project). And this dependency jar uses org.apache.log4j.Logger for logging. All logs must go into one log file. My problem is, whatever I am logging with the code in the jar file is not being written to the log file. Initially I had logback.xml. To resolve the above problem I added log4j.properties file to my web app. It resolved my problem and now I can see all logs in one file.

Again my new probelm is: Earlier the log file was rolling every day according to the rolling policy in logback.xml. Now it is not rolling. Even after I configured the rolling policy in log4j.properties that matches with the rolling policy that is in logback.xml, rolling is not happening.

I don't want to replace log4j in my dependency with logback. And also I want to write alll my logs into one file. Is it possible to this, how can I resolve my issue?

FYI: I have "log4j-over-slf4j" dependency included in my pom.xml

Log4j.properties:

log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.File=SOME_PATH/logs/studentApp.log
log4j.appender.file.rollingPolicy = org.apache.log4j.rolling.TimeBasedRollingPolicy
log4j.appender.file.rollingPolicy.FileNamePattern = SOME_PATH/logs/studentApp.%d{yyyy-MM-dd}.log    
log4j.appender.file.maxBackupIndex=14
log4j.appender.file.threshold=DEBUG
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%-5p] %d %c - %m%n
log4j.rootLogger=DEBUG,file
2 Answers

The following configuration will create a .log file for the current date and keep adding the log in that file. When the date chanages, it will create a new file with the current date. This configuration will also zip the files as or when they exceed a certain size limit.

    <appender name="FILE"
        class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">

            <fileNamePattern>log.%d{yyyy-MM-dd}.%i.log.zip</fileNamePattern>

                          <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                                <!-- or whenever the file size reaches 500MB -->
                                <maxFileSize>300MB</maxFileSize>
                        </timeBasedFileNamingAndTriggeringPolicy>
        </rollingPolicy>
        <encoder>
            <pattern>%date %level [%thread] %logger{0} - %msg%n</pattern>
        </encoder>
    </appender>

Hope it helps.

Related