0

After a lot of attempts, I have am finally able to formulate a question. I hope it makes some sense and is easy to understand. Working on a web-application that uses Spring and Jersey. I am required to implement an application-wide logger that should log all the activities performed on the application into a database. For the time being I have used the HAS-A implementation and called the logging method everywhere a CRUD operation is performed. Something like this:

LogBean lBean=new LogBean("rickesh@email.com","update","address","127.0.0.1");
logToDatabase(lBean);

But this causes a lot of repeated lines of code and I have to repeatedly keep instantiating and calling the log method every section the CRUD operation in performed. Is there any way I can pull out the logging from the controller layer, the REST layer? Are there any specific functionality in Spring or Jersey with which I can perform logging on a separate layer and I don't have to keep repeating the same lines of code everywhere. Please advice.

Mono Jamoon
  • 4,437
  • 17
  • 42
  • 64

2 Answers2

6

If you are getting messy with writing your logs you should look into AOP. If you are already using spring you should read about Spring AOP, and for logging per se, read using Spring AOP for logging

Community
  • 1
  • 1
Chen Harel
  • 9,684
  • 5
  • 44
  • 58
1

AOP is a better way but if getting to learn it to resolve this issue is going to take longer then here is a simple alternative.

  1. Add log4j JAR to your WebApp. Make sure, log4j version bundled in your WebApp doesn't conflict with the version already with your Application Server
  2. Place a log4j.xml for FILE and CONSOLE appendars in your class path (src/main/resources)
  3. There is a Log4JConfigureListener provided by Spring which you can declare under section in your web.xml
  4. Additionally, if too much log is generated, you can limit the output of the loggers via either log4j.xml in your application to certain packages only or via using Root logger configuration for your project specific packages. For example, in JBoss you can add a "category" for a package at a specific LOG level

Your specific "separate layer" should have a separate and distinct package name to target the log appendars for that layer Hope this helps!

Horizon
  • 548
  • 3
  • 7