java.util.logging无配置文件全局日志管理案例
程序员文章站
2022-05-03 22:30:44
...
程序运行日志对调试程序很有用,JDK提供日志记录功能,网上很多讲述JDK日志功能的帖子只是代码片段,这里提供一个比较完整的案例,主要是注重几个日志相关的类之互相配合使用的关系。代码比较简单,类的说明在手册里也有,就不解释了。
package Town; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.logging.*; /* * Created with IntelliJ IDEA. * User: cobra * Date: 15-12-3 * Time: 下午4:16 * To change this template use File | Settings | File Templates. */ public class TraceLog { private String LogPath ="E:\\data\\Logs\\lucom\\"; private int logCount = 5; private int LogLimit = 10000000; //指定要写入到任意文件的近似最大量(以字节为单位) 10M private static LogManager logManager = LogManager.getLogManager(); private static Logger InfoLog; private static Logger ErrLog; public TraceLog () { if (logManager.getLogger("LogInfo") == null) { iniInfoLog(); } else { InfoLog = logManager.getLogger("LogInfo"); } if (logManager.getLogger("LogErr") == null) { iniErrLog(); } else { ErrLog = logManager.getLogger("LogErr"); } } //初始化info日志 private void iniInfoLog () { String InfoLogFile = "traceinfo%g.%u.log"; InfoLog = Logger.getLogger("LogInfo"); try { FileHandler InfoFileHandler = new FileHandler(LogPath+InfoLogFile , LogLimit, logCount,true); InfoFileHandler.setLevel(Level.INFO); InfoFileHandler.setFormatter(new Formatter() { @Override public String format(LogRecord record) { return (new SimpleDateFormat("[yyyy-MM-dd HH:mm:ss.SSS]").format(new Date()))+":"+record.getLevel()+":"+record.getMessage()+"\n"; } }); InfoLog.addHandler(InfoFileHandler); logManager.addLogger(InfoLog); } catch (IOException e) { e.printStackTrace(); } } //初始化Err日志 private void iniErrLog () { String ErrLogFile = "traceerr%g.%u.log"; ErrLog = Logger.getLogger("LogErr"); try { FileHandler ErrFileHandler = new FileHandler(LogPath+ErrLogFile , LogLimit,logCount,true); ErrFileHandler.setLevel(Level.WARNING); ErrFileHandler.setFormatter(new Formatter() { @Override public String format(LogRecord record) { return (new SimpleDateFormat("[yyyy-MM-dd HH:mm:ss.SSS]").format(new Date()))+":"+record.getLevel()+":"+record.getMessage()+"\n"; } }); ErrLog.addHandler(ErrFileHandler); logManager.addLogger(ErrLog); } catch (IOException e) { e.printStackTrace(); } } public void logInfo (String LoggingMessage) { InfoLog.info(LoggingMessage); } public void logErr (String LoggingMessage) { ErrLog.warning(LoggingMessage); } }
上一篇: 知道你们两个出去干啥
下一篇: 身体和灵魂,总有一个在路上