# 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:

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:

Drag to your running Eclipse* workspace. *Requires Eclipse Marketplace Client

Need help? Check out our installation guide.

# Properties

Property Value
Rule ID ReplaceWrongClassForLogger
First seen in jSparrow version 4.13.0
Minimum Java version 1.1
Remediation cost 5 min
Links