CollectedLogger.java 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. package de.jplag.logger;
  2. import java.io.PrintStream;
  3. import java.io.Serial;
  4. import java.text.SimpleDateFormat;
  5. import java.util.ArrayList;
  6. import java.util.Date;
  7. import java.util.concurrent.ConcurrentLinkedDeque;
  8. import org.slf4j.helpers.FormattingTuple;
  9. import org.slf4j.helpers.MarkerIgnoringBase;
  10. import org.slf4j.helpers.MessageFormatter;
  11. import org.slf4j.spi.LocationAwareLogger;
  12. /**
  13. * This logger is able to collect errors and print them at the end. Mainly adopted from org.slf4j.impl.SimpleLogger
  14. * @author Dominik Fuchss
  15. */
  16. public final class CollectedLogger extends MarkerIgnoringBase {
  17. @Serial
  18. private static final long serialVersionUID = -1278670638921140275L;
  19. private static final int LOG_LEVEL_TRACE = LocationAwareLogger.TRACE_INT;
  20. private static final int LOG_LEVEL_DEBUG = LocationAwareLogger.DEBUG_INT;
  21. private static final int LOG_LEVEL_INFO = LocationAwareLogger.INFO_INT;
  22. private static final int LOG_LEVEL_WARN = LocationAwareLogger.WARN_INT;
  23. private static final int LOG_LEVEL_ERROR = LocationAwareLogger.ERROR_INT;
  24. private final int currentLogLevel = LOG_LEVEL_INFO;
  25. /**
  26. * The short name of this simple log instance
  27. */
  28. private transient String shortLogName = null;
  29. /**
  30. * Indicator whether finalization is in progress.
  31. * @see #printAllErrorsForLogger()
  32. */
  33. private transient boolean isFinalizing = false;
  34. private final transient SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-hh:mm:ss_SSS");
  35. private final ConcurrentLinkedDeque<Triple<String, Throwable, Date>> allErrors = new ConcurrentLinkedDeque<>();
  36. CollectedLogger(String name) {
  37. this.name = name;
  38. }
  39. private void log(int level, String message, Throwable throwable) {
  40. log(level, message, throwable, null);
  41. }
  42. private void log(int level, String message, Throwable throwable, Date timeOfError) {
  43. if (!isLevelEnabled(level)) {
  44. return;
  45. }
  46. if (level == LOG_LEVEL_ERROR && !isFinalizing) {
  47. // Buffer errors for the final output
  48. allErrors.add(new Triple<>(message, throwable, new Date()));
  49. return;
  50. }
  51. StringBuilder builder = new StringBuilder(32);
  52. // Append date-time
  53. builder.append(dateFormat.format(timeOfError == null ? new Date() : timeOfError)).append(' ');
  54. // Append current thread name
  55. builder.append('[').append(Thread.currentThread().getName()).append("] ");
  56. // Append current Level
  57. builder.append('[').append(renderLevel(level)).append(']').append(' ');
  58. // Append the name of the log instance
  59. if (shortLogName == null)
  60. shortLogName = computeShortName();
  61. builder.append(shortLogName).append(" - ");
  62. // Append the message
  63. builder.append(message);
  64. write(builder, throwable);
  65. }
  66. void printAllErrorsForLogger() {
  67. this.isFinalizing = true;
  68. // Copy errors to prevent infinite recursion
  69. var errors = new ArrayList<>(this.allErrors);
  70. if (errors.isEmpty())
  71. return;
  72. this.allErrors.removeAll(errors);
  73. info("Summary of all Errors:");
  74. errors.forEach(error -> log(LOG_LEVEL_ERROR, error.first(), error.second(), error.third()));
  75. isFinalizing = false;
  76. }
  77. @SuppressWarnings("java:S106")
  78. void write(StringBuilder buf, Throwable throwable) {
  79. PrintStream targetStream = System.out;
  80. targetStream.println(buf.toString());
  81. writeThrowable(throwable, targetStream);
  82. targetStream.flush();
  83. }
  84. private void writeThrowable(Throwable throwable, PrintStream targetStream) {
  85. if (throwable != null) {
  86. throwable.printStackTrace(targetStream);
  87. }
  88. }
  89. private String computeShortName() {
  90. return name.substring(name.lastIndexOf(".") + 1);
  91. }
  92. private boolean isLevelEnabled(int logLevel) {
  93. return logLevel >= currentLogLevel;
  94. }
  95. private String renderLevel(int level) {
  96. return switch (level) {
  97. case LOG_LEVEL_TRACE -> "TRACE";
  98. case LOG_LEVEL_DEBUG -> "DEBUG";
  99. case LOG_LEVEL_INFO -> "INFO";
  100. case LOG_LEVEL_WARN -> "WARN";
  101. case LOG_LEVEL_ERROR -> "ERROR";
  102. default -> throw new IllegalStateException("Unrecognized level [" + level + "]");
  103. };
  104. }
  105. public boolean isTraceEnabled() {
  106. return isLevelEnabled(LOG_LEVEL_TRACE);
  107. }
  108. @Override
  109. public void trace(String message) {
  110. log(LOG_LEVEL_TRACE, message, null);
  111. }
  112. public void trace(String format, Object param1) {
  113. formatAndLog(LOG_LEVEL_TRACE, format, param1, null);
  114. }
  115. public void trace(String format, Object param1, Object param2) {
  116. formatAndLog(LOG_LEVEL_TRACE, format, param1, param2);
  117. }
  118. public void trace(String format, Object... argArray) {
  119. formatAndLog(LOG_LEVEL_TRACE, format, argArray);
  120. }
  121. public void trace(String message, Throwable t) {
  122. log(LOG_LEVEL_TRACE, message, t);
  123. }
  124. public boolean isDebugEnabled() {
  125. return isLevelEnabled(LOG_LEVEL_DEBUG);
  126. }
  127. public void debug(String message) {
  128. log(LOG_LEVEL_DEBUG, message, null);
  129. }
  130. public void debug(String format, Object param1) {
  131. formatAndLog(LOG_LEVEL_DEBUG, format, param1, null);
  132. }
  133. public void debug(String format, Object param1, Object param2) {
  134. formatAndLog(LOG_LEVEL_DEBUG, format, param1, param2);
  135. }
  136. public void debug(String format, Object... argArray) {
  137. formatAndLog(LOG_LEVEL_DEBUG, format, argArray);
  138. }
  139. public void debug(String message, Throwable throwable) {
  140. log(LOG_LEVEL_DEBUG, message, throwable);
  141. }
  142. public boolean isInfoEnabled() {
  143. return isLevelEnabled(LOG_LEVEL_INFO);
  144. }
  145. public void info(String message) {
  146. log(LOG_LEVEL_INFO, message, null);
  147. }
  148. public void info(String format, Object arg) {
  149. formatAndLog(LOG_LEVEL_INFO, format, arg, null);
  150. }
  151. public void info(String format, Object arg1, Object arg2) {
  152. formatAndLog(LOG_LEVEL_INFO, format, arg1, arg2);
  153. }
  154. public void info(String format, Object... argArray) {
  155. formatAndLog(LOG_LEVEL_INFO, format, argArray);
  156. }
  157. public void info(String message, Throwable throwable) {
  158. log(LOG_LEVEL_INFO, message, throwable);
  159. }
  160. public boolean isWarnEnabled() {
  161. return isLevelEnabled(LOG_LEVEL_WARN);
  162. }
  163. public void warn(String message) {
  164. log(LOG_LEVEL_WARN, message, null);
  165. }
  166. public void warn(String format, Object arg) {
  167. formatAndLog(LOG_LEVEL_WARN, format, arg, null);
  168. }
  169. public void warn(String format, Object arg1, Object arg2) {
  170. formatAndLog(LOG_LEVEL_WARN, format, arg1, arg2);
  171. }
  172. public void warn(String format, Object... argArray) {
  173. formatAndLog(LOG_LEVEL_WARN, format, argArray);
  174. }
  175. public void warn(String message, Throwable throwable) {
  176. log(LOG_LEVEL_WARN, message, throwable);
  177. }
  178. public boolean isErrorEnabled() {
  179. return isLevelEnabled(LOG_LEVEL_ERROR);
  180. }
  181. public void error(String message) {
  182. log(LOG_LEVEL_ERROR, message, null);
  183. }
  184. public void error(String format, Object arg) {
  185. formatAndLog(LOG_LEVEL_ERROR, format, arg, null);
  186. }
  187. public void error(String format, Object arg1, Object arg2) {
  188. formatAndLog(LOG_LEVEL_ERROR, format, arg1, arg2);
  189. }
  190. public void error(String format, Object... argArray) {
  191. formatAndLog(LOG_LEVEL_ERROR, format, argArray);
  192. }
  193. public void error(String message, Throwable throwable) {
  194. log(LOG_LEVEL_ERROR, message, throwable);
  195. }
  196. private void formatAndLog(int level, String format, Object arg1, Object arg2) {
  197. if (!isLevelEnabled(level)) {
  198. return;
  199. }
  200. FormattingTuple formattingTuple = MessageFormatter.format(format, arg1, arg2);
  201. log(level, formattingTuple.getMessage(), formattingTuple.getThrowable());
  202. }
  203. private void formatAndLog(int level, String format, Object... arguments) {
  204. if (!isLevelEnabled(level)) {
  205. return;
  206. }
  207. FormattingTuple formattingTuple = MessageFormatter.arrayFormat(format, arguments);
  208. log(level, formattingTuple.getMessage(), formattingTuple.getThrowable());
  209. }
  210. }