日志工厂类
package cn.itcast.utils; import java.util.logging.FileHandler; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.Logger; import java.util.logging.SimpleFormatter; /** * 用静态方法封装的Logger工厂类 * * @author weizh_000 * */ public class LoggerFactory { /** * 生成新的Logger对象 * @return 返回日志对象 */ public static Logger createLogger() { Logger logger = Logger.getLogger(getCallerName()); try { Handler handler = new FileHandler("C:/Users/weizh_000/Desktop/log.log", true); handler.setFormatter(new SimpleFormatter());// 设置日志的格式 logger.addHandler(handler);// 设置操作日志的对象 } catch (Exception e) { e.printStackTrace(); } return logger; } /** * 获取调用者类名 * @return 返回调用者类名 */ private static String getCallerName() { Throwable t = new Throwable(); StackTraceElement caller = t.getStackTrace()[1]; return caller.getClassName(); } }
调用方法:
public class TestCalc { private Logger logger = LoggerFactory.createLogger(); }