publicclassFileLoggerextendsLoggerBaseimplementsLifecycle{ publicvoidstart()throws LifecycleException { // Validate and update our current component state if (started) thrownew LifecycleException(sm.getString("fileLogger.alreadyStarted")); lifecycle.fireLifecycleEvent(START_EVENT, null); started = true; }
publicvoidstop()throws LifecycleException { // Validate and update our current component state if (!started) thrownew LifecycleException(sm.getString("fileLogger.notStarted")); lifecycle.fireLifecycleEvent(STOP_EVENT, null); started = false; close(); } }
publicvoidlog(String msg){ // Construct the timestamp we will use, if requested Timestamp ts = new Timestamp(System.currentTimeMillis()); String tsString = ts.toString().substring(0, 19); String tsDate = tsString.substring(0, 10);
// If the date has changed, switch log files if (!date.equals(tsDate)) { synchronized (this) { if (!date.equals(tsDate)) { close(); date = tsDate; open(); } } }
// Log this message, timestamped if necessary if (writer != null) { if (timestamp) { writer.println(tsString + " " + msg); } else { writer.println(msg); } } }
通常情况下 FileLogger 会操作多个文件,在操作下一个时会把当前的关掉。
The open method
先检查目录是否村子啊,没有就建一个。然后再创建 log 文件的 PrintWriter 并返回。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
privatevoidopen(){
// Create the directory if necessary File dir = new File(directory); if (!dir.isAbsolute()) dir = new File(System.getProperty("catalina.base"), directory); dir.mkdirs();
// Open the current log file try { String pathname = dir.getAbsolutePath() + File.separator + prefix + date + suffix; writer = new PrintWriter(new FileWriter(pathname, true), true); } catch (IOException e) { writer = null; }
}
The close method
很简单,flush IO 流并重制变量
1 2 3 4 5 6 7 8
privatevoidclose(){ if (writer == null) return; writer.flush(); writer.close(); writer = null; date = ""; }
这个案例运行的时候大概卡了快一分钟才执行完,看了 log 原来是有 class 找不到, 应该是我用的 jar 包已经是 Catalina 了,不是 tomcat 了,版本太高
1 2 3 4 5 6 7 8 9 10 11 12 13 14
2021-08-02 10:38:13 HttpProcessor[8080][4] process.invoke java.lang.NoClassDefFoundError: org/apache/tomcat/util/log/SystemLogHandler at org.apache.catalina.connector.RequestBase.recycle(RequestBase.java:562) at org.apache.catalina.connector.HttpRequestBase.recycle(HttpRequestBase.java:417) at org.apache.catalina.connector.http.HttpRequestImpl.recycle(HttpRequestImpl.java:195) at org.apache.catalina.connector.http.HttpProcessor.process(HttpProcessor.java:1101) at org.apache.catalina.connector.http.HttpProcessor.run(HttpProcessor.java:1151) at java.lang.Thread.run(Thread.java:836) Caused by: java.lang.ClassNotFoundException: org.apache.tomcat.util.log.SystemLogHandler at java.net.URLClassLoader.findClass(URLClassLoader.java:444) at java.lang.ClassLoader.loadClass(ClassLoader.java:480) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:384) at java.lang.ClassLoader.loadClass(ClassLoader.java:413) ... 6 more