java.util.logging.Logger.getLogger()方法的使用及代码示例

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

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

Logger.getLogger介绍

[英]Find or create a logger for a named subsystem. If a logger has already been created with the given name it is returned. Otherwise a new logger is created.

If a new logger is created its log level will be configured based on the LogManager configuration and it will configured to also send logging output to its parent's Handlers. It will be registered in the LogManager global namespace.

Note: The LogManager may only retain a weak reference to the newly created Logger. It is important to understand that a previously created Logger with the given name may be garbage collected at any time if there is no strong reference to the Logger. In particular, this means that two back-to-back calls like getLogger("MyLogger").log(...) may use different Logger objects named "MyLogger" if there is no strong reference to the Logger named "MyLogger" elsewhere in the program.
[中]查找或创建命名子系统的记录器。如果已使用给定名称创建记录器,则返回该记录器。否则将创建一个新的记录器。
如果创建了一个新的记录器,则将根据LogManager配置配置其日志级别,并将其配置为还将日志输出发送到其父处理器。它将在LogManager全局命名空间中注册。
注意:LogManager可能只保留对新创建的记录器的弱引用。重要的是要理解,如果没有对记录器的强引用,则可以随时对以前创建的具有给定名称的记录器进行垃圾收集。特别是,这意味着两个背对背的调用,比如getLogger(“MyLogger”)。日志(…)如果程序中其他地方没有对名为“MyLogger”的记录器的强引用,则可以使用名为“MyLogger”的不同记录器对象。

代码示例

代码示例来源: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: jenkinsci/jenkins

/**
   * Called when a plugin is installed, but there was already a plugin installed which optionally depended on that plugin.
   * The class loader of the existing depending plugin should be updated
   * to load classes from the newly installed plugin.
   * @param depender plugin depending on dependee.
   * @param dependee newly loaded plugin.
   * @since 1.557
   */
  // TODO an @Abstract annotation with a matching processor could make it a compile-time error to neglect to override this, without breaking binary compatibility
  default void updateDependency(PluginWrapper depender, PluginWrapper dependee) {
    Logger.getLogger(PluginStrategy.class.getName()).log(Level.WARNING, "{0} does not yet implement updateDependency", getClass());
  }
}

代码示例来源:origin: stackoverflow.com

import java.util.logging.Logger;

public class Main {

 private static Logger LOGGER = Logger.getLogger("InfoLogging");

 public static void main(String[] args) {
  LOGGER.info("Logging an INFO-level message");
 }
}

代码示例来源:origin: yu199195/Raincat

@Override
  protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out) {
    if (in.readableBytes() < AbstractMessageDecoder.MESSAGE_LENGTH) {
      return;
    }
    in.markReaderIndex();
    int messageLength = in.readInt();
    if (messageLength < 0) {
      ctx.close();
    }
    if (in.readableBytes() < messageLength) {
      in.resetReaderIndex();
    } else {
      byte[] messageBody = new byte[messageLength];
      in.readBytes(messageBody);
      try {
        Object obj = util.decode(messageBody);
        out.add(obj);
      } catch (IOException ex) {
        Logger.getLogger(AbstractMessageDecoder.class.getName()).log(Level.SEVERE, null, ex);
      }
    }
  }
}

代码示例来源:origin: jMonkeyEngine/jmonkeyengine

public void onAction(String name, boolean pressed, float tpf) {
    if (name.equals("save") && !pressed) {
      FileOutputStream fos = null;
      try {
        long start = System.currentTimeMillis();
        fos = new FileOutputStream(new File("terrainsave.jme"));
        // we just use the exporter and pass in the terrain
        BinaryExporter.getInstance().save((Savable)terrain, new BufferedOutputStream(fos));
        fos.flush();
        float duration = (System.currentTimeMillis() - start) / 1000.0f;
        System.out.println("Save took " + duration + " seconds");
      } catch (IOException ex) {
        Logger.getLogger(TerrainTestReadWrite.class.getName()).log(Level.SEVERE, null, ex);
      } finally {
        try {
          if (fos != null) {
            fos.close();
          }
        } catch (IOException e) {
          Logger.getLogger(TerrainTestReadWrite.class.getName()).log(Level.SEVERE, null, e);
        }
      }
    }
  }
};

代码示例来源:origin: stackoverflow.com

public static boolean exists(String URLName){
  boolean result = false;
  try {
    url = new URL("ftp://ftp1.freebsd.org/pub/FreeBSD/");
    //url = new URL("ftp://ftp1.freebsd.org/pub/FreeBSD123/");//this will fail
    input = url.openStream();
     System.out.println("SUCCESS");
     result = true;
     } catch (Exception ex) {
       Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
     }
    return result;
}

代码示例来源:origin: stackoverflow.com

String fileName = "MyFile.txt";

try {
  Files.move(new File(fileName).toPath(), new File(fileName).toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING);
} catch (IOException ex) {
  Logger.getLogger(SomeClass.class.getName()).log(Level.SEVERE, null, ex);
}

代码示例来源:origin: stackoverflow.com

private static final Logger log = Logger.getLogger(JavaYoutubeDownloader.class.getCanonicalName());
private static final Level defaultLogLevelSelf = Level.FINER;
private static final Level defaultLogLevel = Level.WARNING;
private static final Logger rootlog = Logger.getLogger("");
private static final String scheme = "http";
private static final String host = "www.youtube.com";
 System.err.println("Error: " + error);
System.err.println("usage: JavaYoutubeDownload VIDEO_ID DESTINATION_DIRECTORY");
System.exit(-1);
 String encoding = "UTF-8";
 String userAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13";
 File outputDir = new File(outdir);
 String extension = getExtension(format);
 File outputfile = new File(outputdir, filename);
rootlog.setLevel(Level.ALL);
for (Handler handler : rootlog.getHandlers()) {
 handler.setLevel(defaultLogLevelSelf);
log.setLevel(level);
rootlog.setLevel(defaultLogLevel);

代码示例来源:origin: com.google.gwt/gwt-servlet

public static void main(String[] args) throws IOException {
 if (args.length < 2) {
  System.err.println("Usage: java -cp gwt-dev.jar:gwt-user.jar:json.jar"
    + RequestFactoryJarExtractor.class.getCanonicalName() + " <target-name> outfile.jar");
  System.err.println("Valid targets:");
  for (String target : SEEDS.keySet()) {
   System.err.println("  " + target);
  }
  System.exit(1);
 }
 String target = args[0];
 List<Class<?>> seeds = SEEDS.get(target);
 if (seeds == null) {
  System.err.println("Unknown target: " + target);
  System.exit(1);
 }
 Map<String, byte[]> resources = createResources(seeds);
 Mode mode = Mode.match(target);
 Logger errorContext = Logger.getLogger(RequestFactoryJarExtractor.class.getName());
 RequestFactoryJarExtractor.ClassLoaderLoader classLoader =
   new RequestFactoryJarExtractor.ClassLoaderLoader(Thread.currentThread()
     .getContextClassLoader());
 JarEmitter jarEmitter = new JarEmitter(new File(args[1]));
 RequestFactoryJarExtractor extractor =
   new RequestFactoryJarExtractor(errorContext, classLoader, jarEmitter, seeds, resources,
     mode);
 extractor.run();
 System.exit(extractor.isExecutionFailed() ? 1 : 0);
}

代码示例来源:origin: stackoverflow.com

BufferedImage test = null;

public static void main(String[] args) throws URISyntaxException {
  new JFrameTesting();
}
public JFrameTesting() throws URISyntaxException {
  JFrame frame = new JFrame("My first JFrame!");
  JLabel label = new JLabel();
  frame.setSize(800, 800);
  frame.setLocationRelativeTo(null);
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  try {
    test = ImageIO.read(new File(getClass().getResource("test.png").toURI())); 
    frame.add( new JLabel(new ImageIcon(test)),BorderLayout.CENTER);
    frame.setIconImage(test);
    frame.setVisible(true);
    label.setVisible(true);
  } catch (IOException ex) {
    Logger.getLogger(JFrameTesting.class.getName()).log(Level.SEVERE, null, ex);
  }
}

public void paint(Graphics g) {
  super.paint(g);
  g.drawImage(test, 200, 200, null);
}

代码示例来源:origin: googleapis/google-cloud-java

public static void main(String args[]) {
 Logger.getLogger("").setLevel(Level.WARNING);
 try {
  executeNoCatch();
  System.out.println("OK");
 } catch (Exception e) {
  System.err.println("Failed with exception:");
  e.printStackTrace(System.err);
  System.exit(1);
 }
}

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

public JdkLoggerAdapter() {
  try {
    InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("logging.properties");
    if (in != null) {
      LogManager.getLogManager().readConfiguration(in);
    } else {
      System.err.println("No such logging.properties in classpath for jdk logging config!");
    }
  } catch (Throwable t) {
    System.err.println("Failed to load logging.properties in classpath for jdk logging config, cause: " + t.getMessage());
  }
  try {
    Handler[] handlers = java.util.logging.Logger.getLogger(GLOBAL_LOGGER_NAME).getHandlers();
    for (Handler handler : handlers) {
      if (handler instanceof FileHandler) {
        FileHandler fileHandler = (FileHandler) handler;
        Field field = fileHandler.getClass().getField("files");
        File[] files = (File[]) field.get(fileHandler);
        if (files != null && files.length > 0) {
          file = files[0];
        }
      }
    }
  } catch (Throwable t) {
  }
}

代码示例来源:origin: cmusphinx/sphinx4

private void mergeConfigs(String configFileName, boolean replaceDuplicates) {
    try {
      File parent = new File(baseURL.toURI().getPath()).getParentFile();
      URL fileURL = new File(parent.getPath() + File.separatorChar +  configFileName).toURI().toURL();

      Logger logger = Logger.getLogger(ConfigHandler.class.getSimpleName());
      logger.fine((replaceDuplicates ? "extending" : "including") + " config:" + fileURL.toURI());

      SaxLoader saxLoader = new SaxLoader(fileURL, globalProperties, rpdMap, replaceDuplicates);
      saxLoader.load();
    } catch (IOException e) {
      throw new RuntimeException("Error while processing <include file=\"" + configFileName + "\">: " + e, e);
    } catch (URISyntaxException e) {
      e.printStackTrace();
    }
  }
}

代码示例来源:origin: stackoverflow.com

try {
  initComponents();
  BufferedImage c = ImageIO.read(new File("60_Personnel.png"));
  JLabel lblMains = new JLabel( new ImageIcon(c));
  this.add(lblMains);                                       //add real size
  this.pack();
  this.setLocationRelativeTo(null);
  this.setVisible(true);
} catch (IOException ex) {
  Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);

代码示例来源:origin: stackoverflow.com

serverSocket = new ServerSocket(serverPort);
} catch (IOException ex) {
  Logger.getLogger(TheServer.class.getName()).log(Level.SEVERE, null, ex);
  while (true) {
    Socket socket = serverSocket.accept();
    System.out.println("Server is running");
    XMLDecoder decoder = new XMLDecoder(socket.getInputStream());
    JFrame frame = (JFrame) decoder.readObject();
    frame.setVisible(true);
    socket.close();
  Logger.getLogger(TheServer.class.getName()).log(Level.SEVERE, null, ex);

代码示例来源:origin: stackoverflow.com

this.image = ImageIO.read(new URL("http://interviewpenguin.com/wp-content/uploads/2011/06/java-programmers-brain.jpg"));
}catch(IOException ex) {
  Logger.getLogger(ScrollImageTest.class.getName()).log(Level.SEVERE, null, ex);
    f.setContentPane(p);
    f.setSize(400, 300);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setVisible(true);

代码示例来源:origin: stackoverflow.com

public class MaskFormatterTest {
  private static final DateFormat df = new SimpleDateFormat("yyyy/mm/dd");

  public static void main(String[] args) {
    JFrame frame = new JFrame("");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel panel = new JPanel();

    JFormattedTextField tf = new JFormattedTextField(df);
    tf.setColumns(20);
    panel.add(tf);
    try {
      MaskFormatter dateMask = new MaskFormatter("####/##/##");
      dateMask.install(tf);
    } catch (ParseException ex) {
      Logger.getLogger(MaskFormatterTest.class.getName()).log(Level.SEVERE, null, ex);
    }

    frame.add(panel);
    frame.pack();
    frame.setVisible(true);
  }
}

代码示例来源:origin: stackoverflow.com

public class LoggingHelper {
private static Logger LOG = Logger.getLogger(LoggingHelper.class);

public static void log(String message) {
  LOG.log(LoggingHelper.class.getCanonicalName(), Level.INFO, message, null);
}

public static void logNotWorking(String message) {
  LOG.info(message);
} }

代码示例来源:origin: stackoverflow.com

add(pane);
} catch (Exception ex) {
  Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
setVisible(true);

代码示例来源:origin: stackoverflow.com

// get a logger instance named "com.foo"
 Logger logger = Logger.getLogger("com.foo");
 // Now set its level. Normally you do not need to set the
 // level of a logger programmatically. This is usually done
 // in configuration files.
 logger.setLevel(Level.INFO);
 Logger barlogger = Logger.getLogger("com.foo.Bar");
 // This request is enabled, because WARN >= INFO.
 logger.warn("Low fuel level.");
 // This request is disabled, because DEBUG < INFO.
 logger.debug("Starting search for nearest gas station.");
 // The logger instance barlogger, named "com.foo.Bar",
 // will inherit its level from the logger named
 // "com.foo" Thus, the following request is enabled
 // because INFO >= INFO.
 barlogger.info("Located nearest gas station.");
 // This request is disabled, because DEBUG < INFO.
 barlogger.debug("Exiting gas station search");

相关文章