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}