package com.lx.product.seal.log; import java.io.*; import java.text.SimpleDateFormat; import java.util.Date; public class Logger { private Logger() { } private static class LoggerHolder { private static final Logger LOGGER = new Logger(); } private static File logFile; private static OutputStreamWriter loger; public static final int ERROR_TYPE = 0;//错误日志 public static final int INFO_TYPE = 1;//普通日志 public static final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); public static final SimpleDateFormat formats = new SimpleDateFormat("yyyyMMddHHmmss"); public static final SimpleDateFormat formatd = new SimpleDateFormat("yyyyMMdd"); static { File menu = new File("logs"); if (!menu.exists() || !menu.isDirectory()) { menu.mkdirs(); } logFile = new File("logs" + File.separator + "install_" + formats.format(new Date()) + ".log"); if (!logFile.exists()) { System.out.println("日志文件不存在:" + logFile.getAbsolutePath()); try { logFile.createNewFile(); System.out.println("已创建日志文件:" + logFile.getAbsolutePath()); } catch (Exception e) { System.out.println("创建日志文件失败:" + logFile.getAbsolutePath() + "," + e.getMessage()); } } try { loger = new OutputStreamWriter(new FileOutputStream(logFile), "utf-8"); } catch (Exception e) { System.out.println("初始日志文件失败:" + logFile.getAbsolutePath() + "," + e.getMessage()); } } /** * 获取日志实例 * @return */ public static Logger getInstance() { return LoggerHolder.LOGGER; } /** * 写日志 * @param message * @param type * @return */ public boolean writeInfo(String message, int type) { if (loger != null) { try { loger.write("【"); if (type == this.ERROR_TYPE) loger.write("ERROR"); else loger.write("INFO "); loger.write(" " + format.format(new Date())); loger.write("】 "); loger.write(message); loger.write("\r\n"); loger.flush(); return true; } catch (Exception e) { System.out.println("日志写入错误:" + logFile.getAbsolutePath() + "," + e.getMessage()); } } return false; } public void closeLogger() { if (loger != null) { try { loger.close(); } catch (Exception e) { System.out.println("日志写入错误:" + logFile.getAbsolutePath() + "," + e.getMessage()); } } } }