mayur_mitkari
mayur_mitkari

Reputation: 197

Log4j Logging for custom Log levels in Java

I have written class for custom logging level i.e. INIT

import org.apache.log4j.Logger;
import org.apache.log4j.Level;

public class InitLoggingLevel extends Level {

    public static final String INITLOGGING_LEVEL = "INITLOGGING";
    public static final Level INIT_LOGGING = new InitLoggingLevel(
        DEBUG_INT - 4, INITLOGGING_LEVEL, 7);

    protected InitLoggingLevel(int level, String levelStr, int syslogEquivalent){
        super(level, levelStr, syslogEquivalent);
    }
}

Now what are changes I need to make in log4j.properties and how I am going to use this INIT logging level in My Java class?

Upvotes: 5

Views: 10294

Answers (4)

Luca Scarpinati
Luca Scarpinati

Reputation: 31

You have to:

  1. Override the method toLevel(String logArgument) like this:

    public static Level toLevel(String logArgument) {
        if (logArgument != null && logArgument.toUpperCase().equals("INITLOGGING")) {
            return INIT_LOGGING;
        }
        return (Level) toLevel(logArgument);
    }
    
  2. Write a configuration line in the log4j.properties like this:

    log4j.logger.[MY_CATEGORY]=INITLOGGING#your-package.InitLoggingLevel

That's all!

P.S.: The '#' syntax is described in org.apache.log4j.helpers.OptionConverter source class.

Upvotes: 3

JLind
JLind

Reputation: 1

Don't know if you already figured it out, but I found the following article, which helped me.

https://www.owasp.org/index.php/How_to_add_a_security_log_level_in_log4j

The new level is printed with the expected log tag, but log4j will not recognize the new level in my property file. I will see, what I can do about that.

Upvotes: 0

OQJF
OQJF

Reputation: 1350

It can be like this :

 <category  name="xxx" additivity="false">
           <priority class="your class" value="info"/>
           <appender-ref ref="xxxlog"/>
        </category>

Upvotes: 0

Jefri P.
Jefri P.

Reputation: 76

You can try this

log4j.rootLogger=DEBUG, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %c:%L - %m%n
log4j.category.YOUR_PACKAGE=INFO,YOUR_PACKAGE.InitLoggingLevel

or can view log4j category or http://veerasundar.com/blog/2009/08/log4j-tutorial-how-to-send-log-messages-to-different-log-files/

Upvotes: 1

Related Questions