AppLog.java 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. package com.mes.util;
  2. import java.io.File;
  3. import java.io.PrintStream;
  4. import java.io.FileInputStream;
  5. import java.io.FileOutputStream;
  6. import java.io.IOException;
  7. import java.text.SimpleDateFormat;
  8. import java.util.Date;
  9. import java.util.Properties;
  10. import java.util.concurrent.Executors;
  11. import java.util.concurrent.ScheduledExecutorService;
  12. import java.util.concurrent.TimeUnit;
  13. /** Lightweight local logging for the standalone MES desktop client. */
  14. public final class AppLog {
  15. private static final String APP_NAME = "mesclient-op060B-P02";
  16. private static final Object LOCK = new Object();
  17. private static final SimpleDateFormat TIME = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
  18. private static PrintStream out;
  19. private static File stateFile;
  20. private static ScheduledExecutorService heartbeat;
  21. private static volatile boolean userClose;
  22. private static volatile String exitReason;
  23. private static volatile String uncaughtThread;
  24. private static volatile Throwable uncaughtException;
  25. private AppLog() { }
  26. public static void init() {
  27. synchronized (LOCK) {
  28. if (out != null) return;
  29. try {
  30. File code = new File(AppLog.class.getProtectionDomain().getCodeSource().getLocation().toURI());
  31. File base = code.isFile() ? code.getParentFile() : new File(System.getProperty("user.dir"));
  32. File dir = new File(base, "logs");
  33. if (!dir.exists() && !dir.mkdirs()) return;
  34. stateFile = new File(dir, APP_NAME + ".running");
  35. String day = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
  36. out = new PrintStream(new FileOutputStream(new File(dir, APP_NAME + "-" + day + ".log"), true), true, "UTF-8");
  37. reportPreviousRun();
  38. writeState();
  39. Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
  40. public void uncaughtException(Thread thread, Throwable exception) {
  41. synchronized (LOCK) {
  42. exitReason = "UNCAUGHT_EXCEPTION";
  43. uncaughtThread = thread.getName();
  44. uncaughtException = exception;
  45. log("错误", "未捕获异常,线程=" + clean(uncaughtThread), exception);
  46. }
  47. }
  48. });
  49. Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
  50. public void run() {
  51. synchronized (LOCK) {
  52. if (userClose) {
  53. log("信息", "客户端退出,原因=用户主动正常关闭,状态文件将删除", null);
  54. deleteState();
  55. } else if ("UNCAUGHT_EXCEPTION".equals(exitReason)) {
  56. log("错误", "客户端退出,原因=未捕获异常,线程=" + clean(uncaughtThread), uncaughtException);
  57. } else {
  58. log("错误", "客户端退出,原因=未收到正常关闭标记(可能被任务管理器终止、进程崩溃或系统终止)", null);
  59. }
  60. }
  61. }
  62. }, APP_NAME + "-log-shutdown"));
  63. heartbeat = Executors.newSingleThreadScheduledExecutor(r -> {
  64. Thread thread = new Thread(r, APP_NAME + "-heartbeat");
  65. thread.setDaemon(true);
  66. return thread;
  67. });
  68. heartbeat.scheduleAtFixedRate(() -> {
  69. synchronized (LOCK) { writeState(); }
  70. }, 5, 5, TimeUnit.SECONDS);
  71. } catch (Exception ignored) {
  72. // Logging is best-effort and must not stop client startup.
  73. }
  74. }
  75. }
  76. public static void login(String userId, String method, boolean success) {
  77. log(success ? "信息" : "警告", "登录" + (success ? "成功" : "失败")
  78. + ",方式=" + clean(method) + ",用户=" + clean(userId), null);
  79. }
  80. public static void logout(String userId) {
  81. log("信息", "用户退出,用户=" + clean(userId), null);
  82. }
  83. public static void scan(String type, String code) {
  84. log("信息", "扫码,类型=" + clean(type) + ",内容=" + clean(code), null);
  85. }
  86. public static void work(String action, String code, boolean success) {
  87. log(success ? "信息" : "警告", "操作" + (success ? "成功" : "失败")
  88. + ",动作=" + clean(action) + ",内容=" + clean(code), null);
  89. }
  90. public static void markUserClose() {
  91. synchronized (LOCK) {
  92. if (userClose) return;
  93. userClose = true;
  94. exitReason = "USER_CLOSE";
  95. log("信息", "收到用户主动关闭标记", null);
  96. writeState();
  97. }
  98. }
  99. public static void error(String message, Throwable exception) {
  100. log("错误", message, exception);
  101. }
  102. private static void reportPreviousRun() {
  103. if (stateFile == null || !stateFile.isFile()) return;
  104. Properties state = new Properties();
  105. try (FileInputStream input = new FileInputStream(stateFile)) {
  106. state.load(input);
  107. log("错误", "检测到上次进程未正常关闭(可能被任务管理器结束),进程号="
  108. + clean(state.getProperty("pid")) + ",最后心跳="
  109. + clean(state.getProperty("heartbeat")) + ",状态="
  110. + clean(state.getProperty("status")), null);
  111. } catch (Exception exception) {
  112. log("警告", "无法读取上次运行状态", exception);
  113. }
  114. }
  115. private static void writeState() {
  116. if (stateFile == null) return;
  117. Properties state = new Properties();
  118. state.setProperty("pid", getPid());
  119. state.setProperty("heartbeat", Long.toString(System.currentTimeMillis()));
  120. state.setProperty("status", "RUNNING");
  121. File temporary = new File(stateFile.getParentFile(), stateFile.getName() + ".tmp");
  122. try (FileOutputStream output = new FileOutputStream(temporary)) {
  123. state.store(output, "MES client running state");
  124. } catch (IOException ignored) {
  125. return;
  126. }
  127. if (!temporary.renameTo(stateFile)) {
  128. temporary.delete();
  129. }
  130. }
  131. private static void deleteState() {
  132. if (heartbeat != null) heartbeat.shutdownNow();
  133. if (stateFile != null && stateFile.isFile() && !stateFile.delete()) {
  134. log("警告", "无法删除运行状态文件", null);
  135. }
  136. }
  137. private static String getPid() {
  138. String runtime = java.lang.management.ManagementFactory.getRuntimeMXBean().getName();
  139. int separator = runtime.indexOf('@');
  140. return separator > 0 ? runtime.substring(0, separator) : runtime;
  141. }
  142. private static String clean(String value) {
  143. return value == null ? "" : value.replace('\r', ' ').replace('\n', ' ');
  144. }
  145. private static void log(String level, String message, Throwable exception) {
  146. synchronized (LOCK) {
  147. if (out == null) return;
  148. if (exception != null) {
  149. message += ",异常类型=" + exception.getClass().getName()
  150. + ",详情=" + clean(exception.getMessage());
  151. }
  152. out.println("[" + TIME.format(new Date()) + "][" + level + "]["
  153. + Thread.currentThread().getName() + "] " + message);
  154. out.flush();
  155. }
  156. }
  157. }