From 022e977ba612518b5d4500496bb4d93b134e4b5c Mon Sep 17 00:00:00 2001 From: orhanobut Date: Sun, 2 Aug 2015 11:53:30 +0200 Subject: [PATCH 1/2] tests --- gradle.properties | 4 +- logger/build.gradle | 7 ++ .../java/com/orhanobut/logger/LoggerTest.java | 98 ------------------- logger/src/main/AndroidManifest.xml | 5 +- .../java/com/orhanobut/logger/Settings.java | 91 ++++++++--------- .../java/com.orhanobut.logger/LoggerTest.java | 43 ++++++++ .../com.orhanobut.logger/SettingsTest.java | 82 ++++++++++++++++ 7 files changed, 182 insertions(+), 148 deletions(-) delete mode 100644 logger/src/androidTest/java/com/orhanobut/logger/LoggerTest.java create mode 100644 logger/src/test/java/com.orhanobut.logger/LoggerTest.java create mode 100644 logger/src/test/java/com.orhanobut.logger/SettingsTest.java diff --git a/gradle.properties b/gradle.properties index ecd77286..0f95cc27 100644 --- a/gradle.properties +++ b/gradle.properties @@ -18,8 +18,8 @@ # org.gradle.parallel=true #VERSION_NAME=1.0-SNAPSHOT -VERSION_NAME=1.10 -VERSION_CODE=11 +VERSION_NAME=1.11 +VERSION_CODE=12 GROUP=com.orhanobut POM_DESCRIPTION=Simple,pretty and powerful log diff --git a/logger/build.gradle b/logger/build.gradle index 27e75ed2..f1ad6959 100644 --- a/logger/build.gradle +++ b/logger/build.gradle @@ -15,4 +15,11 @@ android { } } +dependencies { + testCompile 'junit:junit:4.12' + testCompile "org.mockito:mockito-core:1.9.5" + testCompile "org.robolectric:robolectric:3.0" + testCompile 'org.assertj:assertj-core:1.7.0' +} + apply from: '../maven_push.gradle' \ No newline at end of file diff --git a/logger/src/androidTest/java/com/orhanobut/logger/LoggerTest.java b/logger/src/androidTest/java/com/orhanobut/logger/LoggerTest.java deleted file mode 100644 index 75ec973e..00000000 --- a/logger/src/androidTest/java/com/orhanobut/logger/LoggerTest.java +++ /dev/null @@ -1,98 +0,0 @@ -package com.orhanobut.logger; - -import junit.framework.Assert; -import junit.framework.TestCase; - -/** - * @author Orhan Obut - */ -public class LoggerTest extends TestCase { - - public void testSetTag() { - try { - Logger.init(null); - fail(); - } catch (Exception e) { - Assert.assertTrue(true); - } - try { - Logger.init(""); - fail(); - } catch (Exception e) { - Assert.assertTrue(true); - } - try { - Logger.init("test"); - Assert.assertTrue(true); - } catch (Exception e) { - fail(); - } - } - - public void testJson() { - Logger.json("{\"test\":\"test\"}"); - } - - public void testXmlLogger() { - Logger.xml("" + - "Tove" + - "Jani" + - "Reminder" + - "Don't forget me this weekend!" + - ""); - } - - public void testEmptyXml() { - Logger.xml(" "); - } - - public void testNegativeMethodCount() { - try { - Logger.t(-10).d("test"); - fail(); - } catch (Exception e) { - Assert.assertTrue(true); - } - } - - public void testTagShouldNotBeNull() { - try { - Logger.init(null); - fail(); - } catch (Exception e) { - Assert.assertTrue(true); - } - } - - public void testStackTraceWithHugeMethodCount() { - try { - Logger.init("test").setMethodCount(40); - Assert.assertTrue(true); - } catch (Exception e) { - fail(); - } - } - - public void testSetMethodOffset() { - try { - Logger.init().setMethodOffset(100); - Assert.assertTrue(true); - } catch (Exception e) { - fail(); - } - try { - Logger.init().setMethodOffset(0); - Assert.assertTrue(true); - } catch (Exception e) { - fail(); - } - try { - Logger.init() - .setMethodCount(100) - .setMethodOffset(100); - Assert.assertTrue(true); - } catch (Exception e) { - fail(); - } - } -} diff --git a/logger/src/main/AndroidManifest.xml b/logger/src/main/AndroidManifest.xml index 42718b61..14deb93b 100644 --- a/logger/src/main/AndroidManifest.xml +++ b/logger/src/main/AndroidManifest.xml @@ -1,6 +1,3 @@ - - - + diff --git a/logger/src/main/java/com/orhanobut/logger/Settings.java b/logger/src/main/java/com/orhanobut/logger/Settings.java index fb359afb..3292f491 100644 --- a/logger/src/main/java/com/orhanobut/logger/Settings.java +++ b/logger/src/main/java/com/orhanobut/logger/Settings.java @@ -5,48 +5,51 @@ */ public final class Settings { - private int methodCount = 2; - private boolean showThreadInfo = true; - private int methodOffset = 0; - - /** - * Determines how logs will printed - */ - private LogLevel logLevel = LogLevel.FULL; - - public Settings hideThreadInfo() { - showThreadInfo = false; - return this; - } - - public Settings setMethodCount(int methodCount) { - this.methodCount = methodCount; - return this; - } - - public Settings setLogLevel(LogLevel logLevel) { - this.logLevel = logLevel; - return this; - } - - public Settings setMethodOffset(int offset) { - this.methodOffset = offset; - return this; - } - - public int getMethodCount() { - return methodCount; - } - - public boolean isShowThreadInfo() { - return showThreadInfo; - } - - public LogLevel getLogLevel() { - return logLevel; - } - - public int getMethodOffset() { - return methodOffset; - } + private int methodCount = 2; + private boolean showThreadInfo = true; + private int methodOffset = 0; + + /** + * Determines how logs will printed + */ + private LogLevel logLevel = LogLevel.FULL; + + public Settings hideThreadInfo() { + showThreadInfo = false; + return this; + } + + public Settings setMethodCount(int methodCount) { + if (methodCount < 0) { + methodCount = 0; + } + this.methodCount = methodCount; + return this; + } + + public Settings setLogLevel(LogLevel logLevel) { + this.logLevel = logLevel; + return this; + } + + public Settings setMethodOffset(int offset) { + this.methodOffset = offset; + return this; + } + + public int getMethodCount() { + return methodCount; + } + + public boolean isShowThreadInfo() { + return showThreadInfo; + } + + public LogLevel getLogLevel() { + return logLevel; + } + + public int getMethodOffset() { + return methodOffset; + } } diff --git a/logger/src/test/java/com.orhanobut.logger/LoggerTest.java b/logger/src/test/java/com.orhanobut.logger/LoggerTest.java new file mode 100644 index 00000000..01043915 --- /dev/null +++ b/logger/src/test/java/com.orhanobut.logger/LoggerTest.java @@ -0,0 +1,43 @@ +package com.orhanobut.logger; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricGradleTestRunner; +import org.robolectric.annotation.Config; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * @author Orhan Obut + */ +@RunWith(RobolectricGradleTestRunner.class) +@Config(constants = BuildConfig.class, sdk = 21) +public class LoggerTest { + + @Test + public void testInit() { + Settings settings = Logger.init(); + assertThat(settings).isInstanceOf(Settings.class); + + settings = Logger.init("TAG"); + assertThat(settings).isInstanceOf(Settings.class); + } + + @Test + public void testT() { + Settings settings = Logger.t("tag").getSettings(); + + assertThat(settings.getMethodCount()).isEqualTo(2); + + settings = Logger.t(10).getSettings(); + assertThat(settings.getMethodCount()).isEqualTo(2); + + settings = Logger.t("tag", 5).getSettings(); + assertThat(settings.getMethodCount()).isEqualTo(2); + + Logger.init().setMethodCount(0); + settings = Logger.t("tag").getSettings(); + assertThat(settings.getMethodCount()).isEqualTo(0); + } + +} diff --git a/logger/src/test/java/com.orhanobut.logger/SettingsTest.java b/logger/src/test/java/com.orhanobut.logger/SettingsTest.java new file mode 100644 index 00000000..257b0c12 --- /dev/null +++ b/logger/src/test/java/com.orhanobut.logger/SettingsTest.java @@ -0,0 +1,82 @@ +package com.orhanobut.logger; + +import junit.framework.TestCase; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricGradleTestRunner; +import org.robolectric.annotation.Config; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * @author Orhan Obut + */ +@RunWith(RobolectricGradleTestRunner.class) +@Config(constants = BuildConfig.class, sdk = 21) +public class SettingsTest extends TestCase { + + private Settings settings; + + @Before + public void setup() { + settings = new Settings(); + } + + @After + public void tearDown() { + settings = null; + } + + @Test + public void testDefaultShowThreadInfo() { + assertThat(settings.isShowThreadInfo()).isTrue(); + } + + @Test + public void testCustomShowThreadInfo() { + settings.hideThreadInfo(); + assertThat(settings.isShowThreadInfo()).isFalse(); + } + + @Test + public void testDefaultLogLevel() { + assertThat(settings.getLogLevel()).isEqualTo(LogLevel.FULL); + } + + @Test + public void testCustomLogLevel() { + settings.setLogLevel(LogLevel.NONE); + assertThat(settings.getLogLevel()).isEqualTo(LogLevel.NONE); + + settings.setLogLevel(LogLevel.FULL); + assertThat(settings.getLogLevel()).isEqualTo(LogLevel.FULL); + } + + @Test + public void testMethodCount() { + //default + assertThat(settings.getMethodCount()).isEqualTo(2); + + settings.setMethodCount(4); + assertThat(settings.getMethodCount()).isEqualTo(4); + + //negative values should be convert to 0 + settings.setMethodCount(-10); + assertThat(settings.getMethodCount()).isEqualTo(0); + } + + @Test + public void testMethodOffset() { + //default + assertThat(settings.getMethodOffset()).isEqualTo(0); + + settings.setMethodOffset(10); + assertThat(settings.getMethodOffset()).isEqualTo(10); + + settings.setMethodOffset(-10); + assertThat(settings.getMethodOffset()).isEqualTo(-10); + } +} From ebba488b6370be4e90ce4c861c3cf2a4b53e63c1 Mon Sep 17 00:00:00 2001 From: orhanobut Date: Sun, 2 Aug 2015 11:57:36 +0200 Subject: [PATCH 2/2] tests --- .travis.yml | 16 + build.gradle | 2 +- logger/build.gradle | 20 +- logger/src/main/AndroidManifest.xml | 2 +- .../java/com/orhanobut/logger/LogLevel.java | 16 +- .../java/com/orhanobut/logger/Logger.java | 164 ++--- .../com/orhanobut/logger/LoggerPrinter.java | 640 +++++++++--------- .../java/com/orhanobut/logger/Printer.java | 24 +- 8 files changed, 449 insertions(+), 435 deletions(-) create mode 100644 .travis.yml diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 00000000..12e0a08e --- /dev/null +++ b/.travis.yml @@ -0,0 +1,16 @@ +language: android + +android: + components: + - build-tools-21.1.1 + - android-18 + licenses: + - 'android-sdk-license-.+' + +notifications: + email: true + +sudo: false + +script: +- ./gradlew test \ No newline at end of file diff --git a/build.gradle b/build.gradle index 8be31ce9..211664dd 100644 --- a/build.gradle +++ b/build.gradle @@ -5,7 +5,7 @@ buildscript { jcenter() } dependencies { - classpath 'com.android.tools.build:gradle:1.1.0' + classpath 'com.android.tools.build:gradle:1.2.3' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files diff --git a/logger/build.gradle b/logger/build.gradle index f1ad6959..cf90e90e 100644 --- a/logger/build.gradle +++ b/logger/build.gradle @@ -1,18 +1,16 @@ apply plugin: 'com.android.library' android { - compileSdkVersion 21 - buildToolsVersion "21.1.2" + compileSdkVersion 21 + buildToolsVersion "21.1.1" - defaultConfig { - minSdkVersion 8 - targetSdkVersion 21 - versionCode 1 - versionName "1.0" - } + defaultConfig { + minSdkVersion 8 + targetSdkVersion 21 + } - lintOptions { - abortOnError false - } + lintOptions { + abortOnError false + } } dependencies { diff --git a/logger/src/main/AndroidManifest.xml b/logger/src/main/AndroidManifest.xml index 14deb93b..206c6db8 100644 --- a/logger/src/main/AndroidManifest.xml +++ b/logger/src/main/AndroidManifest.xml @@ -1,3 +1,3 @@ - + \ No newline at end of file diff --git a/logger/src/main/java/com/orhanobut/logger/LogLevel.java b/logger/src/main/java/com/orhanobut/logger/LogLevel.java index 54e86f30..1ba680b3 100644 --- a/logger/src/main/java/com/orhanobut/logger/LogLevel.java +++ b/logger/src/main/java/com/orhanobut/logger/LogLevel.java @@ -5,13 +5,13 @@ */ public enum LogLevel { - /** - * Prints all logs - */ - FULL, + /** + * Prints all logs + */ + FULL, - /** - * No log will be printed - */ - NONE + /** + * No log will be printed + */ + NONE } diff --git a/logger/src/main/java/com/orhanobut/logger/Logger.java b/logger/src/main/java/com/orhanobut/logger/Logger.java index 8cf03f1a..c16194b4 100644 --- a/logger/src/main/java/com/orhanobut/logger/Logger.java +++ b/logger/src/main/java/com/orhanobut/logger/Logger.java @@ -8,87 +8,87 @@ */ public final class Logger { - private static final Printer printer = new LoggerPrinter(); - private static final String DEFAULT_TAG = "PRETTYLOGGER"; - - //no instance - private Logger() { - } - - /** - * It is used to get the settings object in order to change settings - * - * @return the settings object - */ - public static Settings init() { - return printer.init(DEFAULT_TAG); - } - - /** - * It is used to change the tag - * - * @param tag is the given string which will be used in Logger - */ - public static Settings init(String tag) { - return printer.init(tag); - } - - public static Printer t(String tag) { - return printer.t(tag, printer.getSettings().getMethodCount()); - } - - public static Printer t(int methodCount) { - return printer.t(null, methodCount); - } - - public static Printer t(String tag, int methodCount) { - return printer.t(tag, methodCount); - } - - public static void d(String message, Object... args) { - printer.d(message, args); - } - - public static void e(String message, Object... args) { - printer.e(null, message, args); - } - - public static void e(Throwable throwable, String message, Object... args) { - printer.e(throwable, message, args); - } - - public static void i(String message, Object... args) { - printer.i(message, args); - } - - public static void v(String message, Object... args) { - printer.v(message, args); - } - - public static void w(String message, Object... args) { - printer.w(message, args); - } - - public static void wtf(String message, Object... args) { - printer.wtf(message, args); - } - - /** - * Formats the json content and print it - * - * @param json the json content - */ - public static void json(String json) { - printer.json(json); - } - - /** - * Formats the json content and print it - * - * @param xml the xml content - */ - public static void xml(String xml) { - printer.xml(xml); - } + private static final Printer printer = new LoggerPrinter(); + private static final String DEFAULT_TAG = "PRETTYLOGGER"; + + //no instance + private Logger() { + } + + /** + * It is used to get the settings object in order to change settings + * + * @return the settings object + */ + public static Settings init() { + return printer.init(DEFAULT_TAG); + } + + /** + * It is used to change the tag + * + * @param tag is the given string which will be used in Logger + */ + public static Settings init(String tag) { + return printer.init(tag); + } + + public static Printer t(String tag) { + return printer.t(tag, printer.getSettings().getMethodCount()); + } + + public static Printer t(int methodCount) { + return printer.t(null, methodCount); + } + + public static Printer t(String tag, int methodCount) { + return printer.t(tag, methodCount); + } + + public static void d(String message, Object... args) { + printer.d(message, args); + } + + public static void e(String message, Object... args) { + printer.e(null, message, args); + } + + public static void e(Throwable throwable, String message, Object... args) { + printer.e(throwable, message, args); + } + + public static void i(String message, Object... args) { + printer.i(message, args); + } + + public static void v(String message, Object... args) { + printer.v(message, args); + } + + public static void w(String message, Object... args) { + printer.w(message, args); + } + + public static void wtf(String message, Object... args) { + printer.wtf(message, args); + } + + /** + * Formats the json content and print it + * + * @param json the json content + */ + public static void json(String json) { + printer.json(json); + } + + /** + * Formats the json content and print it + * + * @param xml the xml content + */ + public static void xml(String xml) { + printer.xml(xml); + } } diff --git a/logger/src/main/java/com/orhanobut/logger/LoggerPrinter.java b/logger/src/main/java/com/orhanobut/logger/LoggerPrinter.java index 7cd33994..18f402c3 100644 --- a/logger/src/main/java/com/orhanobut/logger/LoggerPrinter.java +++ b/logger/src/main/java/com/orhanobut/logger/LoggerPrinter.java @@ -26,354 +26,354 @@ */ final class LoggerPrinter implements Printer { - /** - * Android's max limit for a log entry is ~4076 bytes, - * so 4000 bytes is used as chunk size since default charset - * is UTF-8 - */ - private static final int CHUNK_SIZE = 4000; - - /** - * It is used for json pretty print - */ - private static final int JSON_INDENT = 4; - - /** - * The minimum stack trace index, starts at this class after two native calls. - */ - private static final int MIN_STACK_OFFSET = 3; - - /** - * It is used to determine log settings such as method count, thread info visibility - */ - private static final Settings settings = new Settings(); - - /** - * Drawing toolbox - */ - private static final char TOP_LEFT_CORNER = '╔'; - private static final char BOTTOM_LEFT_CORNER = '╚'; - private static final char MIDDLE_CORNER = '╟'; - private static final char HORIZONTAL_DOUBLE_LINE = '║'; - private static final String DOUBLE_DIVIDER = "════════════════════════════════════════════"; - private static final String SINGLE_DIVIDER = "────────────────────────────────────────────"; - private static final String TOP_BORDER = TOP_LEFT_CORNER + DOUBLE_DIVIDER + DOUBLE_DIVIDER; - private static final String BOTTOM_BORDER = BOTTOM_LEFT_CORNER + DOUBLE_DIVIDER + DOUBLE_DIVIDER; - private static final String MIDDLE_BORDER = MIDDLE_CORNER + SINGLE_DIVIDER + SINGLE_DIVIDER; - - /** - * TAG is used for the Log, the name is a little different - * in order to differentiate the logs easily with the filter - */ - private static String TAG = "PRETTYLOGGER"; - - /** - * Localize single tag and method count for each thread - */ - private static final ThreadLocal LOCAL_TAG = new ThreadLocal<>(); - private static final ThreadLocal LOCAL_METHOD_COUNT = new ThreadLocal<>(); - - /** - * It is used to change the tag - * - * @param tag is the given string which will be used in Logger - */ - @Override - public Settings init(String tag) { - if (tag == null) { - throw new NullPointerException("tag may not be null"); - } - if (tag.trim().length() == 0) { - throw new IllegalStateException("tag may not be empty"); - } - LoggerPrinter.TAG = tag; - return settings; + /** + * Android's max limit for a log entry is ~4076 bytes, + * so 4000 bytes is used as chunk size since default charset + * is UTF-8 + */ + private static final int CHUNK_SIZE = 4000; + + /** + * It is used for json pretty print + */ + private static final int JSON_INDENT = 4; + + /** + * The minimum stack trace index, starts at this class after two native calls. + */ + private static final int MIN_STACK_OFFSET = 3; + + /** + * It is used to determine log settings such as method count, thread info visibility + */ + private static final Settings settings = new Settings(); + + /** + * Drawing toolbox + */ + private static final char TOP_LEFT_CORNER = '╔'; + private static final char BOTTOM_LEFT_CORNER = '╚'; + private static final char MIDDLE_CORNER = '╟'; + private static final char HORIZONTAL_DOUBLE_LINE = '║'; + private static final String DOUBLE_DIVIDER = "════════════════════════════════════════════"; + private static final String SINGLE_DIVIDER = "────────────────────────────────────────────"; + private static final String TOP_BORDER = TOP_LEFT_CORNER + DOUBLE_DIVIDER + DOUBLE_DIVIDER; + private static final String BOTTOM_BORDER = BOTTOM_LEFT_CORNER + DOUBLE_DIVIDER + DOUBLE_DIVIDER; + private static final String MIDDLE_BORDER = MIDDLE_CORNER + SINGLE_DIVIDER + SINGLE_DIVIDER; + + /** + * TAG is used for the Log, the name is a little different + * in order to differentiate the logs easily with the filter + */ + private static String TAG = "PRETTYLOGGER"; + + /** + * Localize single tag and method count for each thread + */ + private static final ThreadLocal LOCAL_TAG = new ThreadLocal<>(); + private static final ThreadLocal LOCAL_METHOD_COUNT = new ThreadLocal<>(); + + /** + * It is used to change the tag + * + * @param tag is the given string which will be used in Logger + */ + @Override + public Settings init(String tag) { + if (tag == null) { + throw new NullPointerException("tag may not be null"); } - - @Override - public Settings getSettings() { - return settings; + if (tag.trim().length() == 0) { + throw new IllegalStateException("tag may not be empty"); } - - @Override - public Printer t(String tag, int methodCount) { - if (tag != null) { - LOCAL_TAG.set(tag); - } - LOCAL_METHOD_COUNT.set(methodCount); - return this; + LoggerPrinter.TAG = tag; + return settings; + } + + @Override + public Settings getSettings() { + return settings; + } + + @Override + public Printer t(String tag, int methodCount) { + if (tag != null) { + LOCAL_TAG.set(tag); } - - @Override - public void d(String message, Object... args) { - log(Log.DEBUG, message, args); + LOCAL_METHOD_COUNT.set(methodCount); + return this; + } + + @Override + public void d(String message, Object... args) { + log(Log.DEBUG, message, args); + } + + @Override + public void e(String message, Object... args) { + e(null, message, args); + } + + @Override + public void e(Throwable throwable, String message, Object... args) { + if (throwable != null && message != null) { + message += " : " + throwable.toString(); } - - @Override - public void e(String message, Object... args) { - e(null, message, args); + if (throwable != null && message == null) { + message = throwable.toString(); } - - @Override - public void e(Throwable throwable, String message, Object... args) { - if (throwable != null && message != null) { - message += " : " + throwable.toString(); - } - if (throwable != null && message == null) { - message = throwable.toString(); - } - if (message == null) { - message = "No message/exception is set"; - } - log(Log.ERROR, message, args); + if (message == null) { + message = "No message/exception is set"; } - - @Override - public void w(String message, Object... args) { - log(Log.WARN, message, args); + log(Log.ERROR, message, args); + } + + @Override + public void w(String message, Object... args) { + log(Log.WARN, message, args); + } + + @Override + public void i(String message, Object... args) { + log(Log.INFO, message, args); + } + + @Override + public void v(String message, Object... args) { + log(Log.VERBOSE, message, args); + } + + @Override + public void wtf(String message, Object... args) { + log(Log.ASSERT, message, args); + } + + /** + * Formats the json content and print it + * + * @param json the json content + */ + @Override + public void json(String json) { + if (TextUtils.isEmpty(json)) { + d("Empty/Null json content"); + return; } - - @Override - public void i(String message, Object... args) { - log(Log.INFO, message, args); + try { + if (json.startsWith("{")) { + JSONObject jsonObject = new JSONObject(json); + String message = jsonObject.toString(JSON_INDENT); + d(message); + return; + } + if (json.startsWith("[")) { + JSONArray jsonArray = new JSONArray(json); + String message = jsonArray.toString(JSON_INDENT); + d(message); + } + } catch (JSONException e) { + e(e.getCause().getMessage() + "\n" + json); } - - @Override - public void v(String message, Object... args) { - log(Log.VERBOSE, message, args); + } + + /** + * Formats the json content and print it + * + * @param xml the xml content + */ + @Override + public void xml(String xml) { + if (TextUtils.isEmpty(xml)) { + d("Empty/Null xml content"); + return; } - - @Override - public void wtf(String message, Object... args) { - log(Log.ASSERT, message, args); + try { + Source xmlInput = new StreamSource(new StringReader(xml)); + StreamResult xmlOutput = new StreamResult(new StringWriter()); + Transformer transformer = TransformerFactory.newInstance().newTransformer(); + transformer.setOutputProperty(OutputKeys.INDENT, "yes"); + transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); + transformer.transform(xmlInput, xmlOutput); + d(xmlOutput.getWriter().toString().replaceFirst(">", ">\n")); + } catch (TransformerException e) { + e(e.getCause().getMessage() + "\n" + xml); } - - /** - * Formats the json content and print it - * - * @param json the json content - */ - @Override - public void json(String json) { - if (TextUtils.isEmpty(json)) { - d("Empty/Null json content"); - return; - } - try { - if (json.startsWith("{")) { - JSONObject jsonObject = new JSONObject(json); - String message = jsonObject.toString(JSON_INDENT); - d(message); - return; - } - if (json.startsWith("[")) { - JSONArray jsonArray = new JSONArray(json); - String message = jsonArray.toString(JSON_INDENT); - d(message); - } - } catch (JSONException e) { - e(e.getCause().getMessage() + "\n" + json); - } + } + + /** + * This method is synchronized in order to avoid messy of logs' order. + */ + private synchronized void log(int logType, String msg, Object... args) { + if (settings.getLogLevel() == LogLevel.NONE) { + return; } - - /** - * Formats the json content and print it - * - * @param xml the xml content - */ - @Override - public void xml(String xml) { - if (TextUtils.isEmpty(xml)) { - d("Empty/Null xml content"); - return; - } - try { - Source xmlInput = new StreamSource(new StringReader(xml)); - StreamResult xmlOutput = new StreamResult(new StringWriter()); - Transformer transformer = TransformerFactory.newInstance().newTransformer(); - transformer.setOutputProperty(OutputKeys.INDENT, "yes"); - transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); - transformer.transform(xmlInput, xmlOutput); - d(xmlOutput.getWriter().toString().replaceFirst(">", ">\n")); - } catch (TransformerException e) { - e(e.getCause().getMessage() + "\n" + xml); - } + String tag = getTag(); + String message = createMessage(msg, args); + int methodCount = getMethodCount(); + + logTopBorder(logType, tag); + logHeaderContent(logType, tag, methodCount); + + //get bytes of message with system's default charset (which is UTF-8 for Android) + byte[] bytes = message.getBytes(); + int length = bytes.length; + if (length <= CHUNK_SIZE) { + if (methodCount > 0) { + logDivider(logType, tag); + } + logContent(logType, tag, message); + logBottomBorder(logType, tag); + return; } - - /** - * This method is synchronized in order to avoid messy of logs' order. - */ - private synchronized void log(int logType, String msg, Object... args) { - if (settings.getLogLevel() == LogLevel.NONE) { - return; - } - String tag = getTag(); - String message = createMessage(msg, args); - int methodCount = getMethodCount(); - - logTopBorder(logType, tag); - logHeaderContent(logType, tag, methodCount); - - //get bytes of message with system's default charset (which is UTF-8 for Android) - byte[] bytes = message.getBytes(); - int length = bytes.length; - if (length <= CHUNK_SIZE) { - if (methodCount > 0) { - logDivider(logType, tag); - } - logContent(logType, tag, message); - logBottomBorder(logType, tag); - return; - } - if (methodCount > 0) { - logDivider(logType, tag); - } - for (int i = 0; i < length; i += CHUNK_SIZE) { - int count = Math.min(length - i, CHUNK_SIZE); - //create a new String with system's default charset (which is UTF-8 for Android) - logContent(logType, tag, new String(bytes, i, count)); - } - logBottomBorder(logType, tag); + if (methodCount > 0) { + logDivider(logType, tag); } - - private void logTopBorder(int logType, String tag) { - logChunk(logType, tag, TOP_BORDER); + for (int i = 0; i < length; i += CHUNK_SIZE) { + int count = Math.min(length - i, CHUNK_SIZE); + //create a new String with system's default charset (which is UTF-8 for Android) + logContent(logType, tag, new String(bytes, i, count)); } - - private void logHeaderContent(int logType, String tag, int methodCount) { - StackTraceElement[] trace = Thread.currentThread().getStackTrace(); - if (settings.isShowThreadInfo()) { - logChunk(logType, tag, HORIZONTAL_DOUBLE_LINE + " Thread: " + Thread.currentThread().getName()); - logDivider(logType, tag); - } - String level = ""; - - int stackOffset = getStackOffset(trace) + settings.getMethodOffset(); - - //corresponding method count with the current stack may exceeds the stack trace. Trims the count - if (methodCount + stackOffset > trace.length) { - methodCount = trace.length - stackOffset - 1; - } - - for (int i = methodCount; i > 0; i--) { - int stackIndex = i + stackOffset; - if (stackIndex >= trace.length) { - continue; - } - StringBuilder builder = new StringBuilder(); - builder.append("║ ") - .append(level) - .append(getSimpleClassName(trace[stackIndex].getClassName())) - .append(".") - .append(trace[stackIndex].getMethodName()) - .append(" ") - .append(" (") - .append(trace[stackIndex].getFileName()) - .append(":") - .append(trace[stackIndex].getLineNumber()) - .append(")"); - level += " "; - logChunk(logType, tag, builder.toString()); - } + logBottomBorder(logType, tag); + } + + private void logTopBorder(int logType, String tag) { + logChunk(logType, tag, TOP_BORDER); + } + + private void logHeaderContent(int logType, String tag, int methodCount) { + StackTraceElement[] trace = Thread.currentThread().getStackTrace(); + if (settings.isShowThreadInfo()) { + logChunk(logType, tag, HORIZONTAL_DOUBLE_LINE + " Thread: " + Thread.currentThread().getName()); + logDivider(logType, tag); } + String level = ""; - private void logBottomBorder(int logType, String tag) { - logChunk(logType, tag, BOTTOM_BORDER); - } + int stackOffset = getStackOffset(trace) + settings.getMethodOffset(); - private void logDivider(int logType, String tag) { - logChunk(logType, tag, MIDDLE_BORDER); + //corresponding method count with the current stack may exceeds the stack trace. Trims the count + if (methodCount + stackOffset > trace.length) { + methodCount = trace.length - stackOffset - 1; } - private void logContent(int logType, String tag, String chunk) { - String[] lines = chunk.split(System.getProperty("line.separator")); - for (String line : lines) { - logChunk(logType, tag, HORIZONTAL_DOUBLE_LINE + " " + line); - } + for (int i = methodCount; i > 0; i--) { + int stackIndex = i + stackOffset; + if (stackIndex >= trace.length) { + continue; + } + StringBuilder builder = new StringBuilder(); + builder.append("║ ") + .append(level) + .append(getSimpleClassName(trace[stackIndex].getClassName())) + .append(".") + .append(trace[stackIndex].getMethodName()) + .append(" ") + .append(" (") + .append(trace[stackIndex].getFileName()) + .append(":") + .append(trace[stackIndex].getLineNumber()) + .append(")"); + level += " "; + logChunk(logType, tag, builder.toString()); } + } - private void logChunk(int logType, String tag, String chunk) { - String finalTag = formatTag(tag); - switch (logType) { - case Log.ERROR: - Log.e(finalTag, chunk); - break; - case Log.INFO: - Log.i(finalTag, chunk); - break; - case Log.VERBOSE: - Log.v(finalTag, chunk); - break; - case Log.WARN: - Log.w(finalTag, chunk); - break; - case Log.ASSERT: - Log.wtf(finalTag, chunk); - break; - case Log.DEBUG: - // Fall through, log debug by default - default: - Log.d(finalTag, chunk); - break; - } - } + private void logBottomBorder(int logType, String tag) { + logChunk(logType, tag, BOTTOM_BORDER); + } - private String getSimpleClassName(String name) { - int lastIndex = name.lastIndexOf("."); - return name.substring(lastIndex + 1); - } + private void logDivider(int logType, String tag) { + logChunk(logType, tag, MIDDLE_BORDER); + } - private String formatTag(String tag) { - if (!TextUtils.isEmpty(tag) && !TextUtils.equals(TAG, tag)) { - return TAG + "-" + tag; - } - return TAG; + private void logContent(int logType, String tag, String chunk) { + String[] lines = chunk.split(System.getProperty("line.separator")); + for (String line : lines) { + logChunk(logType, tag, HORIZONTAL_DOUBLE_LINE + " " + line); } - - /** - * @return the appropriate tag based on local or global - */ - private String getTag() { - String tag = LOCAL_TAG.get(); - if (tag != null) { - LOCAL_TAG.remove(); - return tag; - } - return TAG; + } + + private void logChunk(int logType, String tag, String chunk) { + String finalTag = formatTag(tag); + switch (logType) { + case Log.ERROR: + Log.e(finalTag, chunk); + break; + case Log.INFO: + Log.i(finalTag, chunk); + break; + case Log.VERBOSE: + Log.v(finalTag, chunk); + break; + case Log.WARN: + Log.w(finalTag, chunk); + break; + case Log.ASSERT: + Log.wtf(finalTag, chunk); + break; + case Log.DEBUG: + // Fall through, log debug by default + default: + Log.d(finalTag, chunk); + break; } + } - private String createMessage(String message, Object... args) { - return args.length == 0 ? message : String.format(message, args); - } + private String getSimpleClassName(String name) { + int lastIndex = name.lastIndexOf("."); + return name.substring(lastIndex + 1); + } - private int getMethodCount() { - Integer count = LOCAL_METHOD_COUNT.get(); - int result = settings.getMethodCount(); - if (count != null) { - LOCAL_METHOD_COUNT.remove(); - result = count; - } - if (result < 0) { - throw new IllegalStateException("methodCount cannot be negative"); - } - return result; + private String formatTag(String tag) { + if (!TextUtils.isEmpty(tag) && !TextUtils.equals(TAG, tag)) { + return TAG + "-" + tag; } - - /** - * Determines the starting index of the stack trace, after method calls made by this class. - * - * @param trace the stack trace - * @return the stack offset - */ - private int getStackOffset(StackTraceElement[] trace) { - for (int i = MIN_STACK_OFFSET; i < trace.length; i++) { - StackTraceElement e = trace[i]; - String name = e.getClassName(); - if (!name.equals(LoggerPrinter.class.getName()) && !name.equals(Logger.class.getName())) { - return --i; - } - } - return -1; + return TAG; + } + + /** + * @return the appropriate tag based on local or global + */ + private String getTag() { + String tag = LOCAL_TAG.get(); + if (tag != null) { + LOCAL_TAG.remove(); + return tag; + } + return TAG; + } + + private String createMessage(String message, Object... args) { + return args.length == 0 ? message : String.format(message, args); + } + + private int getMethodCount() { + Integer count = LOCAL_METHOD_COUNT.get(); + int result = settings.getMethodCount(); + if (count != null) { + LOCAL_METHOD_COUNT.remove(); + result = count; + } + if (result < 0) { + throw new IllegalStateException("methodCount cannot be negative"); + } + return result; + } + + /** + * Determines the starting index of the stack trace, after method calls made by this class. + * + * @param trace the stack trace + * @return the stack offset + */ + private int getStackOffset(StackTraceElement[] trace) { + for (int i = MIN_STACK_OFFSET; i < trace.length; i++) { + StackTraceElement e = trace[i]; + String name = e.getClassName(); + if (!name.equals(LoggerPrinter.class.getName()) && !name.equals(Logger.class.getName())) { + return --i; + } } + return -1; + } } diff --git a/logger/src/main/java/com/orhanobut/logger/Printer.java b/logger/src/main/java/com/orhanobut/logger/Printer.java index c5eac503..4d5e7c46 100644 --- a/logger/src/main/java/com/orhanobut/logger/Printer.java +++ b/logger/src/main/java/com/orhanobut/logger/Printer.java @@ -5,27 +5,27 @@ */ public interface Printer { - Printer t(String tag, int methodCount); + Printer t(String tag, int methodCount); - Settings init(String tag); + Settings init(String tag); - Settings getSettings(); + Settings getSettings(); - void d(String message, Object... args); + void d(String message, Object... args); - void e(String message, Object... args); + void e(String message, Object... args); - void e(Throwable throwable, String message, Object... args); + void e(Throwable throwable, String message, Object... args); - void w(String message, Object... args); + void w(String message, Object... args); - void i(String message, Object... args); + void i(String message, Object... args); - void v(String message, Object... args); + void v(String message, Object... args); - void wtf(String message, Object... args); + void wtf(String message, Object... args); - void json(String json); + void json(String json); - void xml(String xml); + void xml(String xml); }