826220679@qq.com
2025-08-07 4d6cd980c5c69e4d9d150669c89734642297e0cd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package main;
 
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date; // ÐÞ¸´£ºÊ¹Óàjava.util.Date ¶ø²»ÊÇ java.sql.Date
import java.text.SimpleDateFormat;
 
/**
 * ÈÕÖ¾¼Ç¼¹¤¾ßÀà
 */
public class LogUtil {
    private static final String LOG_DIR = "systemfile/logfile";
    private static final String LOG_FILE = LOG_DIR + "/openlog.txt";
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    
    /**
     * ¼Ç¼³ÌÐòÆô¶¯ÈÕÖ¾
     */
    public static void logOpen() {
        ensureLogDirExists();
        String timestamp = DATE_FORMAT.format(new Date());
        writeLog("³ÌÐòÆô¶¯: " + timestamp + "\n");
    }
    
    /**
     * ¼Ç¼³ÌÐò¹Ø±ÕÈÕÖ¾²¢¼ÆË㹤×÷ʱ³¤
     * @param startTime ³ÌÐòÆô¶¯Ê±¼ä´Á
     */
    public static void logClose(long startTime) {
        ensureLogDirExists();
        long endTime = System.currentTimeMillis();
        String closeTime = DATE_FORMAT.format(new Date(endTime));
        
        // ¼ÆË㹤×÷ʱ³¤
        long duration = endTime - startTime;
        String durationStr = formatDuration(duration);
        
        String log = "³ÌÐò¹Ø±Õ: " + closeTime + "\n" +
                     "¹¤×÷ʱ³¤: " + durationStr + "\n" +
                     "-----------------------------------\n";
        writeLog(log);
    }
    
    /**
     * È·±£ÈÕ־Ŀ¼´æÔÚ
     */
    private static void ensureLogDirExists() {
        File dir = new File(LOG_DIR);
        if (!dir.exists()) {
            boolean created = dir.mkdirs(); // ´´½¨¶à¼¶Ä¿Â¼
            if (!created) {
                System.err.println("ÎÞ·¨´´½¨ÈÕ־Ŀ¼: " + LOG_DIR);
            }
        }
    }
    
    /**
     * ¸ñʽ»¯Ê±³¤£¨ºÁÃë¡ú¿É¶Á×Ö·û´®£©
     */
    private static String formatDuration(long millis) {
        long seconds = millis / 1000;
        long hours = seconds / 3600;
        long minutes = (seconds % 3600) / 60;
        seconds = seconds % 60;
        return String.format("%dСʱ %d·ÖÖÓ %dÃë", hours, minutes, seconds);
    }
    
    /**
     * Ð´ÈëÈÕÖ¾µ½Îļþ£¨×·¼Óģʽ£©
     */
    private static void writeLog(String content) {
        try (FileWriter fw = new FileWriter(LOG_FILE, true);
             BufferedWriter bw = new BufferedWriter(fw)) {
            bw.write(content);
            bw.flush(); // È·±£ÄÚÈÝÁ¢¼´Ð´Èë
        } catch (IOException e) {
            System.err.println("дÈëÈÕ־ʧ°Ü: " + e.getMessage());
        }
    }
}