package org.sonarsource.scanner.cli;
import java.io.PrintStream;
+import java.time.LocalTime;
+import java.time.format.DateTimeFormatter;
public class Logs {
+ private DateTimeFormatter timeFormatter;
private boolean debugEnabled = false;
private boolean displayStackTrace = false;
private PrintStream stdOut;
public Logs(PrintStream stdOut, PrintStream stdErr) {
this.stdErr = stdErr;
this.stdOut = stdOut;
+ this.timeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss.SSS");
}
public void setDebugEnabled(boolean debugEnabled) {
public void setDisplayStackTrace(boolean displayStackTrace) {
this.displayStackTrace = displayStackTrace;
}
-
+
public boolean isDebugEnabled() {
return debugEnabled;
}
public void debug(String message) {
if (isDebugEnabled()) {
- stdOut.println("DEBUG: " + message);
+ LocalTime currentTime = LocalTime.now();
+ String timestamp = currentTime.format(timeFormatter);
+ stdOut.println(timestamp + " DEBUG: " + message);
}
}
public void info(String message) {
- stdOut.println("INFO: " + message);
+ print(stdOut, "INFO: " + message);
}
public void warn(String message) {
- stdOut.println("WARN: " + message);
+ print(stdErr, "WARN: " + message);
}
public void error(String message) {
- stdErr.println("ERROR: " + message);
+ print(stdErr, "ERROR: " + message);
}
public void error(String message, Throwable t) {
- stdErr.println("ERROR: " + message);
+ print(stdErr, "ERROR: " + message);
if (t != null && displayStackTrace) {
t.printStackTrace(stdErr);
}
}
+
+ private void print(PrintStream stream, String msg) {
+ if (debugEnabled) {
+ LocalTime currentTime = LocalTime.now();
+ String timestamp = currentTime.format(timeFormatter);
+ stream.println(timestamp + " " + msg);
+ } else {
+ stream.println(msg);
+ }
+ }
}
import org.junit.Before;
import org.junit.Test;
+import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.sonarsource.scanner.cli.Logs;
verify(stdOut).println("INFO: info");
verifyNoMoreInteractions(stdOut, stdErr);
}
-
+
@Test
public void testError() {
Exception e = new NullPointerException("exception");
logs.setDisplayStackTrace(false);
logs.error("error1");
verify(stdErr).println("ERROR: error1");
-
+
logs.error("error2", e);
verify(stdErr).println("ERROR: error2");
-
+
verifyNoMoreInteractions(stdOut, stdErr);
-
+
logs.setDisplayStackTrace(true);
logs.error("error3", e);
verify(stdErr).println("ERROR: error3");
logs.setDebugEnabled(true);
logs.debug("debug");
- verify(stdOut).println("DEBUG: debug");
+ verify(stdOut).println(Matchers.matches("\\d\\d:\\d\\d:\\d\\d.\\d\\d\\d DEBUG: debug$"));
logs.setDebugEnabled(false);
logs.debug("debug");