Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intercept Log Messages slf4j

I have an application which uses slf4j as the logging facade. Now I would like to intercept all the error messages before the transfer is handed out to the underlying logging system. Is it possible to do that for slf4j? I looked through the documentation and see that we can change the Appenders in the implementation (like log4j) to achieve this but can we do this at the facade level itself? The intercept does basic stuff like incrementing a global counter for the number of error messages etc.

like image 999
user1916312 Avatar asked Dec 19 '12 15:12

user1916312


People also ask

Which is better log4j or SLF4J?

Comparison SLF4J and Log4j Unlike log4j, SLF4J (Simple Logging Facade for Java) is not an implementation of logging framework, it is an abstraction for all those logging frameworks in Java similar to log4J. Therefore, you cannot compare both. However, it is always difficult to prefer one between the two.

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 use Commons Logging?

SLF4J based implementation of commons-logging wrapper APIs.

How do you change the log level in SLF4J?

When using log4j, the Logger. log(Priority p, Object message) method is available and can be used to log a message at a log level determined at runtime. We're using this fact and this tip to redirect stderr to a logger at a specific log level. slf4j doesn't have a generic log() method that I can find.


1 Answers

There is nothing for doing this in the SLF4J API.

But if your logger is Logback you can do it using a Filter like TurboFilter.

If you're not using Logback you'll probably need something like an AspectJ interceptor.

like image 60
proactif Avatar answered Sep 24 '22 05:09

proactif