Logger的Formatter

public class TestLogger {
	public static void main(String[] args){
		Logger log=Logger.getLogger("haha");
		log.setLevel(Level.INFO);
		Logger log1=Logger.getLogger("haha");
		System.out.println(log==log1);
		Logger log2=Logger.getLogger("haha1");
		ConsoleHandler consoleHandler=new ConsoleHandler();
		consoleHandler.setLevel(Level.ALL);
		log.addHandler(consoleHandler);
		
		try {
			FileHandler fileHandler;
			String pathString=System.getProperty("user.dir");
			System.out.println(pathString);
			fileHandler=new FileHandler(pathString+"\\JZlog.log");
			fileHandler.setLevel(Level.INFO);
			fileHandler.setFormatter(new MyClassHandler());
		    log.addHandler(fileHandler);	
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		for(int i=0;i<10;i++){
			log.info("aaa");
			log2.info("bbb");
			log2.fine("fine");
		}
		
	}
}

class MyClassHandler extends Formatter{
	@Override
	public String format(LogRecord record) {
		// TODO Auto-generated method stub
		SimpleDateFormat sdf=new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
		Date date=new Date(record.getMillis());
		String strDate=sdf.format(date);
		return strDate+":"+record.getMessage()+"\n";
	}
}

JZlog.log:

01/15/2013 10:56:31:aaa
01/15/2013 10:56:31:aaa
01/15/2013 10:56:31:aaa
01/15/2013 10:56:31:aaa
01/15/2013 10:56:31:aaa
01/15/2013 10:56:31:aaa
01/15/2013 10:56:31:aaa
01/15/2013 10:56:31:aaa
01/15/2013 10:56:31:aaa
01/15/2013 10:56:31:aaa


你可能感兴趣的:(Logger的Formatter)