Search code examples
javalog4j

log4j logger set default priority


I have an standalone java application with following config 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="file" class="org.apache.log4j.RollingFileAppender">
        <param name="maxFileSize" value="1MB" />
        <param name="maxBackupIndex" value="1" />
        <param name="File"
            value=".\\myComp.log" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d{dd.MM.yy HH\:mm\:ss.SSS} %5p %c{1}:%L - %m%n " />
        </layout>
    </appender>

    <category name="com.mycomp.project.starter">
        <priority value="${project.client.log.level.starter}" />
    </category>
    <category name="com.security">
        <priority value="${project.client.log.level.security}" />
    </category>

    <root>
        <level value="ERROR" />
        <appender-ref ref="file" />
    </root>

</log4j:configuration>

When I start the Application I can set the log level through a ini file which can contain:

-Dproject.client.log.level.starter=INFO
-Dproject.client.log.level.security=DEBUG

What I would like to archive is, if the -Dproject.client.log.level.security=DEBUG is not set it should use ERROR.

How could I achieve this? I appreciate any help.


Solution

  • Okay, I got a solution, unfortunately it involved switching to log4j2.

    I found out that log4j allows Property Substitution allows to use system properties with prefix sys:. In combination with this finding (where I can set default values with a simple -), I changed my config to:

    <?xml version="1.0" encoding="UTF-8"?>
    <Configuration>
        <Appenders>
            <RollingFile  name="file" fileName=".\\myComp.log" append="true" filePattern=".\\myComp-%d{MM-dd-yyyy}-%i.log.gz">
                <PatternLayout pattern="%d{dd.MM.yy HH:mm:ss.SSS} %5p %c{1}:%L - %m%n "/>
                <Policies>
                    <SizeBasedTriggeringPolicy size="1 MB"/>
                </Policies>
            </RollingFile>
        </Appenders>
        <Loggers>
            <!-- setting log level per default to INFO if not set through system properties -->
            <Logger name="com.myComp.starter" level="${sys:project.client.log.level.starter:-INFO}" />
            <!-- setting log level per default to ERROR if not set through system properties -->
            <Logger name="com.security" level="${sys:project.client.log.level.security:-ERROR}" />
            <Root level="ERROR">
                <AppenderRef ref="file"/>
            </Root>
        </Loggers>
    </Configuration>
    

    Now I am able to set it within a ini file or leave it out if not needed and still have a defined log level.