2013-02-03 23 views
0

在以下代码中,类MyCustomeFormatter扩展为Formatter。它也覆盖了format消息。这种方法何时被调用?例如:何时调用格式化方法?

logger.log(Level.INFO,"This is an info message") 

语句将消息记录到指定的处理程序。但是什么时候调用overriden方法?

import java.util.Date; 
import java.util.logging.Formatter; 
import java.util.logging.LogRecord; 


public class MyCustomFormatter extends Formatter { 

public MyCustomFormatter() { 
    super(); 
} 

public String format(LogRecord record) { 

    // Create a StringBuffer to contain the formatted record 
    // start with the date. 
    StringBuffer sb = new StringBuffer(); 

    // Get the date from the LogRecord and add it to the buffer 
    Date date = new Date(record.getMillis()); 
    sb.append(date.toString()); 
    sb.append(" "); 

    // Get the level name and add it to the buffer 
    sb.append(record.getLevel().getName()); 
    sb.append(" "); 

    // Get the formatted message (includes localization 
    // and substitution of paramters) and add it to the buffer 
    sb.append(formatMessage(record)); 
    sb.append("\n"); 

    return sb.toString(); 
} 
} 

回答

0

Logger.log()电话Handler.publish()

的情况下,处理从StreamHandler继承:

public synchronized void publish(LogRecord record) { 
    if (!isLoggable(record)) { 
     return; 
    } 
    String msg; 
    try { 
     msg = getFormatter().format(record); 
    } catch (Exception ex) { 
     // We don't want to throw an exception here, but we 
     // report the exception to any registered ErrorManager. 
     reportError(null, ex, ErrorManager.FORMAT_FAILURE); 
     return; 
    } 

    try { 
     if (!doneHeader) { 
      writer.write(getFormatter().getHead(this)); 
      doneHeader = true; 
     } 
     writer.write(msg); 
    } catch (Exception ex) { 
     // We don't want to throw an exception here, but we 
     // report the exception to any registered ErrorManager. 
     reportError(null, ex, ErrorManager.WRITE_FAILURE); 
    } 
}