Java - Log4j

> Procedural Languages > Java

1 - About

Log4j is a debugging logger.

Advertising

3 - Configuration

3.1 - File

as a java property:

-Dlog4j.configuration=file:/etc/schema-registry/log4j.properties

3.2 - Code

public class Main
{
 
    private final static Logger logger = Logger.getLogger(Main.class);
 
    public static void main(final String[] args) throws Exception
    {
 
        // Minimal Configuration
        System.setProperty("log4j.debug","true");
        org.apache.log4j.BasicConfigurator.configure();
 
        if (args.length != 1)
        {
            logger.error("Please provide an argument");
            return;
        }
...

4 - Example

4.1 - Multiple Thread

A constructor code where the logger is declared as class variable private Logger threadLogger

// Logger Name is normally hierarchic "com.foo.bar"
// We add the thread name
String loggerName = QueryExecutor.class.getCanonicalName()+"."+threadName;
LOGGER = Logger.getLogger(loggerName);
 
// Log4j properties
Properties log4jProp = new Properties();
 
// Once a message is accepted by the logger,
// it's sent to one or several appenders (to a file, to the console, to a mail server, etc.).
final String appenderName = "FileAppender";
// Set logger level to DEBUG and its only appender.
log4jProp.setProperty("log4j.logger."+loggerName, "DEBUG, " + appenderName);
 
 
// File Appender
log4jProp.setProperty("log4j.appender." + appenderName,"org.apache.log4j.FileAppender");
// Properties are the set method (File equivalent to setFile)
String timeStamp = new SimpleDateFormat("yyyy.MM.dd_HH.mm.ss").format(new Date());
String logFileName = loggerName+"_"+timeStamp+".log";
log4jProp.setProperty("log4j.appender." + appenderName + ".File", logFileName);
// Above Warning
// The levels of logging are TRACE, DEBUG, INFO, WARN, ERROR and FATAL.
// See org.apache.log4j.Level
log4jProp.setProperty("log4j.appender." + appenderName + ".Threshold","WARN");
// Layout is org.apache.log4j.PatternLayout
log4jProp.setProperty("log4j.appender." + appenderName + ".layout","org.apache.log4j.PatternLayout");
// See org.apache.log4j.PatternLayout#setConversionPattern date in ISO 8601 format, thread name, level, logger, message
log4jProp.setProperty("log4j.appender." + appenderName + ".layout.ConversionPattern","%d [%t] %-5p %c - %m%n");
 
PropertyConfigurator.configure(log4jProp);
lang/java/log4j.txt · Last modified: 2019/10/27 16:38 by gerardnico