import java.io.IOException;
import java.util.logging.*;// 日志级别枚举类
enum LogLevel {INFO,WARNING,ERROR
}public class LogUtil {private static final Logger logger = Logger.getLogger(LogUtil.class.getName());// 设置日志格式static {LogManager.getLogManager().reset();ConsoleHandler consoleHandler = new ConsoleHandler();consoleHandler.setFormatter(new SimpleFormatter());logger.addHandler(consoleHandler);}/*** 记录信息级别的日志* @param message 日志信息*/public static void info(String message) {logger.log(Level.INFO, message);}/*** 记录警告级别的日志* @param message 日志信息*/public static void warning(String message) {logger.log(Level.WARNING, message);}/*** 记录错误级别的日志* @param message 日志信息*/public static void error(String message) {logger.log(Level.SEVERE, message);}/*** 动态设置日志级别* @param logLevel 日志级别*/public static void setLogLevel(LogLevel logLevel) {switch (logLevel) {case INFO:logger.setLevel(Level.INFO);break;case WARNING:logger.setLevel(Level.WARNING);break;case ERROR:logger.setLevel(Level.SEVERE);break;}}/*** 将日志输出到文件* @param filePath 文件路径*/public static void setLogFile(String filePath) {try {FileHandler fileHandler = new FileHandler(filePath);fileHandler.setFormatter(new SimpleFormatter());logger.addHandler(fileHandler);} catch (IOException e) {logger.log(Level.SEVERE, "Failed to set log file.", e);}}/*** 将日志输出到指定的日志处理器* @param logHandler 日志处理器*/public static void setLogHandler(Handler logHandler) {logger.addHandler(logHandler);}/*** 移除指定的日志处理器* @param logHandler 日志处理器*/public static void removeLogHandler(Handler logHandler) {logger.removeHandler(logHandler);}/*** 清除所有的日志处理器*/public static void clearLogHandlers() {Handler[] handlers = logger.getHandlers();for (Handler handler : handlers) {logger.removeHandler(handler);}}
}