001package net.gdface.utils; 002 003import java.io.PrintStream; 004 005/** 006 * ç®€å•æ—¥å¿—输出工具类 007 * @author guyadong 008 * 009 */ 010public class SampleLog { 011 /** å ä½ç¬¦ */ 012 private static final String DELIM_STR = "{}"; 013 private static final Object[] EMPTY_ARGS = new Object[0]; 014 015 private static void log(PrintStream printStream,int level, String format, Object ... args){ 016 if(null == printStream || null == format){ 017 return; 018 } 019 if(null == args){ 020 args = EMPTY_ARGS; 021 } 022 StringBuilder buffer = new StringBuilder(format.length() + 64); 023 int beginIndex = 0,endIndex = 0,count = 0; 024 while((endIndex = format.indexOf(DELIM_STR, beginIndex))>=0){ 025 buffer.append(format.substring(beginIndex, endIndex)); 026 try{ 027 buffer.append(args[count++]); 028 }catch(IndexOutOfBoundsException e){ 029 // 数组越界时对应å ä½ç¬¦å¡«null 030 buffer.append("null"); 031 } 032 beginIndex = endIndex + DELIM_STR.length(); 033 } 034 buffer.append(format.substring(beginIndex,format.length())); 035 Thread currentThread = Thread.currentThread(); 036 StackTraceElement stackTrace = currentThread.getStackTrace()[level]; 037 printStream.printf("[%s] (%s:%d) %s\n", 038 currentThread.getName(), 039 stackTrace.getFileName(), 040 stackTrace.getLineNumber(), 041 buffer.toString()); 042 } 043 /** 044 * å‘{@code printStream}输出日志信æ¯<br> 045 * example: 046 * <pre> 047 * log("name : {},age:{}","tom",23); 048 * </pre> 049 * @param printStream 050 * @param format æ ¼å¼å—符串,采用"{}"为å ä½ç¬¦,å ä½ç¬¦ä¸ªæ•°è¦ä¸Ž{@code args}æ•°ç»„é•¿åº¦åŒ¹é… 051 * @param args å¡«å……å ä½ç¬¦çš„傿•°åˆ—表,如果数é‡å°äºŽå ä½ç¬¦ä¸ªæ•°åˆ™å¤šå‡ºçš„å ä½ç¬¦å¡«å……"null" 052 */ 053 public static void log(PrintStream printStream,String format, Object ... args){ 054 log(printStream,3,format,args); 055 } 056 /** 057 * å‘æŽ§åˆ¶å°è¾“出日志信æ¯<br> 058 * @param format æ ¼å¼å—符串,采用"{}"为å ä½ç¬¦ 059 * @param args 060 * @see #log(PrintStream, String, Object...) 061 */ 062 public static void log(String format, Object ... args){ 063 log(System.out,3,format,args); 064 } 065}