java.util.logging.Logger类的使用及代码示例

x33g5p2x  于2022-01-17 转载在 其他  
字(14.4k)|赞(0)|评价(0)|浏览(176)

本文整理了Java中java.util.logging.Logger类的一些代码示例,展示了Logger类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Logger类的具体详情如下:
包路径:java.util.logging.Logger
类名称:Logger

Logger介绍

[英]A Logger object is used to log messages for a specific system or application component. Loggers are normally named, using a hierarchical dot-separated namespace. Logger names can be arbitrary strings, but they should normally be based on the package name or class name of the logged component, such as java.net or javax.swing. In addition it is possible to create "anonymous" Loggers that are not stored in the Logger namespace.

Logger objects may be obtained by calls on one of the getLogger factory methods. These will either create a new Logger or return a suitable existing Logger. It is important to note that the Logger returned by one of the getLogger factory methods may be garbage collected at any time if a strong reference to the Logger is not kept.

Logging messages will be forwarded to registered Handler objects, which can forward the messages to a variety of destinations, including consoles, files, OS logs, etc.

Each Logger keeps track of a "parent" Logger, which is its nearest existing ancestor in the Logger namespace.

Each Logger has a "Level" associated with it. This reflects a minimum Level that this logger cares about. If a Logger's level is set to null, then its effective level is inherited from its parent, which may in turn obtain it recursively from its parent, and so on up the tree.

The log level can be configured based on the properties from the logging configuration file, as described in the description of the LogManager class. However it may also be dynamically changed by calls on the Logger.setLevel method. If a logger's level is changed the change may also affect child loggers, since any child logger that has null as its level will inherit its effective level from its parent.

On each logging call the Logger initially performs a cheap check of the request level (e.g., SEVERE or FINE) against the effective log level of the logger. If the request level is lower than the log level, the logging call returns immediately.

After passing this initial (cheap) test, the Logger will allocate a LogRecord to describe the logging message. It will then call a Filter (if present) to do a more detailed check on whether the record should be published. If that passes it will then publish the LogRecord to its output Handlers. By default, loggers also publish to their parent's Handlers, recursively up the tree.

Each Logger may have a ResourceBundle name associated with it. The named bundle will be used for localizing logging messages. If a Logger does not have its own ResourceBundle name, then it will inherit the ResourceBundle name from its parent, recursively up the tree.

Most of the logger output methods take a "msg" argument. This msg argument may be either a raw value or a localization key. During formatting, if the logger has (or inherits) a localization ResourceBundle and if the ResourceBundle has a mapping for the msg string, then the msg string is replaced by the localized value. Otherwise the original msg string is used. Typically, formatters use java.text.MessageFormat style formatting to format parameters, so for example a format string "{0} {1}" would format two parameters as strings.

When mapping ResourceBundle names to ResourceBundles, the Logger will first try to use the Thread's ContextClassLoader. If that is null it will try the SystemClassLoader instead. As a temporary transition feature in the initial implementation, if the Logger is unable to locate a ResourceBundle from the ContextClassLoader or SystemClassLoader the Logger will also search up the class stack and use successive calling ClassLoaders to try to locate a ResourceBundle. (This call stack search is to allow containers to transition to using ContextClassLoaders and is likely to be removed in future versions.)

Formatting (including localization) is the responsibility of the output Handler, which will typically call a Formatter.

Note that formatting need not occur synchronously. It may be delayed until a LogRecord is actually written to an external sink.

The logging methods are grouped in five main categories:

  • There are a set of "log" methods that take a log level, a message string, and optionally some parameters to the message string.
  • There are a set of "logp" methods (for "log precise") that are like the "log" methods, but also take an explicit source class name and method name.
  • There are a set of "logrb" method (for "log with resource bundle") that are like the "logp" method, but also take an explicit resource bundle name for use in localizing the log message.
  • There are convenience methods for tracing method entries (the "entering" methods), method returns (the "exiting" methods) and throwing exceptions (the "throwing" methods).
  • Finally, there are a set of convenience methods for use in the very simplest cases, when a developer simply wants to log a simple string at a given log level. These methods are named after the standard Level names ("severe", "warning", "info", etc.) and take a single argument, a message string.

For the methods that do not take an explicit source name and method name, the Logging framework will make a "best effort" to determine which class and method called into the logging method. However, it is important to realize that this automatically inferred information may only be approximate (or may even be quite wrong!). Virtual machines are allowed to do extensive optimizations when JITing and may entirely remove stack frames, making it impossible to reliably locate the calling class and method.

All methods on Logger are multi-thread safe.

Subclassing Information: Note that a LogManager class may provide its own implementation of named Loggers for any point in the namespace. Therefore, any subclasses of Logger (unless they are implemented in conjunction with a new LogManager class) should take care to obtain a Logger instance from the LogManager class and should delegate operations such as "isLoggable" and "log(LogRecord)" to that instance. Note that in order to intercept all logging output, subclasses need only override the log(LogRecord) method. All the other logging methods are implemented as calls on this log(LogRecord) method.
[中]Logger对象用于记录特定系统或应用程序组件的消息。记录器通常使用分层的点分隔名称空间命名。记录器名称可以是任意字符串,但它们通常应基于记录组件(如java)的包名或类名。net或javax。摆动此外,还可以创建不存储在记录器命名空间中的“匿名”记录器。
记录器对象可以通过调用其中一个getLogger工厂方法获得。这些将创建一个新的记录器或返回一个合适的现有记录器。需要注意的是,如果没有保留对记录器的强引用,则任何时候都可能对getLogger工厂方法之一返回的记录器进行垃圾收集。
日志消息将转发到已注册的处理程序对象,这些对象可以将消息转发到各种目的地,包括控制台、文件、操作系统日志等。
每个记录器都跟踪一个“父”记录器,它是记录器名称空间中最近的现有祖先。
每个记录器都有一个与其关联的“级别”。这反映了记录器关心的最低级别。如果记录器的级别设置为null,则其有效级别将从其父级继承,而父级又可能从其父级递归获取该级别,依此类推。
可以根据日志配置文件中的属性配置日志级别,如LogManager类的说明所述。但是,它也可以通过对记录器的调用进行动态更改。设置级别方法。如果更改了记录器的级别,更改也可能会影响子记录器,因为任何级别为null的子记录器都将从其父记录器继承其有效级别。
在每次日志调用时,记录器首先根据记录器的有效日志级别对请求级别(例如,严重或轻微)执行廉价检查。如果请求级别低于日志级别,日志调用将立即返回。
通过此初始(廉价)测试后,记录器将分配一个日志记录来描述日志消息。然后它将调用一个过滤器(如果存在的话),对是否应该发布记录进行更详细的检查。如果通过,它将把日志记录发布到它的输出处理程序。默认情况下,日志记录器也会递归地向上发布到其父处理程序。
每个记录器可能都有一个与其关联的ResourceBundle名称。命名包将用于本地化日志消息。如果记录器没有自己的ResourceBundle名称,那么它将从其父级递归地继承ResourceBundle名称。
大多数记录器输出方法采用“msg”参数。此msg参数可以是原始值或本地化键。格式化期间,如果记录器具有(或继承)本地化ResourceBundle,并且ResourceBundle具有msg字符串的映射,则msg字符串将替换为本地化值。否则将使用原始msg字符串。通常,格式化程序使用java。文本MessageFormat样式格式化以格式化参数,例如,格式字符串“{0}{1}”将两个参数格式化为字符串。
将ResourceBundle名称映射到ResourceBundle时,记录器将首先尝试使用线程的ContextClassLoader。如果该值为空,它将尝试SystemClassLoader。作为初始实现中的临时转换功能,如果记录器无法从ContextClassLoader或SystemClassLoader中找到ResourceBundle,记录器还将搜索类堆栈,并使用连续调用的ClassLoader尝试定位ResourceBundle。(此调用堆栈搜索允许容器转换为使用ContextClassLoader,并可能在未来版本中删除。)
格式化(包括本地化)是输出处理程序的责任,它通常会调用格式化程序。
请注意,格式化不需要同步进行。它可能会延迟,直到日志记录实际写入外部接收器。
测井方法分为五大类:
*有一组“log”方法,它们采用日志级别、消息字符串以及消息字符串的一些可选参数。
*有一组“logp”方法(用于“log-precise”)与“log”方法类似,但也采用显式的源类名和方法名。
*有一组“logrb”方法(用于“带有资源包的日志”)与“logp”方法类似,但也使用显式的资源包名称来本地化日志消息。
*有一些方便的方法可以跟踪方法条目(“进入”方法)、方法返回(“退出”方法)和抛出异常(“抛出”方法)。
*最后,在最简单的情况下,当开发人员只想在给定的日志级别记录简单字符串时,可以使用一组方便的方法。这些方法以标准级别名称(“严重”、“警告”、“信息”等)命名,并采用单个参数,即消息字符串。
对于不采用显式源名称和方法名称的方法,日志框架将“尽最大努力”确定将哪个类和方法调用到日志方法中。然而,重要的是要认识到,这种自动推断的信息可能只是近似的(甚至可能是完全错误的!)。虚拟机可以在JIT时进行广泛的优化,并可能完全删除堆栈帧,从而无法可靠地定位调用类和方法。
记录器上的所有方法都是多线程安全的。
子类化信息:请注意,LogManager类可以为命名空间中的任何点提供其自己的命名记录器实现。因此,Logger的任何子类(除非它们与新的LogManager类一起实现)都应该注意从LogManager类获取Logger实例,并且应该将诸如“isLoggable”和“log(LogRecord)”之类的操作委托给该实例。注意,为了截获所有日志输出,子类只需要重写log(LogRecord)方法。所有其他日志记录方法都作为对该日志(LogRecord)方法的调用来实现。

代码示例

代码示例来源:origin: google/guava

@Override
 public void handlePotentialDeadlock(PotentialDeadlockException e) {
  logger.log(Level.SEVERE, "Detected potential deadlock", e);
 }
},

代码示例来源:origin: spring-projects/spring-framework

public JavaUtilLog(String name) {
  this.name = name;
  this.logger = java.util.logging.Logger.getLogger(name);
}

代码示例来源:origin: square/okhttp

@Override protected void execute() {
 try {
  processConnection();
 } catch (IOException e) {
  logger.info(
    MockWebServer.this + " connection from " + raw.getInetAddress() + " failed: " + e);
 } catch (Exception e) {
  logger.log(Level.SEVERE,
    MockWebServer.this + " connection from " + raw.getInetAddress() + " crashed", e);
 }
}

代码示例来源:origin: jenkinsci/jenkins

@Override public Void call() throws Error {
  Logger logger = Logger.getLogger(name);
  loggers.add(logger);
  logger.setLevel(level);
  return null;
}
void broadcast() {

代码示例来源:origin: apache/incubator-dubbo

@Override
public Level getLevel() {
  return fromJdkLevel(java.util.logging.Logger.getLogger(GLOBAL_LOGGER_NAME).getLevel());
}

代码示例来源:origin: google/guava

private static String lenientToString(@Nullable Object o) {
  try {
   return String.valueOf(o);
  } catch (Exception e) {
   // Default toString() behavior - see Object.toString()
   String objectToString =
     o.getClass().getName() + '@' + Integer.toHexString(System.identityHashCode(o));
   // Logger is created inline with fixed name to avoid forcing Proguard to create another class.
   Logger.getLogger("com.google.common.base.Strings")
     .log(WARNING, "Exception during lenientFormat for " + objectToString, e);
   return "<" + objectToString + " threw " + e.getClass().getName() + ">";
  }
 }
}

代码示例来源:origin: jenkinsci/jenkins

/**
 * Loads the contents of this file into a new object.
 */
public Object read() throws IOException {
  if (LOGGER.isLoggable(Level.FINE)) {
    LOGGER.fine("Reading "+file);
  }
  try (InputStream in = new BufferedInputStream(Files.newInputStream(file.toPath()))) {
    return xs.fromXML(in);
  } catch (RuntimeException | Error e) {
    throw new IOException("Unable to read "+file,e);
  }
}

代码示例来源:origin: google/guava

@Override
public void handleException(Throwable exception, SubscriberExceptionContext context) {
 Logger logger = logger(context);
 if (logger.isLoggable(Level.SEVERE)) {
  logger.log(Level.SEVERE, message(context), exception);
 }
}

代码示例来源:origin: jenkinsci/jenkins

void migrateUsers(UserIdMapper mapper) throws IOException {
  LOGGER.fine("Beginning migration of users to userId mapping.");
  Map<String, File> existingUsers = scanExistingUsers();
  for (Map.Entry<String, File> existingUser : existingUsers.entrySet()) {
    File newDirectory = mapper.putIfAbsent(existingUser.getKey(), false);
    LOGGER.log(Level.INFO, "Migrating user '" + existingUser.getKey() + "' from 'users/" + existingUser.getValue().getName() + "/' to 'users/" + newDirectory.getName() + "/'");
    Files.move(existingUser.getValue().toPath(), newDirectory.toPath(), StandardCopyOption.REPLACE_EXISTING);
  }
  mapper.save();
  LOGGER.fine("Completed migration of users to userId mapping.");
}

代码示例来源:origin: jenkinsci/jenkins

private static void warnWindowsSymlink() {
  if (warnedSymlinks.compareAndSet(false, true)) {
    LOGGER.warning("Symbolic links enabled on this platform but disabled for this user; run as administrator or use Local Security Policy > Security Settings > Local Policies > User Rights Assignment > Create symbolic links");
  }
}

代码示例来源:origin: apache/incubator-dubbo

@Override
public boolean isDebugEnabled() {
  return logger.isLoggable(Level.FINE);
}

代码示例来源:origin: square/okhttp

@Override public Response intercept(Chain chain) throws IOException {
  long t1 = System.nanoTime();
  Request request = chain.request();
  logger.info(String.format("Sending request %s on %s%n%s",
    request.url(), chain.connection(), request.headers()));
  Response response = chain.proceed(request);
  long t2 = System.nanoTime();
  logger.info(String.format("Received response for %s in %.1fms%n%s",
    request.url(), (t2 - t1) / 1e6d, response.headers()));
  return response;
 }
}

代码示例来源:origin: square/okhttp

private static void enableHttp2FrameLogging() {
  frameLogger = Logger.getLogger(Http2.class.getName());
  frameLogger.setLevel(Level.FINE);
  ConsoleHandler handler = new ConsoleHandler();
  handler.setLevel(Level.FINE);
  handler.setFormatter(new SimpleFormatter() {
   @Override public String format(LogRecord record) {
    return Util.format("%s%n", record.getMessage());
   }
  });
  frameLogger.addHandler(handler);
 }
}

代码示例来源:origin: jenkinsci/jenkins

/**
 * Schedules this job for an execution
 * @return
 *      {@link Future} to keeps track of the status of the execution.
 */
public Future<UpdateCenterJob> submit() {
  LOGGER.fine("Scheduling "+this+" to installerService");
  // TODO: seems like this access to jobs should be synchronized, no?
  // It might get synch'd accidentally via the addJob method, but that wouldn't be good.
  jobs.add(this);
  return installerService.submit(this,this);
}

代码示例来源:origin: jenkinsci/jenkins

/**
 * Installs log handler to monitor all Hudson logs.
 */
@edu.umd.cs.findbugs.annotations.SuppressFBWarnings("LG_LOST_LOGGER_DUE_TO_WEAK_REFERENCE")
private void installLogger() {
  Jenkins.logRecords = handler.getView();
  Logger.getLogger("").addHandler(handler);
}

代码示例来源:origin: google/guava

public void testSuccessfulAsList_resultCancelledRacingInputDone() throws Exception {
 TestLogHandler listenerLoggerHandler = new TestLogHandler();
 Logger exceptionLogger = Logger.getLogger(AbstractFuture.class.getName());
 exceptionLogger.addHandler(listenerLoggerHandler);
 try {
  doTestSuccessfulAsList_resultCancelledRacingInputDone();
  assertWithMessage("Nothing should be logged")
    .that(listenerLoggerHandler.getStoredLogRecords())
    .isEmpty();
 } finally {
  exceptionLogger.removeHandler(listenerLoggerHandler);
 }
}

代码示例来源:origin: google/guava

@Override
 public void tearDown() throws Exception {
  interruptingTask.stopInterrupting();
  interruptingThread.interrupt();
  joinUninterruptibly(interruptingThread, 2500, MILLISECONDS);
  Thread.interrupted();
  if (interruptingThread.isAlive()) {
   // This will be hidden by test-output redirection:
   logger.severe("InterruptenatorTask did not exit; future tests may be affected");
   /*
    * This won't do any good under JUnit 3, but I'll leave it around in
    * case we ever switch to JUnit 4:
    */
   fail();
  }
 }
});

代码示例来源:origin: square/okhttp

public synchronized void connectionPreface() throws IOException {
 if (closed) throw new IOException("closed");
 if (!client) return; // Nothing to write; servers don't send connection headers!
 if (logger.isLoggable(FINE)) {
  logger.fine(format(">> CONNECTION %s", CONNECTION_PREFACE.hex()));
 }
 sink.write(CONNECTION_PREFACE.toByteArray());
 sink.flush();
}

代码示例来源:origin: hankcs/HanLP

@Override
protected Map.Entry<String, String> onGenerateEntry(String line)
{
  String[] paramArray = line.split(separator, 2);
  if (paramArray.length != 2)
  {
    logger.warning("词典有一行读取错误: " + line);
    return null;
  }
  return new AbstractMap.SimpleEntry<String, String>(paramArray[0], paramArray[1]);
}

代码示例来源:origin: apache/incubator-dubbo

@Override
public boolean isWarnEnabled() {
  return logger.isLoggable(Level.WARNING);
}

相关文章