Java Hack: How to use Log4j in jar applications
There is no doubt how important is the logs for a production grade application. Operational problems can be avoided and business decisions can be improved by collecting and analyzing adequate logs.
Recently I’ve been working on a Java project where I had to use the jSMPP library. Two of it’s dependencies are SLF4J and Log4J. Though it can work without then just fine for development, but as I got used to the library the uncool warning messages started to bother me. So I went there to add them in the dependencies. It is needed to mention here SL4J just provides a facade where Log4J does all the heavy lifting.
The first thing I noticed that it’s a bit tricky to configure Log4J. By default it takes its configurations from a log4j.properties file which basically looks like this:
My first challenge was to find the sweet spot of where should I put this file. I was reading tutorials and SO answers trying their suggestions finally what worked for me was to put the file in:
out/production/classes/
I think it is also needed to mention that I am using IntelliJ IDEA for my development. I would be much obliged if someone could point me out what was I doing wrong.
Anyway, after it worked out I did some more development and was ready to hand over so I made the .jar of the project and tried to run it and bam!!, same error appeared. What I think is placing the properties file in my specified location was a bit hacky, and may not got included in the jar.
After a bit research , this was my solution. I created a class Log4Jconfigurator which had a configure method. My inspiration was the Log4J’s BasicConfigurator class. I took the idea and made it work with my need. The BasicConfigurator had only the methods to print the logs in the console but I needed to do it both in the console and file. So my configurator looks like this:
You can see that its configure method takes a String logpath which is the file path where I want to write the log. In the line 16 you may set a different level like Info, Warn, Error, Debug etc. Finally I needed to call this from the main method:
String logpath = "/home/jonhdoe/logs/myproject.log";
Log4Jconfigurator.configure(logpath);
After this I can log nicely both in console and file and I can switch between them any moment. You may find it useful too when you have to use Log4J in your projects.
Happy coding.