Java: Can you expose 3rd party interface from your own class - java

We’re using log4j2 to do logging throughout our application and now I want to add some additional functions to the LogManager…at the same time, I hoped it would be possible to hide the “implementation details” of the LogManager for the rest of the application, so that instead of importing the log4j2 Logger everywhere, I can expose my own interface or class, from my own proprietary LogManager (that way, it would be possible to refactor or replace the way I store log messages without affecting the entire application).
I can create my own LogManager, called LM, easily like this:
package com.xxx.yyy.logging;
import org.apache.logging.log4j.LogManager;
public class LM extends LogManager {
…add own methods here…
}
But when I call:
LM.getLogger(Application.class)
It returns an object of type org.apache.logging.log4j.Logger – is there an easy way to “wrap and expose” this interface via my own package, so that the rest of the application don’t have to be concerned with log4j?
I’ve tried something like:
package com.xxx.yyy.logging;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.message.MessageFactory;
public class LMlogger extends org.apache.logging.log4j.core.Logger implements Logger {
protected LMlogger(LoggerContext context, String name,
MessageFactory messageFactory) {
super(context, name, messageFactory);
// TODO Auto-generated constructor stub
}
};
…in order to implement the class returned as well as the expected interface, but still I can’t “down-cast” the returned Logger-object to my own LMlogger (which makes sense, as my class is the sub-class). But is there another way to keep the log4j2 implemenation details in one place only, without having to wrap each and every method of the Logger-class?

You can use the tool that log4j2 provides to generate custom Logger wrappers.
This tool was intended to add convenience methods for custom log levels or hide existing log levels, but you can use it for any purpose.
It also hides the LogManager from the client code (your app), and the generated code is in whatever package you specify, so client code won't be aware it is using log4j2.
You may need to regenerate the wrapper when you upgrade log4j2 after it had API changes (which is rare, but there will be additional API in 2.6).

Look at the following way:
Create a same-name Class org.apache.logging.log4j.LogManager in your project, and copy the source code of the original org.apache.logging.log4j.LogManager in log4j lib. Then edit the code and add what you want.
Logger or other class in the same way.
But you must make sure that your project must be loaded before the log4j lib.

Related

Static Context Configuration for Logback Appenders

I've found a few examples (even on Stack Overflow) of some programmatic configuration of Logback logging appenders, but as much as I've incorporated into my own setup hasn't worked for me so far. Some examples produce an actual Logger instance, but considering I've already got a Logger being statically instantiated within my class, I want to be able to programmatically enable an Appender that I've defined for unit testing purposes.
Here is my custom appender:
package org.example.logging;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import java.util.ArrayList;
import java.util.List;
// Credit to https://stackoverflow.com/a/29077499/5476186
public class TestAppender extends AppenderBase<ILoggingEvent> {
private static List<ILoggingEvent> events = new ArrayList<>();
#Override
protected void append(ILoggingEvent e) {
events.add(e);
}
public static List<ILoggingEvent> events() {
return List.copyOf(events);
}
public static void clear() {
events.clear();
}
}
And in my testing code, I'm trying to configure my TestAppender to "kick in" so that, after invoking this method in my test setup, I can capture the logs and validate them:
package org.example.logging;
import ch.qos.logback.classic.LoggerContext;
import org.slf4j.LoggerFactory;
// ...
// Mostly modeled after https://stackoverflow.com/a/7825548/5476186
private static void startAppender() {
LoggerContext logCtx = (LoggerContext) LoggerFactory.getILoggerFactory();
TestAppender appender = new TestAppender();
appender.setContext(logCtx);
appender.setName("TEST");
// I was hoping this would statically allow the appender to kick in,
// but all of the examples then attach this appender to a Logger instance.
appender.start();
}
Obviously, this isn't working for me. So I guess I have two contingent questions.
Is this possible and, if so, how can I make it work?
If this is not possible, what's the cleanest way to accomplish what I'm trying to do? (Enable/disable appenders during testing without having to manually mess with a config file.)
In one of the threads linked above, I found this answer which looks like one possible solution is to modify the text in the configuration file and to force a reload, but that doesn't seem super clean to me. Another option would be to create my own wrapper Logger factory which I could use to provide loggers with my TestAppender during test execution with dependency injection. I'll probably be creating a wrapper anyway, even though I'm using SLF4J.
Side note: I know that my test code as currently written is pretty tightly coupled with Logback instead of SLF4J, so I'm open to criticism/advice on that issue, too.
If you're using slf4j in your production code, then there is already a project that can help in testing: Its called slf4j-test
In a nutshell, it provides an API to retrieve a "test logger" in the test that will keep all the logged messages in memory so that you'll be able to verify them.
So that you:
Execute a method that logs something
Retrieve a test logger
call getLoggingEvents() on the test logger and verify the logged events
The link that I've provided contains an example of the API as well as maven integration example.
If, alternatively you would like to use logback directly for the tests or something, there is already a ListAppender shipped as a part of logback distribution that allows retrieval of events that have passed through the appender. You can add it programmatically to the logger and use inside the test.
Here you can find a comprehensive example of doing that

How SLF4J/ JPA / JAX-RS find their implementation?

I'm learning Java and I find that there are many functionalities that are standardized :
logging (using SLF4J)
Persistence (using JPA)
REST (using JAX-RS)
SOAP (using JAX-WS)
etc.
Let's take the Sl4j example : to use it correctly with log4j, we have to import the sl4j api, the sl4j/log4j bridge and the log4j implementation.
Question : In my class, I only communicate with the Slf4j API.
How my application knows about the log4j implementation ?
Can someone explains what's happening exactly under the hood ?
Regards
The OP asks a general question about how implementation is injected in some different cases.
Logging
As sated in many answers, the SLF4J gives the interface and log4j-slf4j gives the implementation.
When you use the following statement:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
...
private static final Logger LOG = LoggerFactory.getLogger(FooBarClass.class);
...
LOG.debug("Foobar");
This is what is Happening:
We try to get the Logger from the getLogger method declared in the LoggerFactory class :
public static ILoggerFactory getILoggerFactory() {
if (INITIALIZATION_STATE == UNINITIALIZED) {
synchronized (LoggerFactory.class) {
if (INITIALIZATION_STATE == UNINITIALIZED) {
INITIALIZATION_STATE = ONGOING_INITIALIZATION;
performInitialization();
}
}
}
switch (INITIALIZATION_STATE) {
case SUCCESSFUL_INITIALIZATION:
return StaticLoggerBinder.getSingleton().getLoggerFactory();
}
...
}
So the magic happens at that statement:
return StaticLoggerBinder.getSingleton().getLoggerFactory();
Because the classpath knows you implemented why, the StaticLoggerBinder implementation is provided by log4j.
As we can notice, log4j provides a with its own implementation:
private final ILoggerFactory loggerFactory;
...
private StaticLoggerBinder() {
loggerFactory = new Log4jLoggerFactory();
}
And that's it !
Persistence
For JPA/Hibernate part, you have to include hibernate-jpa-api and hibernate-* (core, entitymanager, etc).
Let's say you want to create an EntityManagerFactory:
import javax.persitence.EntityManagerFactory
import javax.persitence.Persistence;
...
private static EntityManagerFactory EMF = Peristence.createEntityManagerFactory("foobar", null);
As for List and ArrayList, your classpath is fed with the interface and the implementation thanks to the JARs you import.
The EntityManagerFactory comes from the hibernate-jpa-api where we have a Persistence class.
We can notice that the createEntityManagerFactory method first lists all the providers and for each one of them, an createEntityManagerFactory is fired.
This is where the hibernate comes. It provides an HibernatePersistenceProvider that implements the PersistenceProvider class.
This is how Hibernate is injected.
Slf4j can be used with log4j or any other underlying logging library.
In case of log4j, it uses log4j-slf4j-impl.jar which contains necessary classes for communicating with log4j library.
As per the documentation -
SLF4J doesn't resolve the logging implementation at execution, but
directly at the compilation with a bridging API. So more than the JAR
of SLF4J you need the following JARs : the bridging JAR and the JAR of
the implementation. Here is what you get with Log4J :
If you are talking about dealing with slf4j loggers, like:
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(FooClass.class);
then it is pretty simple: org.slf4j.Logger is just an interface, which has several implementations. In case of usage library slf4j-log4j12, this interface is implemented by class org.slf4j.impl.Log4jLoggerAdapter which internally contains
final transient org.apache.log4j.Logger logger;
So it is simple adapter which wraps your logging requests and invoke them on log4j logger object:
public void debug(String msg) {
logger.log(FQCN, Level.DEBUG, msg, null);
}
More specifically, proper Logger implementation is produced by LoggerFactory which firstly creates Log4jLoggerFactory via
StaticLoggerBinder.getSingleton().getLoggerFactory()
, latter creates needed Log4jLoggerAdapter instance.
Generally it works via adaptation level like pictured on img from documentation:
The SLF4J manual refers to how under the hoop SLF4J finds the implementation to use : Binding with a logging framework at deployment time.
SLF4J refers the thing that allows to use an implementation (Logback, Log4J, etc...) as "SLF4J bindings" :
As mentioned previously, SLF4J supports various logging frameworks.
The SLF4J distribution ships with several jar files referred to as
"SLF4J bindings", with each binding corresponding to a supported
framework.
You have as many SLF4J bindings as implementations of SLF4J.
And of course, an implementation API may have distinct "SLF4J bindings" according to its version :
To switch logging frameworks, just replace slf4j bindings on your
class path. For example, to switch from java.util.logging to log4j,
just replace slf4j-jdk14-1.7.22.jar with slf4j-log4j12-1.7.22.jar.
The binding with the implementation is not performed at runtime but at compile-time : each SLF4J binding is hardwired at compile time to use one and only one specific logging framework.
So, you have just to include the SLF4J binding in the classpath (for example slf4j-jdk14-1.7.22.jar) so that SLF4J uses it :
SLF4J does not rely on any special class loader machinery. In fact,
each SLF4J binding is hardwired at compile time to use one and only
one specific logging framework. For example, the
slf4j-log4j12-1.7.22.jar binding is bound at compile time to use
log4j. In your code, in addition to slf4j-api-1.7.22.jar, you simply
drop one and only one binding of your choice onto the appropriate
class path location. Do not place more than one binding on your class
path. Here is a graphical illustration of the general idea.
That's why it is generally advised to never place more than one SLF4J binding on the classpath as SLF4J is not designed to choose the implementation at runtime.

How to remove log calls in J2SE/J2EE application (not Android)

I know that removing logger calls with Proguard works for Android applications.
How can one accomplish this in standard Java application?
import java.util.logging.Logger;
public class Clazz {
private static final Logger LOGGER = Logger.getLogger(Clazz.class.getName());
public void foo() {
LOGGER.info("bar");
}
}
in my Proguard configuration I have the following:
-assumenosideeffects class java.util.logging.Logger { *; }
-whyareyoukeeping class java.util.logging.Logger
which gives the following output when running:
[proguard] java.util.logging.Logger
[proguard] is a library class.
I understand that it's a library but I want to strip all calls to it anyway. Is this possible with Proguard? If not, why? How come this works so conveniently for Android, does the logger field or lack of it have something to do with this?
You should be able to remove logging calls like this, assuming you haven't disabled optimization -- it's the optimization step that removes unnecessary and unwanted calls. ProGuard can't remove the Logger class itself, since it is a run-time library class, as you've seen.
You mustn't use a wildcard for matching the methods though, since this includes essential methods like wait() and finalize() (affecting all classes). You'll have to enumerate the methods that you want to remove. For instance:
-assumenosideeffects class java.util.logging.Logger {
void info(java.lang.String);
}

SLF4J in distributable library, how to obtain Logger

I want to distribute a lib relying on the SLF4J logger interface. What is the best practice way to obtain the logger which integrate nicely into any other project? Sorry for the unstructured question style, I'm still trying to figure out how all this stuff is glued together.
In other projects I always use this piece of code, because I want to obtain a custom logger:
private final static Logger LOGGER = LoggerFactory.getILoggerFactory().getLogger(NAME_OF_APP);
If I create the class org.slf4j.impl.StaticLoggerBinder and have it some other lib, does the therein defined factory get used even if I just call LoggerFactory.getLogger(NAME_OF_APP) or is some default slf4j factory used?
I want the user to be able to use his own factory and logger, so which way is to perfere, and most of all why?
I'm not sure I fully understand what you are trying to do.
SLF4J is composed of two parts. First the API which you use in your lib to code your logging calls. And secondly the implementation which you use during your development to do logging, but DO NOT set as a dependency of the lib.
Because SLF4J looks for the implementations on the class path the developers using our lib can simple include any implementation they want. Sometimes is some quite strange ways :-) They can use a range of prebuilt implementations or code their own. It's up to them.
I don't think you need to do anything more than just use SLF4J's API as is.
From http://slf4j.org/manual.html
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HelloWorld {
public static void main(String[] args) {
Logger logger = LoggerFactory.getLogger(HelloWorld.class);
logger.info("Hello World");
}
}
So, always use LoggerFactory.getLogger(...). The argument allow the logger backend to determine the behavior of the logger returned to you.
I am not sure I fully understand what your scenario is.
But from my viewpoint, what you want is a distributed logging component.
A simple approach to do that is a socket appender. And a full feature component for distributed logging may like Facebook's scribe.
Use Logger static wrapper from jcabi-log:
import com.jcabi.log.Logger;
public class MyLibraryClass {
public void foo() {
Logger.info(this, "some information");
}
}
All logs will be sent through SLF4J.

In java how do you refer to a class that is in the default package of a third party library?

I have downloaded a third party library and they have classes I need to refer to in the default package? How do I import these classes?
It's not possible directly with the compiler. Sun removed this capability. If something is in the default namespace, everything must be in the default namespace.
However, you can do it using the ClassLoader. Assuming the class is called Thirdparty, and it has a static method call doSomething(), you can execute it like this:
Class clazz = ClassLoader.getSystemClassLoader().loadClass("Thirdparty");
java.lang.reflect.Method method = clazz.getMethod("doSomething");
method.invoke(null);
This is tedious to say the least...
Long ago, sometime before Java 1.5, you used to be able to import Thirdparty; (a class from the unnamed/default namespace), but no longer. See this Java bug report. A bug report asking for a workaround to not being able to use classes from the default namespace suggests to use the JDK 1.3.1 compiler.
To avoid the tedious method.invoke() calls, I adapted the above solution:
Write an interface for the desired functionality in your desired my.package
package my.package;
public interface MyAdaptorInterface{
public void function1();
...
}
Write an adaptor in the default package:
public class MyAdaptor implements my.package.MyAdaptorInterface{
public void function1(){thirdparty.function1();}
...
}
Use ClassLoader/Typecast to access object from my.package
package my.package;
Class clazz = ClassLoader.getSystemClassLoader().loadClass("MyAdaptor");
MyAdaptorInterface myObj = (MyAdaptorInterface)clazz.newInstance();
myObj.function1();

Categories

Resources