Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement Custom Logger with slf4j

Tags:

java

slf4j

I want to implement a Custom logger which logs all log entries to a Database. Currently my app logs this way (slf4j and log4j binding):

private static final Logger logger = LoggerFactory.getLogger( MyClass.class ); 

I'm not sure how to proceed. My Idea is to implement a Custom Logging binding through implementing the org.slf4j.Logger Interface

What would be the next steps? My target is to not change the current code

Links I considered:

  • Java custom logger: logging standards or/and best practices
  • http://www.slf4j.org/manual.html
like image 620
Martin Dürrmeier Avatar asked Apr 16 '10 14:04

Martin Dürrmeier


People also ask

Can we use SLF4J instead of log4j?

Conclusion. So essentially, SLF4J does not replace Log4j, Both work together. SLF4j removes the tight coupling between the application and logging frameworks. It makes it easy to replace with any other logging framework in the future with a more capable library.

Does SLF4J support Log4j2?

log4j-slf4j-impl. jar – Log4j 2 SLF4J binding. It allows applications coded to the SLF4J API to use Log4j2 as the implementation.


2 Answers

it should be fairly easy. you'll need to implement your own Logger and LoggerFactory. you will not have to change existing code at all.

after doing that you'll need to implement StaticLoggerBinder to return your logger factory and class name. if you download the slf4j zip file then you get the source for all the implementations too, just have a look at the StaticLoggerBinder in slf4j-log4j for an example.

have a look at this link for details : http://www.slf4j.org/faq.html#slf4j_compatible

like image 158
chris Avatar answered Sep 22 '22 04:09

chris


You do not have to write your own logging implementation, how about switching the logging framework to logback? Loback supports logging to database natively. As you use the SLF4J API both times your code won't change.

Take a look at the ch.qos.logback.classic.db.DBAppender. If the default table layout does not fit your needs, you can implement ch.qos.logback.classic.db.names.DBNameResolver to customzie the table and coloum names.

like image 30
Matthias B Avatar answered Sep 21 '22 04:09

Matthias B