# 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);
	}
	// ...
}

Use a Java Refactoring Tool

No license required

You can review this refactoring on your code without a license by installing jSparrow to your Eclipse IDE. Install the plug-in from Eclipse IDE: Eclipse Marketplace.

System-wide Refactoring

Do you want to automate this refactoring (and many more) to your system-wide code? The automatic application of this system-wide refactoring can be unlocked by acquiring your jSparrow license.

a drawn cute bird pointing at a graph that shows positive results

# Properties

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