java日志
程序中日志存在目的就是显示运行的状况和故障定位。可以根据自己的程序需要划定日志的级别,日志的输出方式通常时两种:控制台和文本文件。在java中,创建一个属于自己的日志系统的方式是建立一个日志类:
public class Log{ public final static int LOG_LEVEL_DUMP = 1; public final static int LOG_LEVEL_TRACE = 2; public final static int LOG_LEVEL_NORMAL = 3; public final static int LOG_LEVEL_ERROR = 4; public final static int LOG_LEVEL_NONE = 5; protected static boolean log2file = false; protected static boolean log2console = true; protected static String path = "."+File.separator+"log.txt"; protected static int level = LOG_LEVEL_NONE; private Log() { } static public void setLevel(int l) { if((l == LOG_LEVEL_TRACE) || (l == LOG_LEVEL_NORMAL) || (l == LOG_LEVEL_NONE) || (l == LOG_LEVEL_DUMP) || (l == LOG_LEVEL_ERROR)){ level = l; }else{ level = LOG_LEVEL_NORMAL; } } static public void setPath(String s) { path = s; } static public void setFile(boolean b) { log2file = b; } static public void setConsole(boolean b) { log2console = b; } static public int getLevel() { return level; } static public String getPath() { return path; } static public boolean getConsole() { return log2console; } static public boolean getFile() { return log2file; } static public void logException(String event, Exception e) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(bos); e.printStackTrace(ps); ps.close(); log(Log_LEVEL_ERROR, event+e+":"+bos); try{ bos.close(); }catch(IOException f) {} } synchronized static public void log(int level, String event) { if(level == LOG_LEVEL_NONE) return; if(level<log.level) return; Date dt = new Date(); String log = "[" + dt.toString() + "] ["; switch(level) { case LOG_LEVEL_TRACE: log+="TRACE";break; case LOG_LEVEL_NORMAL: log+="NORMAL";break; case LOG_LEVEL_ERROR: log+="ERROR";break; case LOG_LEVEL_NONE: log+="NONE"; break; case LOG_LEVEL_DUMP: log+="DUMP"; break; } log+="] ["+Thread.currentThread().getName()+"]"+event; if(log2console) System.out,println(log); if(log2file) { try{ FileOutputStream fw = new FileOutputStream(path, true); PrintStream ps = new PrintStream(fw); ps.println(log); ps.close(); fw.close(); }catch(IOException e){} } } }