[关闭]
@DevWiki 2015-08-05T20:27:59.000000Z 字数 1362 阅读 1005

Java简易的Log

Java


在写代码时,经常打印一些信息用于调试,我经常使用System.out.println()打印,但是有一个问题,打印的信息多的时候就很难找到输出的位置,为了方便找到打印的位置,写了个简易的Log类,以后有机会在添加功能.

Java简易的Log类如下:

  1. public class Log {
  2. private static final char TOP_LEFT_CORNER = '╔';
  3. private static final char BOTTOM_LEFT_CORNER = '╚';
  4. private static final char HORIZONTAL_DOUBLE_LINE = '║';
  5. private static final String DOUBLE_DIVIDER = "════════════════════════════════════════════";
  6. private static final String TOP_BORDER = TOP_LEFT_CORNER + DOUBLE_DIVIDER + DOUBLE_DIVIDER;
  7. private static final String BOTTOM_BORDER = BOTTOM_LEFT_CORNER + DOUBLE_DIVIDER + DOUBLE_DIVIDER;
  8. private Log(){}
  9. private static String createInfo(String msg){
  10. StringBuffer buffer = new StringBuffer();
  11. StackTraceElement element = new Throwable().getStackTrace()[2];
  12. String className = element.getClassName();
  13. String methodName = element.getMethodName();
  14. int lineNum = element.getLineNumber();
  15. buffer.append(HORIZONTAL_DOUBLE_LINE);
  16. buffer.append(" ");
  17. buffer.append(className);
  18. buffer.append("[");
  19. buffer.append(methodName);
  20. buffer.append(":");
  21. buffer.append(lineNum);
  22. buffer.append("]");
  23. buffer.append(msg);
  24. return buffer.toString();
  25. }
  26. public static void info(String msg){
  27. System.out.println(TOP_BORDER);
  28. System.out.println(HORIZONTAL_DOUBLE_LINE);
  29. System.out.println(createInfo(msg));
  30. System.out.println(HORIZONTAL_DOUBLE_LINE);
  31. System.out.println(BOTTOM_BORDER);
  32. }
  33. }

测试类如下:

  1. public class Client {
  2. public static void main(String[] args) {
  3. Log.info("123");
  4. Log.info("测试...");
  5. }
  6. }

显示结果如下:

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注