Java logging interface - java

If I've to distribute a certain framework like a customized validation framework which can be used in many projects, how do I handle logging within this framework so that it uses the same logging method as the project in which it is being used? i.e I've written a logger interface with the usual debug,warn,info... methods and the implementation of this interface can implement those methods using log4j or any other logging methods. If I distribute this as a jar, how can different projects use this jar with their logging framework?

I would strongly suggest that instead of writing yet another logging framework you recode your application to use the SLF4J logging API instead. All the work of interfacing to other logging implementations have been done, and is well known in the industry.
An added benefit is that you get {}-placeholders, which allow you to just do
log.debug("a={}, b={}", a, b);
and the a.toString() and b.toString() are only called when the string will actually be logged. This allows for a lot of log statements which will not actually be executed unless you need them to run in a debug setting.

There are some libraries that provide an abstraction layer over log4j, java.util.logging etc. They act as the 'interface' and then the person using your project can use the implementation of their choosing. Have a look at Apache Commons Logging and SLF4J.

Related

Bridge for logging systems

I'am developing simple Java event library and I want to support more than one logging system.
I have an idea with using own class named LoggerBridge.
public void setLogger(LoggerBridge bridge){
}
public class LoggerBridge{
public void log(Level, String){}
...
}
But this solution is not practical at all, is there some other option how to achieve this result ?
Some bridge, which it supports all types of logging system ?
This is an age old problem and several logging facades were made to allow you to log things in for example libraries, without forcing the user to use the same logging framework you chose (or try to make multiple logging frameworks work nicely together).
One of the earliest ones was commons-logging which is considered outdated these days, but there are a lot of older libraries that use it. It can be bridged to your actual logging system (see below).
Newer ones include SLF4J. These should be used when you're writing a library, so you'd be programming to the SLF4J API instead of an actual logging implementation.
A logging bridge is when you have a library that uses for example log4J, but your other code is using let's say SLF4J with Logback (a quite common combination). The bridge "fakes" being the log4J library, when it actually just redirects the logging to your SLF4J+Logback combination.

slf4j mechanism of loading its impl

When you use slf4j and want to use it with log4j, you just put the log4j jar file in classpath and without any configuration slf4j understand it's impl.
How slf4j do that? what is the mechanism here?
First let me clarify a few points:
SLF4J defines a standard logging API (harder than you'd think if the number of logging APIs are anything to go by).
while there can be many implementations of SLF4J, the common one is Logback.
historically there has been several attempts at logging APIs, these logging APIs have in turn have been used by other APIs you may use in your project - for example Spring usings Commons Logging.
It this last point that's important. Within a project you may use a number of 3rd party APIs each of which use one of the popular logging APIs (Log4J, Commons, JDK, etc). This is a pain because you have to configure each individually.
The solution is to use SLF4J, which provides reimplementations for the legacy logging APIs, which delegate to SLF4J. Hence when whichever 3rd party APIs you use makes a logging call, that call is delegated to SLF4J by the SLF4J implementation of a particular logging API.
And so the mechanism being used is delegation combined with the fact that Java inherently uses the first class it loads from the classpath (in this case the reimplementation of a particular logging API). So as long as the Logging classes in the reimplementation match the definition the calling code was compiled against, the calling code is none the wiser.

(Java SE/Android) cross platform logging

I want this library I'm working on to have logging support, but Android and SE have their own ways of logging. In SE you can use System.out.println methods or the java.util.logging.Logger class. Android uses android.util.Log to log on logcat. At first I used reflection to check if android was usable, then reflectively call the log methods in Log.class; but that wasn't a good idea.
My solution is to have the developers using my library handle logs themselves. There will be a Handler interface they set and has an onLog method
public void onLog(int level, String tag, String msg);
The library will call the onLog method on the handlers in my custom Logger class. Is it a good idea to have developers handle the logs instead of the library itself? Seems to be the best solution so far and if I document it good then it should't be an issue.
I agree with you that logging should be delegated to clients, and your homegrown approach is indeed sensible.
IMO, the SLF4J facade would be ideal for your situation. Your library would include the slf4j-api jar and contain SLF4J logging statements. If clients wanted logging, they'd just drop in a logging backend (and an optional config file) into their application's classpath to capture/view your log statements.
The advantages to this approach are that it grants clients the most control with zero coding required to get logging; and that it allows the client to choose among many available backends.
I would use logback as the backend for J2SE apps and logback-android for Android.
You can try microlog
http://code.google.com/p/microlog4android/
It can help you use a consistent logging mechanism across android and java. If you use slf4j, it can be used as a wrapper both for microlog (in case of your android project) and log4j (for your java projects)

How to decouple logging implementation and API?

I'm creating a small Java framework, which will log its events. I don't want the framework to be dependent on any particular logging implementation (jul, commons logging, log4j, slf4j, logback, etc). Instead, I want to allow my clients to choose anything they prefer.
The question is - how should I realize such decoupling? How my framework should log its events?
slf4j is designed to solve exactly this problem: it decouples the API from the logging implementation.
slf4j is not a logging implementation by itself. It depends on the existence of a back-end implementation. Logback just happens to natively implement the slf4j API but there are bindings for log4j, java.util.Logging and others.
At some level you must have an API for your clients to use. You might as well make it one of the existing APIs rather than writing your own.
I think that will be difficult to achieve as your code must call something in order to log information and error messages. I think you will have to choose one (I recommend slf4j) and stick to it - this seems to be what is generally done by everyone else.
I would include support for AspectJ and Commons Logging.

Difference in using java.util.logging and Log4j Loggers

I am developing a java application for which i have to use a logging mechanism. And now i am confused to choose either java libraries logger or to go for Log4j logger.
So i want to know when i can go for java logger
and when i can go for log4j logger.
I'd suggest you go with SLF4J instead to decouple your application from specific logging frameworks. It has adapters for various popular logging frameworks such as Jakarta Logging, JDK1.4 logging, log4j etc. making it a good abstraction for logging needs.
Logger class was not part of jdk earlier on, so several library implementations sprung up. The Log4j library has one of the most comprehensive set of logging utilities (Formatters, Appenders etc). However, for most developers this would be an overkill and the simple java.util.Logger would suffice.
I personally use a custom wrapper over my logger implementation. This enables me to define custom calls to carry out functional logging/auditing.
There are the Apache Commoms Logging project and SLF4J, either of which abstracts the underlying logging library.
In practice I tend to use Log4J over the built in logging classes. Mainly because Log4J can be configured per web-app in an application server, whereas JDK logging is configured per JVM.
The approach I would currently recommend is to use SLF4J as the logging API. You can then pick your logging framework depending on your needs as you discover them.
I did a writeup on what I consider to be best practice in getting started with SLF4J and a simple "log to System.out" which is currently placed at. http://runjva.appspot.com/logging101/index.html
Hopefully it is helpful.
I find Log4j more flexible when it comes to tweaking the logging cfg without re-compiling code in production environment.

Categories