Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use log4j with multiple classes?

Tags:

java

log4j

I'm currently writing a big project in java, with numerous classes, some classes are quiet small, that simply represent objects with only few methods. I have a logger set in my main class, and it works fine. I want to be able to use only one logger (with one console appender) with all the classes. I tried to pass a reference to the logger to the different classes, but it doesn't look right. besides, sometimes I'm running tests on the classes without running main, and thus the logger is not initialized for the other classes.

What's the best approach to accomplish that, I mean, how to log from different classes to one log, with no hard dependency between the classes and with the ability to use the log independently with each class ?

like image 963
stdcall Avatar asked Oct 02 '11 06:10

stdcall


People also ask

How can logger be used in multiple classes?

Your logger instances should typically be private , static and final . By doing so, each class will have it's own logger instance (that is created once the class is loaded), so that you could identify the class where the log record was created, and also you no longer need to pass logger instances across classes.

Is log4j outdated?

There have been millions of downloads of outdated, vulnerable Log4j versions despite the emergence of a serious security hole in December 2021, according to figures compiled by the firm that runs Apache Maven's Central Repository.


5 Answers

If I understand correctly, what you have at the minute is:

public class Main {
    public static final Logger LOGGER = Logger.getLogger(Main.class);
}

public class AnotherClass {
    public void doSomething() {
        Main.LOGGER.debug("value=" + value);
    }
}

or, you pass references to a logger into the constructors of the class.

Firstly, you can use one global logger by simply using the same value passed to Logger.getLogger, like:

public class Main {
    private static final Logger LOGGER = Logger.getLogger("GLOBAL");
}

public class AnotherClass {
    private final Logger LOGGER = Logger.getLogger("GLOBAL");

    public void doSomething() {
        LOGGER.debug("value=" + value);
    }
}

This uses exactly the same logger, Logger.getLogger returns the same object in both calls. You no longer have a dependency between the classes, and this will work.

The other thing I gather from your comments is that you are configuring by hand (using BasicConfigurator.configure. Most of the time this isn't necessary, and you should be doing your configuration by simply adding a log4j.properties or log4j.xml to your classpath. In Eclipse this is done by adding it to src/ (or src/main/resources if you're using maven). If you're using junit, then add it to the test/ source directory (or src/test/resources with maven). This is a much better long term way of configuring log4j, because you don't have to pass information between classes.

Also, the recommended way to use loggers is to pass the class to the Logger.getLogger(). In this way you can filter your output based upon the class name, which is usually much more useful than just having one global logger:

public class Main {
    private static final Logger LOGGER = Logger.getLogger(Main.class);
    public static final main(String[] args) {
        LOGGER.debug("started");
    }
}

public class AnotherClass {
    private final Logger LOGGER = Logger.getLogger(this.getClass());

    public void doSomething() {
        LOGGER.debug("value=" + value);
    }
}

Then in the log4j.properties, you can configure a single appender to one file.

# Set root logger level to DEBUG and its only appender to A1.
log4j.rootLogger=DEBUG, A1

# A1 is set to be a ConsoleAppender.
log4j.appender.A1=org.apache.log4j.ConsoleAppender

# A1 uses PatternLayout.
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

Finally, it is not necessary to declare all of your loggers as static. This only makes a noticeable difference if you are doing lots[*] of object creation. Declaring your loggers as non-static fields allows you to use Logger.getLogger(this.getClass()); in which case adding a logger to a class becomes a cut and paste of a single line. This slf4j page contains a good explanation of the pros and cons. So use non-static fields unless you have a very good reason not to.

Cameron is right when he say that you should try and use slf4j if possible, it has one killer feature, you can use multiple logging frameworks with it.

[*] and I mean lots.

like image 83
Matthew Farwell Avatar answered Oct 03 '22 03:10

Matthew Farwell


Your logger instances should typically be private, static and final. By doing so, each class will have it's own logger instance (that is created once the class is loaded), so that you could identify the class where the log record was created, and also you no longer need to pass logger instances across classes.

like image 43
Vineet Reynolds Avatar answered Oct 03 '22 03:10

Vineet Reynolds


The best way to do it is to have each class have it's own logger (named after the class), then set up your configuration so that they all append to the same appender.

For example:

class A {
    private static final Logger log = Logger.getLogger(A.class);
}

class B {
    private static final Logger log = Logger.getLogger(B.class);
}

Then your log4j.properties can look like the example in the log4j documentation:

# Set root logger level to DEBUG and its only appender to A1.
log4j.rootLogger=DEBUG, A1

# A1 is set to be a ConsoleAppender.
log4j.appender.A1=org.apache.log4j.ConsoleAppender

# A1 uses PatternLayout.
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

Both A and B will log to the root logger and hence to the same appender (in this case the console).

This will give you what you want: each class is independent but they all write to the same log. You also get the bonus feature that you can change the logging level for each class in the log4j configuration.

As an aside, you might want to consider moving to slf4j if the project is still in early development. slf4j has some enhancements over log4j that make it a little easier to work with.

like image 43
Cameron Skinner Avatar answered Oct 03 '22 03:10

Cameron Skinner


I recently found out this solution.

Use @Log4j annotation with all the classes in which you wish using logger.

Benefits:

  1. Easy to maintain, easy to track down.
  2. Only one object of the logger is created which will be used through out.

How to do this?

Pre-req: Install Lombok Plugin in your editor, add lombok dependency in your project.

Now for the definition part:

@Log4j2
public class TestClass {
    TestClass() {
        log.info("Default Constructor"); 
        //With the help of lombok plugin, you'll be able to see the suggestions
    }
    <Data members and data methods>
}

UPDATE:

Did some research on this, you can use other Log classes via this method, once you build the code and the Jar has been generated, all the classes using the annotations will share a singleton Logger.

  1. Make sure you are keeping the same standard throughout the project, if someone else starts using the general definition of classes like the traditional way, you might end up having multiple instances.
  2. Make sure that you are using the same logger classes throughout the project, if you have chosen to use @Slf4j, keep it consistent throughout, you might end up with some errors at some places and yes definitely inconsistencies.
like image 32
Priyank Verma Avatar answered Oct 03 '22 02:10

Priyank Verma


The reason you have multiple logger instances is because you want them to behave different when logging (usually by printing out the class name they are configured with). If you do not care about that, you can just create a single static logger instance in a class and use that all over the place.

To create single logger, you can simply create a static utility logging class to be single point logger, so if we need to change the logger package, you will only update this class.

final public class Logger {
    private static final org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger("Log");

    enum Level {Error, Warn, Fatal, Info, Debug}

    private Logger() {/* do nothing */};

    public static void logError(Class clazz, String msg) {
        log(Level.Error, clazz, msg, null);
    }

    public static void logWarn(Class clazz, String msg) {
        log(Level.Warn, clazz, msg, null);
    }

    public static void logFatal(Class clazz, String msg) {
        log(Level.Fatal, clazz, msg, null);
    }

    public static void logInfo(Class clazz, String msg) {
        log(Level.Info, clazz, msg, null);
    }

    public static void logDebug(Class clazz, String msg) {
        log(Level.Debug, clazz, msg, null);
    }


    public static void logError(Class clazz, String msg, Throwable throwable) {
        log(Level.Error, clazz, msg, throwable);
    }


    public static void logWarn(Class clazz, String msg, Throwable throwable) {
        log(Level.Warn, clazz, msg, throwable);
    }

    public static void logFatal(Class clazz, String msg, Throwable throwable) {
        log(Level.Fatal, clazz, msg, throwable);
    }

    public static void logInfo(Class clazz, String msg, Throwable throwable) {
        log(Level.Info, clazz, msg, throwable);
    }

    public static void logDebug(Class clazz, String msg, Throwable throwable) {
        log(Level.Debug, clazz, msg, throwable);
    }

    private static void log(Level level, Class clazz, String msg, Throwable throwable) {
        String message = String.format("[%s] : %s", clazz, msg);
        switch (level) {
            case Info:
                logger.info(message, throwable);
                break;
            case Warn:
                logger.warn(message, throwable);
                break;
            case Error:
                logger.error(message, throwable);
                break;
            case Fatal:
                logger.fatal(message, throwable);
                break;
            default:
            case Debug:
                logger.debug(message, throwable);
        }
    }

}
like image 26
Ahmad Al-Kurdi Avatar answered Oct 03 '22 04:10

Ahmad Al-Kurdi