1 package org.simantics.audit;
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;
14 import java.util.UUID;
16 import org.slf4j.Logger;
17 import org.slf4j.LoggerFactory;
19 import com.fasterxml.jackson.core.JsonProcessingException;
20 import com.fasterxml.jackson.databind.ObjectMapper;
22 public class AuditLogging {
24 private static final Logger LOGGER = LoggerFactory.getLogger(AuditLogging.class);
26 private static ObjectMapper mapper = new ObjectMapper();
34 public static String register(String id) throws AuditLoggingException {
36 String entryRoot = id + "_" + UUID.randomUUID().toString();
37 Files.createDirectories(getEntryRoot(entryRoot));
39 } catch (Exception e) {
40 throw new AuditLoggingException("Could not register service with id " + id, e);
44 public static List<String> getLogEvents(String uuid, String level, String startDate, String endDate) throws AuditLoggingException {
45 Path entryRoot = getEntryRoot(uuid);
47 LocalDate localStartDate = LocalDate.parse(startDate);
48 LocalDate localEndDate = LocalDate.parse(endDate).plusDays(1);
49 List<String> allLines = new ArrayList<>();
50 while (localStartDate.isBefore(localEndDate)) {
51 String fileName = resolveLogFileName(uuid, Level.valueOf(level.toUpperCase()), localStartDate);
53 List<String> lines = Files.readAllLines(entryRoot.resolve(fileName));
54 allLines.addAll(lines);
55 } catch (FileSystemException e) {
56 // presumably file not found but lets not throw this cause forward, log here
57 LOGGER.error("Could not read file {}", fileName, e);
59 localStartDate = localStartDate.plusDays(1);
63 } catch (Exception e) {
64 throw new AuditLoggingException(e);
69 public static Path getEntryRoot(String uuid) {
70 return Activator.getLogLocation().resolve(uuid);
73 public static Path getLogFile(String uuid, Level level) {
74 Path root = getEntryRoot(uuid);
75 String fileName = resolveLogFileName(uuid, level, LocalDate.now());
76 return root.resolve(fileName);
79 private static String resolveLogFileName(String uuid, Level level, LocalDate date) {
80 return date.toString() + "_" + uuid + "." + level.toString().toLowerCase();
83 public static void log(String uuid, Map<String, Object> json) throws AuditLoggingException {
84 write(uuid, Level.INFO, json);
87 public static void error(String uuid, Map<String, Object> json) throws AuditLoggingException {
88 write(uuid, Level.ERROR, json);
91 public static void trace(String uuid, Map<String, Object> json) throws AuditLoggingException {
92 write(uuid, Level.TRACE, json);
95 private static void write(String uuid, Level level, Map<String, Object> json) throws AuditLoggingException {
96 Map<String, Object> wrappedAuditEvent = wrapAndAddAuditMetadata(uuid, level, json);
98 String jsonLine = mapper.writeValueAsString(wrappedAuditEvent);
99 Path logFile = getLogFile(uuid, level);
100 if (!Files.exists(logFile))
101 Files.createFile(logFile);
102 String lineWithNewline = jsonLine + "\n";
103 Files.write(logFile, lineWithNewline.getBytes(StandardCharsets.UTF_8), StandardOpenOption.WRITE, StandardOpenOption.APPEND);
104 } catch (JsonProcessingException e) {
105 throw new AuditLoggingException("Could not serialize input", e);
106 } catch (IOException e) {
107 throw new AuditLoggingException("Could not write line to log", e);
111 private static final String timestamp = "timestamp";
113 private static Map<String, Object> wrapAndAddAuditMetadata(String uuid, Level level, Map<String, Object> original) {
114 Map<String, Object> wrapped = new HashMap<>();
115 long newValue = System.currentTimeMillis();
116 Object possibleExisting = wrapped.put(timestamp, newValue);
117 if (possibleExisting != null) {
118 LOGGER.warn("Replacing existing value {} for key {} - new value is {}", possibleExisting, timestamp, newValue);
120 possibleExisting = wrapped.put("uuid", uuid);
121 if (possibleExisting != null) {
122 LOGGER.warn("Replacing existing value {} for key {} - new value is {}", possibleExisting, "uuid", uuid);
124 possibleExisting = wrapped.put("level", level.toString());
125 if (possibleExisting != null) {
126 LOGGER.warn("Replacing existing value {} for key {} - new value is {}", possibleExisting, "level", level.toString());
128 wrapped.put("original", original);