# Replace Wrong Class for Logger
# Description
A conventional way of initializing a logger for a certain class is the use of a factory method. Examples of common factory methods are:
- org.slf4j.LoggerFactory.getLogger(Class<?>)(opens new window) to create a- org.slf4j.Logger(opens new window).
- org.apache.logging.log4j.LogManager.getLogger(Class<?>)(opens new window) to initialize a- org.apache.logging.log4j.Logger(opens new window)
- java.util.logging.Logger.getLogger(String)(opens new window) returning a- java.util.logging.Logger(opens new window).
If a given logger is initialized with a class which is different from the class where it is declared, then this rule will replace the wrong initialization argument with the correct one. For example, if a logger for the class Employee is initialized with User.class, then the argument of the initialization will be replaced by Employee.class.
# Benefits
This rule removes misleading logging messages.
# Tags
# Code Changes
# Using org.slf4j.Logger
Pre
//...
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
//...
public class Employee extends User {
	static final Logger LOGGER = LoggerFactory.getLogger(User.class);
	// ...
}
Post
//...
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
//...
public class Employee extends User {
	static final Logger LOGGER = LoggerFactory.getLogger(Employee.class);
	// ...
}
# Using org.apache.logging.log4j.Logger
Pre
//...
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
//...
public class Employee extends User {
	static final Logger LOGGER = LogManager.getLogger(User.class);
	// ...
}
Post
//...
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
//...
public class Employee extends User {
	static final Logger LOGGER = LogManager.getLogger(Employee.class);
	// ...
}
# Calling Logging Method on java.util.logging.Logger.getLogger
Pre
//...
import java.util.logging.Logger;
import java.util.logging.Level;
//...
public class Employee extends User {
	// ...
	void logInfo(String message) {
		Logger.getLogger(User.class.getName()).log(Level.INFO, message);
	}
	// ...
}
Post
//...
import java.util.logging.Logger;
import java.util.logging.Level;
//...
public class Employee extends User {
	// ...
	void logInfo(String message) {
		Logger.getLogger(Employee.class.getName()).log(Level.INFO, message);
	}
	// ...
}
🛠️ Auto-refactor Available
You can auto-refactor this with jSparrow. 
 Drop this button to your Eclipse IDE workspace to install jSparrow for free: 
Need help? Check out our installation guide.
