java 从 log4j.Logger 获取 getLogger 的通用方式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10725402/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 02:16:07  来源:igfitidea点击:

Generic way of getLogger from log4j.Logger

javalog4j

提问by JavaSheriff

Instead of specifying the class name on each class:

而不是在每个类上指定类名:

log = Logger.getLogger(Foo.class);
log = Logger.getLogger(Bar.class);
log = Logger.getLogger(Test.class);

Will it be OK to use :

是否可以使用:

log = Logger.getLogger(this.getClass());

What will be the implications?

会有什么影响?

回答by matts

If you create a subclass, the log messages will get logged to the subclass's logger.

如果您创建子类,日志消息将被记录到子类的记录器中。

package pkgone;
public class SuperType {
    private Logger log = Logger.getLogger(this.getClass());
    public void someAction() {
        log.info("Doing something");
    }
}

.

.

package pkgtwo;
import pkgone.SuperType;
public class SubType extends SuperType {
    // for instances of SubType, the log object in SuperType
    // will get initialized with SubType's class object
}

.

.

// some code somewhere that uses SubType
SubType obj = new SubType();
obj.someAction();

In the above example, "Doing something" will get logged to the pkgtwo.SubType logger instead of pkgone.SuperType logger, which may or may not be what you want.

在上面的例子中,“做某事”将被记录到 pkgtwo.SubType 记录器而不是 pkgone.SuperType 记录器,这可能是也可能不是你想要的。

回答by davesbrain

Try this way to look up a generic class...

尝试这种方式来查找一个泛型类...

private static final Log LOGGER = Logger.getLogger(MethodHandles.lookup().lookupClass());

The best part is you can use this method statically.

最好的部分是您可以静态使用此方法。

回答by Sanghyun Lee

If you don't want to repeat to make the loggerand want to avoid write a wrong class name, there's @Logof Project Lombok.

如果您不想重复制作logger并希望避免编写错误的类名,则可以使用Project Lombok@Log

If you don't mind using one more library in your project, you can simply add a logger with a simple annotation.

如果你不介意在你的项目中使用更多的库,你可以简单地添加一个带有简单注释的记录器。

import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;

@Log
public class LogExample {    
  public static void main(String... args) {
    log.error("Something's wrong here");
  }
}

回答by ControlAltDel

Sure that seems fine.

当然,这看起来不错。

Be aware that one implication is that if you may have trouble using the log from a static context - It may not be initialized or it may not be visible

请注意,其中一个含义是,如果您在使用静态上下文中的日志时可能遇到问题 - 它可能未初始化或不可见

回答by Nirmalya Roykarmakar

public final class AppLogger {

公共最终类 AppLogger {

private AppLogger() {
}


public static final void logInfo(Class<?> clazz, String logMessage) {
    Logger logger = Logger.getLogger(clazz);
    if (logger.isInfoEnabled()) {
        logger.info(logMessage);
    }
}

public static final void logInfo(Class<?> clazz, String logMessage, Throwable th) {
    Logger logger = Logger.getLogger(clazz);
    if (logger.isInfoEnabled()) {
        logger.info(logMessage, th);
    }
}

}

}

Create this class and then add this to your calling class. Applogger.logInfo(Class.class,String var);

创建此类,然后将其添加到您的调用类中。 Applogger.logInfo(Class.class,String var);

回答by user2299528

+1 for sublass instances that call a super method, the logger will be the sub class.

+1 对于调用超级方法的子类实例,记录器将是子类。

Also if you are applying this as a logging template for your classes, if your class is abstract - your this.getClass will fail as you do not have an instance of this class.

此外,如果您将它用作类的日志记录模板,如果您的类是抽象类 - 您的 this.getClass 将失败,因为您没有此类的实例。

回答by Nelda.techspiress

Using log factory from Apache commons:

使用来自 Apache commons 的日志工厂:

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Logger;

public class SomeNewClass {
...
private final Log logger = LogFactory.getLog(this.getClass());
...
}

Don't have to do anything else. Not sure LogFactory was available at time of question post. If you don't want to use LogFactory you could also simply use private final with the getClass().

不必做任何其他事情。不确定 LogFactory 在发布问题时是否可用。如果您不想使用 LogFactory,您也可以简单地将 private final 与 getClass() 一起使用。

private final Logger log = Logger.getLogger(this.getClass()); 

No reason to create subclasses unless you want a heirarchy of your logging which could also be done with manipulation of the log configuration file (log4j.xml if that's what you are using). You just can't use this.getClass() when the logger is defined as static. Without static or private final you leave the logger open to dangerous possible changes which you don't want.

没有理由创建子类,除非您想要日志的层次结构,这也可以通过操作日志配置文件(如果您使用的是 log4j.xml)来完成。当记录器定义为静态时,您不能使用 this.getClass() 。如果没有 static 或 private final,您会让记录器对您不想要的危险可能的更改保持开放。

回答by Abdul Aleem

There is no implications as I know. As per Matt comment, I guess, thats the right behaviour which everyone wants it.

据我所知,没有任何影响。根据马特的评论,我想这是每个人都想要的正确行为。