| 1 | package be.nikiroo.utils; |
| 2 | |
| 3 | /** |
| 4 | * A handler when a trace message is sent or when a recoverable exception was |
| 5 | * caught by the program. |
| 6 | * |
| 7 | * @author niki |
| 8 | */ |
| 9 | public class TraceHandler { |
| 10 | private boolean showErrors; |
| 11 | private boolean showTraces; |
| 12 | private boolean showErrorDetails; |
| 13 | |
| 14 | /** |
| 15 | * Create a default {@link TraceHandler} that will print errors on stderr |
| 16 | * (without details) and no traces. |
| 17 | */ |
| 18 | public TraceHandler() { |
| 19 | this(true, false, false); |
| 20 | } |
| 21 | |
| 22 | /** |
| 23 | * Create a default {@link TraceHandler}. |
| 24 | * |
| 25 | * @param showErrors |
| 26 | * show errors on stderr |
| 27 | * @param showErrorDetails |
| 28 | * show more details when printing errors |
| 29 | * @param showTraces |
| 30 | * show traces on stdout |
| 31 | */ |
| 32 | public TraceHandler(boolean showErrors, boolean showErrorDetails, |
| 33 | boolean showTraces) { |
| 34 | this.showErrors = showErrors; |
| 35 | this.showErrorDetails = showErrorDetails; |
| 36 | this.showTraces = showTraces; |
| 37 | } |
| 38 | |
| 39 | /** |
| 40 | * An exception happened, log it. |
| 41 | * |
| 42 | * @param e |
| 43 | * the exception |
| 44 | */ |
| 45 | public void error(Exception e) { |
| 46 | if (showErrors) { |
| 47 | if (showErrorDetails) { |
| 48 | e.printStackTrace(); |
| 49 | } else { |
| 50 | error(e.getMessage()); |
| 51 | } |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | /** |
| 56 | * An error happened, log it. |
| 57 | * |
| 58 | * @param message |
| 59 | * the error message |
| 60 | */ |
| 61 | public void error(String message) { |
| 62 | if (showErrors) { |
| 63 | System.err.println(message); |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | /** |
| 68 | * A trace happened, show it. |
| 69 | * <p> |
| 70 | * Will only be effective if {@link TraceHandler#showTraces} is true. |
| 71 | * |
| 72 | * @param message |
| 73 | * the trace message |
| 74 | */ |
| 75 | public void trace(String message) { |
| 76 | if (showTraces) { |
| 77 | System.out.println(message); |
| 78 | } |
| 79 | } |
| 80 | } |