Java记录器,自动确定调用者的类名

问题描述 投票:35回答:21
public static Logger getLogger() {
    final Throwable t = new Throwable();
    final StackTraceElement methodCaller = t.getStackTrace()[1];
    final Logger logger = Logger.getLogger(methodCaller.getClassName());
    logger.setLevel(ResourceManager.LOGLEVEL);
    return logger;
}

此方法将返回一个记录器,该记录器知道它正在记录的类。反对它的任何想法?

许多年后:https://github.com/yanchenko/droidparts/blob/master/droidparts/src/org/droidparts/util/L.java

java logging stack-trace
21个回答
15
投票

我想这会为每个课程增加很多开销。每个班级都必须“抬头”。你创建新的Throwable对象来做到这一点......这些扔掉的东西不是免费的。


2
投票

我更喜欢为每个类创建一个(静态)Logger(使用它的显式类名)。我比按原样使用记录器。


2
投票

您不需要创建新的Throwable对象。你可以打电话给Thread.currentThread().getStackTrace()[1]


1
投票

我在大多数班级的开头都有以下几行。

  private static final Logger log = 
     LoggerFactory.getLogger(new Throwable().getStackTrace()[0].getClassName());

是的,第一次创建该类的对象时会有一些开销,但我主要在webapps中工作,因此在20秒启动时添加微秒并不是真正的问题。


1
投票

Google Flogger日志记录API支持此功能,例如

private static final FluentLogger logger = FluentLogger.forEnclosingClass();

有关详细信息,请参阅https://github.com/google/flogger


0
投票

为什么不?

public static Logger getLogger(Object o) {
  final Logger logger = Logger.getLogger(o.getClass());
  logger.setLevel(ResourceManager.LOGLEVEL);
  return logger;
}

然后当你需要一个类的记录器时:

getLogger(this).debug("Some log message")

0
投票

这种机制在运行时付出了很多额外的努力。

如果您使用Eclipse作为IDE,请考虑使用Log4e。这个方便的插件将使用您最喜欢的日志框架为您生成记录器声明。在编码时花费更多的精力,但在运行时的工作量要少得多。


0
投票

除非你真的需要你的Logger是静态的,否则你可以使用

final Logger logger = LoggerFactory.getLogger(getClass());

0
投票

请参阅我的静态getLogger()实现(在JDK 7上使用相同的“sun。*”magic作为默认的java Logger doit)

  • 注意静态日志记录方法(使用静态导入)没有丑陋的日志属性... import static my.package.Logger。*;

它们的速度相当于本机Java实现(使用100万条日志跟踪进行检查)

package my.pkg;

import java.text.MessageFormat;
import java.util.Arrays;
import java.util.IllegalFormatException;
import java.util.logging.Level;
import java.util.logging.LogRecord;

import sun.misc.JavaLangAccess;
import sun.misc.SharedSecrets;


public class Logger {
static final int CLASS_NAME = 0;
static final int METHOD_NAME = 1;

// Private method to infer the caller's class and method names
protected static String[] getClassName() {
    JavaLangAccess access = SharedSecrets.getJavaLangAccess();
    Throwable throwable = new Throwable();
    int depth = access.getStackTraceDepth(throwable);

    boolean lookingForLogger = true;
    for (int i = 0; i < depth; i++) {
        // Calling getStackTraceElement directly prevents the VM
        // from paying the cost of building the entire stack frame.
        StackTraceElement frame = access.getStackTraceElement(throwable, i);
        String cname = frame.getClassName();
        boolean isLoggerImpl = isLoggerImplFrame(cname);
        if (lookingForLogger) {
            // Skip all frames until we have found the first logger frame.
            if (isLoggerImpl) {
                lookingForLogger = false;
            }
        } else {
            if (!isLoggerImpl) {
                // skip reflection call
                if (!cname.startsWith("java.lang.reflect.") && !cname.startsWith("sun.reflect.")) {
                    // We've found the relevant frame.
                    return new String[] {cname, frame.getMethodName()};
                }
            }
        }
    }
    return new String[] {};
    // We haven't found a suitable frame, so just punt.  This is
    // OK as we are only committed to making a "best effort" here.
}

protected static String[] getClassNameJDK5() {
    // Get the stack trace.
    StackTraceElement stack[] = (new Throwable()).getStackTrace();
    // First, search back to a method in the Logger class.
    int ix = 0;
    while (ix < stack.length) {
        StackTraceElement frame = stack[ix];
        String cname = frame.getClassName();
        if (isLoggerImplFrame(cname)) {
            break;
        }
        ix++;
    }
    // Now search for the first frame before the "Logger" class.
    while (ix < stack.length) {
        StackTraceElement frame = stack[ix];
        String cname = frame.getClassName();
        if (isLoggerImplFrame(cname)) {
            // We've found the relevant frame.
            return new String[] {cname, frame.getMethodName()};
        }
        ix++;
    }
    return new String[] {};
    // We haven't found a suitable frame, so just punt.  This is
    // OK as we are only committed to making a "best effort" here.
}


private static boolean isLoggerImplFrame(String cname) {
    // the log record could be created for a platform logger
    return (
            cname.equals("my.package.Logger") ||
            cname.equals("java.util.logging.Logger") ||
            cname.startsWith("java.util.logging.LoggingProxyImpl") ||
            cname.startsWith("sun.util.logging."));
}

protected static java.util.logging.Logger getLogger(String name) {
    return java.util.logging.Logger.getLogger(name);
}

protected static boolean log(Level level, String msg, Object... args) {
    return log(level, null, msg, args);
}

protected static boolean log(Level level, Throwable thrown, String msg, Object... args) {
    String[] values = getClassName();
    java.util.logging.Logger log = getLogger(values[CLASS_NAME]);
    if (level != null && log.isLoggable(level)) {
        if (msg != null) {
            log.log(getRecord(level, thrown, values[CLASS_NAME], values[METHOD_NAME], msg, args));
        }
        return true;
    }
    return false;
}

protected static LogRecord getRecord(Level level, Throwable thrown, String className, String methodName, String msg, Object... args) {
    LogRecord record = new LogRecord(level, format(msg, args));
    record.setSourceClassName(className);
    record.setSourceMethodName(methodName);
    if (thrown != null) {
        record.setThrown(thrown);
    }
    return record;
}

private static String format(String msg, Object... args) {
    if (msg == null || args == null || args.length == 0) {
        return msg;
    } else if (msg.indexOf('%') >= 0) {
        try {
            return String.format(msg, args);
        } catch (IllegalFormatException esc) {
            // none
        }
    } else if (msg.indexOf('{') >= 0) {
        try {
            return MessageFormat.format(msg, args);
        } catch (IllegalArgumentException exc) {
            // none
        }
    }
    if (args.length == 1) {
        Object param = args[0];
        if (param != null && param.getClass().isArray()) {
            return msg + Arrays.toString((Object[]) param);
        } else if (param instanceof Throwable){
            return msg;
        } else {
            return msg + param;
        }
    } else {
        return msg + Arrays.toString(args);
    }
}

public static void severe(String msg, Object... args) {
    log(Level.SEVERE, msg, args);
}

public static void warning(String msg, Object... args) {
    log(Level.WARNING, msg, args);
}

public static void info(Throwable thrown, String format, Object... args) {
    log(Level.INFO, thrown, format, args);
}

public static void warning(Throwable thrown, String format, Object... args) {
    log(Level.WARNING, thrown, format, args);
}

public static void warning(Throwable thrown) {
    log(Level.WARNING, thrown, thrown.getMessage());
}

public static void severe(Throwable thrown, String format, Object... args) {
    log(Level.SEVERE, thrown, format, args);
}

public static void severe(Throwable thrown) {
    log(Level.SEVERE, thrown, thrown.getMessage());
}

public static void info(String msg, Object... args) {
    log(Level.INFO, msg, args);
}

public static void fine(String msg, Object... args) {
    log(Level.FINE, msg, args);
}

public static void finer(String msg, Object... args) {
    log(Level.FINER, msg, args);
}

public static void finest(String msg, Object... args) {
    log(Level.FINEST, msg, args);
}

public static boolean isLoggableFinest() {
    return isLoggable(Level.FINEST);
}

public static boolean isLoggableFiner() {
    return isLoggable(Level.FINER);
}

public static boolean isLoggableFine() {
    return isLoggable(Level.FINE);
}

public static boolean isLoggableInfo() {
    return isLoggable(Level.INFO);
}

public static boolean isLoggableWarning() {
    return isLoggable(Level.WARNING);
}
public static boolean isLoggableSevere() {
    return isLoggable(Level.SEVERE);
}

private static boolean isLoggable(Level level) {
    return log(level, null);
}

}

0
投票

看看Loggerjcabi-log课程。它完全符合您的需求,提供了一系列静态方法。您不再需要将记录器嵌入到类中:

import com.jcabi.log.Logger;
class Foo {
  public void bar() {
    Logger.info(this, "doing something...");
  }
}

Logger将所有日志发送到SLF4J,您可以在运行时将其重定向到任何其他日志记录工具。


0
投票

一个很好的选择是使用(一个)lombok日志注释:https://projectlombok.org/features/Log.html

它使用当前类生成相应的日志语句。


23
投票

创建堆栈跟踪是一个相对较慢的操作。您的调用者已经知道它所属的类和方法,因此浪费了精力。解决方案的这一方面效率低下。

即使您使用静态类信息,也不应该为每条消息再次获取Logger。 Log4j的From the author,CekiGülcü:

包装类中最常见的错误是在每个日志请求上调用Logger.getLogger方法。这可以保证对您的应用程序的性能造成严重破坏。真!!!

这是在类初始化期间获取Logger的传统,高效的习惯用法:

private static final Logger log = Logger.getLogger(MyClass.class);

请注意,这为层次结构中的每种类型提供了单独的Logger。如果您想出一个在实例上调用getClass()的方法,您将看到由基类型记录的消息显示在子类型的记录器下。也许这在某些情况下是可取的,但我发现它令人困惑(而且我倾向于赞成合成而不是继承)。

显然,通过getClass()使用动态类型将要求您每个实例至少获取一次记录器,而不是像使用静态类型信息的推荐习惯用法那样每个类获取一次。


0
投票

从Java 7开始,这是一个很好的方法:

private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());

记录器可以是static,那很好。这里使用的是SLF4J API

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

但原则上可以与任何日志框架一起使用。如果记录器需要字符串参数,请添加toString()


0
投票

简单而琐碎的老学校:

只需创建自己的类并传递类名,方法名+注释(如果类/方法改变它们会自动重构Shift + F6)

public class MyLogs {    
    public static void LOG(String theClass, String theMethod, String theComment) {
        Log.d("MY_TAG", "class: " + theClass + " meth : " + theMethod + " comm : " + theComment);
    }
}

只需在应用程序的任何地方使用它(无需上下文,无需初始化,无需额外的库和查找) - 可用于任何编程语言!

MyLogs.LOG("MainActivity", "onCreate", "Hello world");

这将在您的控制台中打印:

MY_TAG类:MainActivity meth:onCreate comm:Hello world


21
投票

MethodHandles类(从Java 7开始)包含一个Lookup类,它可以从静态上下文中查找并返回当前类的名称。请考虑以下示例:

import java.lang.invoke.MethodHandles;

public class Main {
  private static final Class clazz = MethodHandles.lookup().lookupClass();
  private static final String CLASSNAME = clazz.getSimpleName();

  public static void main( String args[] ) {
    System.out.println( CLASSNAME );
  }
}

运行时会产生:

Main

对于记录器,您可以使用:

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

18
投票

我们实际上在LogUtils类中有类似的东西。是的,它有点狡猾,但就我而言,优点是值得的。我们希望确保我们没有任何开销,因为它被重复调用,所以我们(有点hackily)确保它只能从静态初始化器上下文调用,la:

private static final Logger LOG = LogUtils.loggerForThisClass();

如果从普通方法或实例初始化程序调用它(即如果“静态”不在上面),它将失败,以降低性能开销的风险。方法是:

public static Logger loggerForThisClass() {
    // We use the third stack element; second is this method, first is .getStackTrace()
    StackTraceElement myCaller = Thread.currentThread().getStackTrace()[2];
    Assert.equal("<clinit>", myCaller.getMethodName());
    return Logger.getLogger(myCaller.getClassName());
}

有人问过这有什么好处

= Logger.getLogger(MyClass.class);

可能从来没有必要处理那些从其他地方复制并粘贴该行并忘记更改类名的人,让你处理一个将所有东西发送到另一个记录器的类。


8
投票

假设您将静态引用保存到记录器,这里是一个独立的静态单例:

public class LoggerUtils extends SecurityManager
{
    public static Logger getLogger()
    {
        String className = new LoggerUtils().getClassName();
        Logger logger = Logger.getLogger(className);
        return logger;
    }

    private String getClassName()
    {
        return getClassContext()[2].getName();
    }
}

用法很干净:

Logger logger = LoggerUtils.getLogger();

4
投票

对于您使用此类的每个类,您无论如何都必须查找Logger,因此您可以在这些类中使用静态Logger。

private static final Logger logger = Logger.getLogger(MyClass.class.getName());

然后,当您需要执行日志消息时,只需引用该记录器。您的方法与静态Log4J Logger的功能完全相同,为什么要重新发明轮子呢?


3
投票

然后最好的事情是两个混合。

public class LoggerUtil {

    public static Level level=Level.ALL;

    public static java.util.logging.Logger getLogger() {
        final Throwable t = new Throwable();
        final StackTraceElement methodCaller = t.getStackTrace()[1];
        final java.util.logging.Logger logger = java.util.logging.Logger.getLogger(methodCaller.getClassName());
        logger.setLevel(level);

        return logger;
    }
}

然后在每个班级:

private static final Logger LOG = LoggerUtil.getLogger();

在代码中:

LOG.fine("debug that !...");

你得到静态记录器,你可以在每个类中复制和粘贴,没有开销......

阿拉


3
投票

通过阅读本网站上的所有其他反馈,我创建了以下用于Log4j:

package com.edsdev.testapp.util;

import java.util.concurrent.ConcurrentHashMap;

import org.apache.log4j.Level;
import org.apache.log4j.Priority;

public class Logger extends SecurityManager {

private static ConcurrentHashMap<String, org.apache.log4j.Logger> loggerMap = new ConcurrentHashMap<String, org.apache.log4j.Logger>();

public static org.apache.log4j.Logger getLog() {
    String className = new Logger().getClassName();
    if (!loggerMap.containsKey(className)) {
        loggerMap.put(className, org.apache.log4j.Logger.getLogger(className));
    }
    return loggerMap.get(className);
}
public String getClassName() {
    return getClassContext()[3].getName();
}
public static void trace(Object message) {
    getLog().trace(message);
}
public static void trace(Object message, Throwable t) {
    getLog().trace(message, t);
}
public static boolean isTraceEnabled() {
    return getLog().isTraceEnabled();
}
public static void debug(Object message) {
    getLog().debug(message);
}
public static void debug(Object message, Throwable t) {
    getLog().debug(message, t);
}
public static void error(Object message) {
    getLog().error(message);
}
public static void error(Object message, Throwable t) {
    getLog().error(message, t);
}
public static void fatal(Object message) {
    getLog().fatal(message);
}
public static void fatal(Object message, Throwable t) {
    getLog().fatal(message, t);
}
public static void info(Object message) {
    getLog().info(message);
}
public static void info(Object message, Throwable t) {
    getLog().info(message, t);
}
public static boolean isDebugEnabled() {
    return getLog().isDebugEnabled();
}
public static boolean isEnabledFor(Priority level) {
    return getLog().isEnabledFor(level);
}
public static boolean isInfoEnabled() {
    return getLog().isInfoEnabled();
}
public static void setLevel(Level level) {
    getLog().setLevel(level);
}
public static void warn(Object message) {
    getLog().warn(message);
}
public static void warn(Object message, Throwable t) {
    getLog().warn(message, t);
}

}

现在在你的代码中你需要的只是

Logger.debug("This is a test");

要么

Logger.error("Look what happened Ma!", e);

如果您需要更多地了解log4j方法,只需从上面列出的Logger类中委派它们。


2
投票

您当然可以使用具有适当模式布局的Log4J:

例如,对于类名“org.apache.xyz.SomeClass”,模式%C {1}将输出“SomeClass”。

http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/PatternLayout.html

© www.soinside.com 2019 - 2024. All rights reserved.