This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
I want to set up a logger that writes to one file from many different java files. I just want to user the Logger class for now as I think thats all I need for my program.
How would I change the above code so that I can use myLogger in a different java file but still in the same package? Also I want to be able to log messages from within static and non-static methods which is where I�m having the trouble at the moment.
I believe your problem can be solved by using Singleton pattern. You have to wrap your myLogger object in a Singleton class. Hence, you will use your logger wrapper in any part of any class in your application, and will output the log message into one file.
You can use your wrapper in any part of any class in your application like this:
You should move the config of the destination log file, level, formatter etc out to log4j.properties for easier maintenance. You can specify where it is using JVM arg -Djava.util.logging.config.file=mylogging.properties.
You can create another instance of Logger in another class and just use that, you dont need to use the same instance. For example:
Then, depending on what level you have specifed out in the properties file (default is INFO unless changed), some, none or all of the above log messages will appear.