Zia
Zia

Reputation: 1011

Writing a log in to specific file for particular Class special log

In my application currently I am using the log4j for log. All the logs are getting written in to same log file. there is one common log file, where some others application also used write the log.

Lets assume i have aap.log and common.log. I want that all the log will get in app.log file but for some specific class log will get in common.log.

My log4j config is as below for app.log

<appender name="logFile" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <File>${home}/logs/app.log</File>       
        <encoder>
            <pattern>%d{MM.dd HH:mm:ss.SSS} [%2.2t][%c{1}.%M] %-5p - %m%n</pattern>
        </encoder>
        <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
            <maxIndex>20</maxIndex>
            <FileNamePattern>${home}/logs/app.log.%i</FileNamePattern>
        </rollingPolicy>
        <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
            <MaxFileSize>25MB</MaxFileSize>
        </triggeringPolicy>
    </appender>

I don't want to create a new appender here for the common.log or addadditivity="false for that class. I want to use one CustomUtility class to write the log in to common.log instead of configuring it from log4.xml.

How can i write the log in same common.log file so other applications data or mine will not get messed up.

Upvotes: 0

Views: 38

Answers (1)

Mark Bramnik
Mark Bramnik

Reputation: 42541

So in a nutshell, you need to do the following:

  1. Define an another File appender (basically duplicate the section that you've presented in the question, change the name pattern). I don't think you should use app.log and app1.log to avoid confusion related to log rotation policies. So just pick other name for this new log file and associate appender with it.

  2. When you have an appender - associate the logger of the utility class with this appender. You don't show it in the question but the chances are that a special "root" logger is associated with the presented appender. So you should define a logger for the utility class (use fully qualified name of the class including the package) and associate the appender that you've created in "1" with it.

After this step, logs coming from this utility class will be written into 2 files. Why? Because of additivity feature of logging libraries:

  1. So you should define the log created in "2" with "additivity=false". Basically additivity means that you should resolve the actual appenders not only from the logger itself but from its parents as well, setting additivity=false breaks this chain

Upvotes: 0

Related Questions