]> gerrit.simantics Code Review - simantics/platform.git/blob - bundles/org.simantics.auditlogging/src/org/simantics/audit/AuditLogging.java
AuditLogging improvements for easier unit testing
[simantics/platform.git] / bundles / org.simantics.auditlogging / src / org / simantics / audit / AuditLogging.java
1 package org.simantics.audit;
2
3 import java.io.IOException;
4 import java.nio.charset.StandardCharsets;
5 import java.nio.file.FileSystemException;
6 import java.nio.file.Files;
7 import java.nio.file.Path;
8 import java.nio.file.StandardOpenOption;
9 import java.time.LocalDate;
10 import java.util.ArrayList;
11 import java.util.HashMap;
12 import java.util.List;
13 import java.util.Map;
14 import java.util.UUID;
15
16 import org.slf4j.Logger;
17 import org.slf4j.LoggerFactory;
18
19 import com.fasterxml.jackson.core.JsonProcessingException;
20 import com.fasterxml.jackson.databind.ObjectMapper;
21
22 public class AuditLogging {
23
24     private static final Logger LOGGER = LoggerFactory.getLogger(AuditLogging.class);
25
26     private static ObjectMapper mapper = new ObjectMapper();
27
28     public enum Level {
29         INFO,
30         ERROR,
31         TRACE
32     }
33
34     public static String register(String id) throws AuditLoggingException {
35         try {
36             String entryRoot = id + "_" + UUID.randomUUID().toString();
37             Files.createDirectories(getEntryRoot(entryRoot));
38             return entryRoot;
39         } catch (Exception e) {
40             throw new AuditLoggingException("Could not register service with id " + id, e);
41         }
42     }
43
44     /**
45      * Gets audit events for the last 5 days
46      * 
47      * @param uuid
48      * @param level
49      * @return
50      * @throws AuditLoggingException
51      */
52     public static List<String> getLogEventsDays(String uuid, String level, int days) throws AuditLoggingException {
53         LocalDate endDate = LocalDate.now().plusDays(1);
54         LocalDate startDate = endDate.minusDays(days);
55         return getLogEvents(uuid, level, startDate, endDate);
56     }
57
58     public static List<String> getLogEvents(String uuid, String level, String startDate, String endDate) throws AuditLoggingException {
59         try {
60             LocalDate localStartDate = LocalDate.parse(startDate);
61             LocalDate localEndDate = LocalDate.parse(endDate).plusDays(1);
62             return getLogEvents(uuid, level, localStartDate, localEndDate);
63         } catch (Exception e) {
64             throw new AuditLoggingException(e);
65         }
66     }
67
68     private static List<String> getLogEvents(String uuid, String level, LocalDate localStartDate, LocalDate localEndDate) throws AuditLoggingException {
69         Path entryRoot = getEntryRoot(uuid);
70         try {
71             List<String> allLines = new ArrayList<>();
72             while (localStartDate.isBefore(localEndDate)) {
73                 String fileName = resolveLogFileName(uuid, Level.valueOf(level.toUpperCase()), localStartDate);
74                 try {
75                     Path fileToRead = entryRoot.resolve(fileName);
76                     if (Files.exists(fileToRead)) {
77                         List<String> lines = Files.readAllLines(fileToRead);
78                         allLines.addAll(lines);
79                     } else {
80                         LOGGER.info("No logging events for " + fileName);
81                     }
82                 } catch (FileSystemException e) {
83                     // presumably file not found but lets not throw this cause forward, log here
84                     LOGGER.error("Could not read file {}", fileName, e);
85                 } finally {
86                     localStartDate = localStartDate.plusDays(1);
87                 }
88             }
89             return allLines;
90         } catch (Exception e) {
91             throw new AuditLoggingException(e);
92         }
93     }
94
95     public static Path getEntryRoot(String uuid) {
96         return Activator.getLogLocation().resolve(uuid);
97     }
98
99     public static Path getLogFile(String uuid, Level level) {
100         Path root = getEntryRoot(uuid);
101         String fileName = resolveLogFileName(uuid, level, LocalDate.now());
102         return root.resolve(fileName);
103     }
104     
105     private static String resolveLogFileName(String uuid, Level level, LocalDate date) {
106         return date.toString() + "_" + uuid + "." + level.toString().toLowerCase();
107     }
108
109     public static void log(String uuid, Map<String, Object> json) throws AuditLoggingException {
110         write(uuid, Level.INFO, json);
111     }
112
113     public static void error(String uuid, Map<String, Object> json) throws AuditLoggingException {
114         write(uuid, Level.ERROR, json);
115     }
116
117     public static void trace(String uuid, Map<String, Object> json) throws AuditLoggingException {
118         write(uuid, Level.TRACE, json);
119     }
120
121     private static void write(String uuid, Level level, Map<String, Object> json) throws AuditLoggingException {
122         Map<String, Object> wrappedAuditEvent = wrapAndAddAuditMetadata(uuid, level, json);
123         try {
124             String jsonLine = mapper.writeValueAsString(wrappedAuditEvent);
125             Path logFile = getLogFile(uuid, level);
126             if (!Files.exists(logFile))
127                 Files.createFile(logFile);
128             String lineWithNewline = jsonLine + "\n";
129             Files.write(logFile, lineWithNewline.getBytes(StandardCharsets.UTF_8), StandardOpenOption.WRITE, StandardOpenOption.APPEND);
130         } catch (JsonProcessingException e) {
131             throw new AuditLoggingException("Could not serialize input", e);
132         } catch (IOException e) {
133             throw new AuditLoggingException("Could not write line to log", e);
134         }
135     }
136
137     private static final String timestamp = "timestamp";
138     
139     private static Map<String, Object> wrapAndAddAuditMetadata(String uuid, Level level, Map<String, Object> original) {
140         Map<String, Object> wrapped = new HashMap<>();
141         long newValue = System.currentTimeMillis();
142         Object possibleExisting = wrapped.put(timestamp, newValue);
143         if (possibleExisting != null) {
144             LOGGER.warn("Replacing existing value {} for key {} - new value is {}", possibleExisting, timestamp, newValue);
145         }
146         possibleExisting = wrapped.put("uuid", uuid);
147         if (possibleExisting != null) {
148             LOGGER.warn("Replacing existing value {} for key {} - new value is {}", possibleExisting, "uuid", uuid);
149         }
150         possibleExisting = wrapped.put("level", level.toString());
151         if (possibleExisting != null) {
152             LOGGER.warn("Replacing existing value {} for key {} - new value is {}", possibleExisting, "level", level.toString());
153         }
154         wrapped.put("original", original);
155         return wrapped;
156     }
157 }