The reason you have multiple logger instances is because you want them to behave different when logging (usually by printing out the class name they are configured with). If you do not care about that, you can just create a single static logger instance in a class and use that all over the place.
为了形成单一记录,你可以简单地建立一个固定的通用记录类别,作为单一点记录,因此,如果我们需要改变记录包,你将只更新这一类别。
final public class Logger {
private static final org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger("Log");
enum Level {Error, Warn, Fatal, Info, Debug}
private Logger() {/* do nothing */};
public static void logError(Class clazz, String msg) {
log(Level.Error, clazz, msg, null);
}
public static void logWarn(Class clazz, String msg) {
log(Level.Warn, clazz, msg, null);
}
public static void logFatal(Class clazz, String msg) {
log(Level.Fatal, clazz, msg, null);
}
public static void logInfo(Class clazz, String msg) {
log(Level.Info, clazz, msg, null);
}
public static void logDebug(Class clazz, String msg) {
log(Level.Debug, clazz, msg, null);
}
public static void logError(Class clazz, String msg, Throwable throwable) {
log(Level.Error, clazz, msg, throwable);
}
public static void logWarn(Class clazz, String msg, Throwable throwable) {
log(Level.Warn, clazz, msg, throwable);
}
public static void logFatal(Class clazz, String msg, Throwable throwable) {
log(Level.Fatal, clazz, msg, throwable);
}
public static void logInfo(Class clazz, String msg, Throwable throwable) {
log(Level.Info, clazz, msg, throwable);
}
public static void logDebug(Class clazz, String msg, Throwable throwable) {
log(Level.Debug, clazz, msg, throwable);
}
private static void log(Level level, Class clazz, String msg, Throwable throwable) {
String message = String.format("[%s] : %s", clazz, msg);
switch (level) {
case Info:
logger.info(message, throwable);
break;
case Warn:
logger.warn(message, throwable);
break;
case Error:
logger.error(message, throwable);
break;
case Fatal:
logger.fatal(message, throwable);
break;
default:
case Debug:
logger.debug(message, throwable);
}
}
}