Java Tutorial/Log/Log — различия между версиями

Материал из Java эксперт
Перейти к: навигация, поиск
 
м (1 версия)
 
(нет различий)

Текущая версия на 05:01, 1 июня 2010

A full list of levels.

Logger LevelDescriptionSEVEREHighest logging level. This has top priority.WARNINGOne level below severe. For warning messages that need attention, but aren"t serious.INFOTwo levels below severe. For informational messages.CONFIGThree levels below severe. For configuration-related output.FINEFour levels below severe. For program tracing information.FINERFive levels below severe. For program tracing information.FINESTLowest logging level. This has lowest priority.ALLSpecial level that makes the system log ALL messages.OFFSpecial level that makes the system log NO messages (turns logging off completely).


Guaranteeing proper class and method names

import java.util.logging.Level;
import java.util.logging.Logger;
public class MainClass {
  private static Logger logger = Logger.getLogger("InfoLogging2");
  public static void main(String[] args) {
    logger.logp(Level.INFO, "InfoLogging2", "main", "Logging an INFO-level message");
  }
}





Information Logging

import java.util.logging.Logger;
public class MainClass {
  private static Logger logger = Logger.getLogger("InfoLogging");
  public static void main(String[] args) {
    logger.info("Logging an INFO-level message");
  }
}





Logging a Method Call

import java.util.logging.Level;
import java.util.logging.Logger;
//package com.mycompany;
class MyClass {
  public boolean myMethod(int p1, Object p2) {
    Logger logger = Logger.getLogger("com.mycompany.MyClass");
    if (logger.isLoggable(Level.FINER)) {
      logger.entering(this.getClass().getName(), "myMethod", new Object[] { new Integer(p1), p2 });
    }
    System.out.println("Method body");
    boolean result = true;
    if (logger.isLoggable(Level.FINER)) {
      logger.exiting(this.getClass().getName(), "myMethod", new Boolean(result));
      logger.exiting(this.getClass().getName(), "myMethod");
    }
    return result;
  }
}





Logging an Exception

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
//package com.mycompany;
public class Main {
  public static void main(String[] argv) {
    Logger logger = Logger.getLogger("com.mycompany.MyClass");
    try {
      throw new IOException();
    } catch (Throwable e) {
      logger.log(Level.SEVERE, "Uncaught exception", e);
    }
    Exception ex = new IllegalStateException();
    logger.throwing("Main class", "myMethod", ex);
  }
}





Log to a file

import java.util.logging.FileHandler;
import java.util.logging.Logger;
public class MainClass {
  private static Logger logger = Logger.getLogger("LogToFile");
  public static void main(String[] args) throws Exception {
    logger.addHandler(new FileHandler("LogToFile.xml"));
    logger.info("A message logged to the file");
  }
}





Preventing a Logger from Forwarding Log Records to Its Parent

import java.util.logging.Logger;
public class Main {
  public static void main(String[] argv) throws Exception {
    Logger logger = Logger.getLogger("com.mycompany");
    // Stop forwarding log records to ancestor handlers
    logger.setUseParentHandlers(false);
    // Start forwarding log records to ancestor handlers
    logger.setUseParentHandlers(true);
  }
}





The ConsoleHandler writes log messages to System.err.

Property NameDescriptionDefault ValueConsoleHandler.levelLog level for the handlerLevel.INFOConsoleHandler.filterFilter to useUndefinedConsoleHandler.formatterFormatter to usejava.util.logging.SimpleFormatterConsoleHandler.encodingCharacter set encoding to useDefault platform encoding


The ErrorManager

The ErrorManager is used to handle any errors that occur.

The error manager defines a single method:



void error(String msg, Exception ex, int code)



The codes are defined as static integers in the ErrorManager class and are listed in the following table.

Error CodeDescriptionCLOSE_FAILUREUsed when close() failsFLUSH_FAILUREUsed when flush() failsFORMAT_FAILUREUsed when formatting fails for any reasonGENERIC_FAILUREUsed for any other error that other error codes don"t matchOPEN_FAILUREUsed when open of an output source failsWRITE_FAILUREUsed when writing to the output source fails


The FileHandler class supports filename patterns.

The FileHandler class allows the substitution of paths such as the user"s home directory or the system"s temporary directory.

The forward slash (/) is used as a directory separator/

The forward slash (/) works for both Unix and Windows machines.

The FileHandler class supported to specify where the generation number goes in the filename when log files are rotated.

These patterns are each prefixed with a percent sign (%).

To include the percent sign in the filename, specify two percent signs (%%).

The following table contains all the valid percent-sign substitutions.

PatternDescription%tFull path of the system temporary directory%hValue of the user.home system property%gGeneration number used to distinguish rotated logs%uUnique number used to resolve process conflicts


The FileHandler is able to write to a single file, or write to a rotating set of files as each file reaches a specified maximum size.

The next number in a sequence is added to the end of the name of each rotating file, unless a generation (sequence) pattern is specified elsewhere.

The properties for the FileHandler are listed in the following table.

Property NameDescriptionDefault ValueFileHandler.levelLog level for the handler.Level.INFOFileHandler.filterFilter to use.undefinedFileHandler.formatterFormatter to use.java.util.logging.XMLFormatterFileHandler.encodingCharacter set encoding to use.Default platform encodingFileHandler.limitSpecifies approximate maximum number of bytes to write to a file. 0 means no limit.0FileHandler.countSpecifies how many output files to cycle through.1FileHandler.patternPattern used to generate output filenames.%h/java%u.logFileHandler.appendBoolean value specifying whether to append to an existing file or overwrite it.false


The MemoryHandler is a circular buffer in memory.

The MemoryHandler is intended for use as a quick way to store messages.

The messages have to be sent to another handler to write them to an external source. Because the buffer is circular, older log records eventually are overwritten by newer records.

The properties on the MemoryHandler are listed in the following table.

Property NameDescriptionDefault ValueMemoryHandler.levelLog level for the handlerLevel.INFOMemoryHandler.filterFilter to useundefinedMemoryHandler.sizeSize of the circular buffer (in bytes)1,000MemoryHandler.pushDefines the push level � the minimum level that will cause messages to be sent to the target handlerLevel.SEVEREMemoryHandler.targetSpecifies the name of the target Handler class(undefined)


The SocketHandler writes log messages to the network over a specified TCP port.

Property NameDescriptionDefault ValueSocketHandler.levelLog level for the handlerLevel.INFOSocketHandler.filterFilter to useundefinedSocketHandler.formatterFormatter to usejava.util.logging.XMLFormatterSocketHandler.encodingCharacter set encoding to useDefault platform encodingSocketHandler.hostTarget host name to connect toundefinedSocketHandler.portTarget TCP port to useundefined


The StreamHandler serves chiefly as a base class for all handlers that write log messages to some OutputStream.

The subclasses of StreamHandler are ConsoleHandler, FileHandler, and SocketHandler.

A lot of the stream handling code is built into this class.

Property NameDescriptionDefault ValueStreamHandler.levelLog level for the handlerLevel.INFOStreamHandler.filterFilter to useundefinedStreamHandler.formatterFormatter to usejava.util.logging.SimpleFormatterStreamHandler.encodingCharacter set encoding to useDefault platform encoding