Reputation: 7665
I have a common jar file that is used as underlying library for multiple other project,
Each project uses different type of logging (one uses log4j, one uses log4j2, one uses file logging, other use DB table logging)
I want to create a interface so every project will implement the common jar and use its own method of logging
So in the common jar I will write:
commonLog.log(level, message);
Then implement the method in other projects and channel the message to the right place.
How to go about designing a solution to this problem?
update
because I don't want anything fancy or additional libraries
I was thinking about something like this:
public interface CommonLogger {
CommonLogger getLogger(final Class<?> clazz);
public void Log(Level level,String message);
public void Log(Level level,String message,Throwable t);
}
then in other projects:
public class DBLogger implements CommonLogger {
@Autowired
DbOperations dao
Class<?> clazz;
private CommonLogger DBLogger(Class<?> clazz) {
this.clazz =clazz;
}
public CommonLogger getLogger(final Class<?> clazz){
return DBLogger(clazz);
}
public void Log(Level level,String message) {
dao.insertAudit(new Date(),clazz.getName(),level,message);
}
public void Log(Level level,String message,Throwable t) {
dao.insertAudit(new Date(),clazz.getName(),level,message + t.getMessage());
}
}
and log4j2 one:
public class Log4j2Bridge implements CommonLogger {
private static Logger logger;
Class<?> clazz;
public CommonLogger getLogger(final Class<?> clazz){
logger = LogManager.getLogger(clazz);
return this;
}
public void Log(Level level,String message) {
logger.log(level,message);
}
public void Log(Level level,String message,Throwable t) {
logger.log(level,message,t);
}
}
But how to get the instance inside the common log?
CommonLogger logger = CommonLogger. getLogger?
Upvotes: 0
Views: 2865
Reputation: 931
There are already solutions for this. popular logging libraries implements bridges which redirect logs from one library to another.
There is Java Common Logging which meant for your use case, and there is also others like slf4j which have bridges for a lot of common logging libraries including the java primitive logger from java.util.logging
slf4j
In your common library use the library like any other logging library:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Example {
final Logger logger = LoggerFactory.getLogger(Example.class);
public Example() {
logger.debug("Example class created");
}
}
Then in the project which uses the library, bind the slf4j to the specific logging library implementation which the project uses, by adding the fitting bridge:
for example for log4j 1.2 in maven:
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.8.0-beta4</version>
</dependency>
Upvotes: 3