diff --git a/.travis.yml b/.travis.yml index 4e4b277e..2f905135 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,15 +2,11 @@ language: android android: components: - - build-tools-21.1.1 - - android-18 - licenses: - - 'android-sdk-license-.+' - -notifications: - email: true - -sudo: false + - tools + - platform-tools + - build-tools-24.0.0 + - android-23 + - android-24 script: -- ./gradlew build \ No newline at end of file +- ./gradlew check \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 00000000..c59448f5 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,9 @@ +# CHANGELOG + +### 1.13 + +- LogTool is renamed to LogAdapter +- Logger.init() is optional now. It used to be mandatory to call this method once. +- Log.e(Throwable) will print out all stacktrace +- Deprecated methods are removed +- Dependencies are updated \ No newline at end of file diff --git a/README.md b/README.md index f7fc0769..afb2b983 100644 --- a/README.md +++ b/README.md @@ -16,17 +16,8 @@ Logger provides : - Jump to source ### Dependency -https://jitpack.io/#orhanobut/logger/1.12 - ```groovy -repositories { - // ... - maven { url "https://jitpack.io" } -} - -dependencies { - compile 'com.github.orhanobut:logger:1.12' -} +compile 'com.orhanobut:logger:1.13' ``` ### Current Log system @@ -44,9 +35,6 @@ Logger.d("hello %s %d", "world", 5); // String.format ``` -### Usage -Note: Because of the latest changes, Logger.init() must be called once to initiate. This will be fixed in the next version - ```java Logger.d("hello"); Logger.e("hello"); @@ -71,7 +59,7 @@ Logger.t("mytag").d("hello"); ### Settings (optional) Change the settings with init. This should be called only once. Best place would be in application class. All of them - are optional. + are optional. You can just use the default settings if you don't init Logger. ```java Logger .init(YOUR_TAG) // default PRETTYLOGGER or use just init() @@ -79,17 +67,17 @@ Logger .hideThreadInfo() // default shown .logLevel(LogLevel.NONE) // default LogLevel.FULL .methodOffset(2) // default 0 - .logTool(new AndroidLogTool()); // custom log tool, optional + .logAdapter(new AndroidLogAdapter()); //default AndroidLogAdapter } ``` Note: Use LogLevel.NONE for the release versions. ### Use another log util instead of android.util.log -- Implement LogTool +- Implement LogAdapter - set it with init ```java -.logTool(new MyCustomLogTool()) +.logAdapter(new CustomLogAdapter()) ``` ### More log samples diff --git a/build.gradle b/build.gradle index 0e59d01c..4ed22df6 100644 --- a/build.gradle +++ b/build.gradle @@ -1,20 +1,53 @@ // Top-level build file where you can add configuration options common to all sub-projects/modules. +subprojects { project -> + group = GROUP + version = VERSION_NAME -buildscript { - repositories { - jcenter() + apply plugin: 'checkstyle' + + task checkstyle(type: Checkstyle) { + configFile rootProject.file('checkstyle.xml') + source 'src/main/java' + ignoreFailures false + showViolations true + include '**/*.java' + + classpath = files() } - dependencies { - classpath 'com.android.tools.build:gradle:1.3.0' - classpath 'com.github.dcendents:android-maven-plugin:1.2' - // NOTE: Do not place your application dependencies here; they belong - // in the individual module build.gradle files + afterEvaluate { + if (project.tasks.findByName('check')) { + check.dependsOn('checkstyle') + } + } + + buildscript { + repositories { + mavenCentral() + } + dependencies { + classpath 'com.android.tools.build:gradle:2.1.2' + } } -} -allprojects { repositories { jcenter() } } + +ext { + minSdkVersion = 8 + targetSdkVersion = 23 + compileSdkVersion = 23 + buildToolsVersion = '24.0.0' + sourceCompatibilityVersion = JavaVersion.VERSION_1_7 + targetCompatibilityVersion = JavaVersion.VERSION_1_7 +} + +ext.deps = [ + // Test dependencies + junit : 'junit:junit:4.12', + truth : 'com.google.truth:truth:0.28', + robolectric: 'org.robolectric:robolectric:3.1', + mockito : "org.mockito:mockito-core:1.10.19" +] diff --git a/gradle.properties b/gradle.properties index 1d3591c8..ab3944df 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,18 +1,13 @@ -# Project-wide Gradle settings. - -# IDE (e.g. Android Studio) users: -# Gradle settings configured through the IDE *will override* -# any settings specified in this file. - -# For more details on how to configure your build environment visit -# http://www.gradle.org/docs/current/userguide/build_environment.html - -# Specifies the JVM arguments used for the daemon process. -# The setting is particularly useful for tweaking memory settings. -# Default value: -Xmx10248m -XX:MaxPermSize=256m -# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 - -# When configured, Gradle will run in incubating parallel mode. -# This option should only be used with decoupled projects. More details, visit -# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects -# org.gradle.parallel=true \ No newline at end of file +VERSION_NAME=1.13 +GROUP=com.orhanobut + +POM_DESCRIPTION=Simple, Pretty and Advanced Logger +POM_URL=https://github.com/orhanobut/logger +POM_SCM_URL=https://github.com/orhanobut/logger +POM_SCM_CONNECTION=scm:git@https://github.com/orhanobut/logger.git +POM_SCM_DEV_CONNECTION=scm:git@https://github.com/orhanobut/logger.git +POM_LICENCE_NAME=The Apache Software License, Version 2.0 +POM_LICENCE_URL=http://www.apache.org/licenses/LICENSE-2.0.txt +POM_LICENCE_DIST=repo +POM_DEVELOPER_ID=nr4bt +POM_DEVELOPER_NAME=Orhan Obut \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties index 0c71e760..d5705170 100644 --- a/gradle/wrapper/gradle-wrapper.properties +++ b/gradle/wrapper/gradle-wrapper.properties @@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-2.2.1-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip diff --git a/logger/build.gradle b/logger/build.gradle index 8518c28f..ed0d138c 100644 --- a/logger/build.gradle +++ b/logger/build.gradle @@ -1,52 +1,24 @@ apply plugin: 'com.android.library' -apply plugin: 'com.github.dcendents.android-maven' -apply plugin: 'checkstyle' - -check.dependsOn('checkstyle') - -task checkstyle(type: Checkstyle) { - configFile = rootProject.file('checkstyle.xml') - source 'src' - include '**/*.java' - exclude '**/gen/**' - - classpath = files() -} android { - compileSdkVersion 21 - buildToolsVersion "21.1.2" + compileSdkVersion rootProject.ext.compileSdkVersion + buildToolsVersion rootProject.ext.buildToolsVersion defaultConfig { - minSdkVersion 8 - targetSdkVersion 22 + minSdkVersion rootProject.ext.minSdkVersion } lintOptions { - abortOnError false + textReport true + textOutput 'stdout' } } -// build a jar with source files -task sourcesJar(type: Jar) { - from android.sourceSets.main.java.srcDirs - classifier = 'sources' -} - -task javadoc(type: Javadoc) { - failOnError false - source = android.sourceSets.main.java.sourceFiles - classpath += project.files(android.getBootClasspath().join(File.pathSeparator)) -} - -// build a jar with javadoc -task javadocJar(type: Jar, dependsOn: javadoc) { - classifier = 'javadoc' - from javadoc.destinationDir +dependencies { + testCompile deps.junit + testCompile deps.truth + testCompile deps.robolectric + testCompile deps.mockito } -dependencies { - testCompile 'junit:junit:4.12' - testCompile "org.robolectric:robolectric:3.0" - testCompile 'org.assertj:assertj-core:1.7.0' -} \ No newline at end of file +apply from: rootProject.file('maven_push.gradle') \ No newline at end of file diff --git a/logger/gradle.properties b/logger/gradle.properties new file mode 100644 index 00000000..c0908413 --- /dev/null +++ b/logger/gradle.properties @@ -0,0 +1,3 @@ +POM_NAME=Logger +POM_ARTIFACT_ID=logger +POM_PACKAGING=aar \ No newline at end of file diff --git a/logger/src/main/java/com/orhanobut/logger/AndroidLogTool.java b/logger/src/main/java/com/orhanobut/logger/AndroidLogAdapter.java similarity index 92% rename from logger/src/main/java/com/orhanobut/logger/AndroidLogTool.java rename to logger/src/main/java/com/orhanobut/logger/AndroidLogAdapter.java index 3e960b0e..83abecfd 100644 --- a/logger/src/main/java/com/orhanobut/logger/AndroidLogTool.java +++ b/logger/src/main/java/com/orhanobut/logger/AndroidLogAdapter.java @@ -2,7 +2,7 @@ import android.util.Log; -class AndroidLogTool implements LogTool { +class AndroidLogAdapter implements LogAdapter { @Override public void d(String tag, String message) { Log.d(tag, message); } diff --git a/logger/src/main/java/com/orhanobut/logger/Helper.java b/logger/src/main/java/com/orhanobut/logger/Helper.java index ed999bef..bc0c24d3 100644 --- a/logger/src/main/java/com/orhanobut/logger/Helper.java +++ b/logger/src/main/java/com/orhanobut/logger/Helper.java @@ -28,76 +28,78 @@ */ final class Helper { - private Helper() { - // Hidden constructor. - } + private Helper() { + // Hidden constructor. + } - /** - * Returns true if the string is null or 0-length. - * - * @param str the string to be examined - * @return true if str is null or zero length - */ - static boolean isEmpty(CharSequence str) { - return str == null || str.length() == 0; - } + /** + * Returns true if the string is null or 0-length. + * + * @param str the string to be examined + * + * @return true if str is null or zero length + */ + static boolean isEmpty(CharSequence str) { + return str == null || str.length() == 0; + } - /** - * Returns true if a and b are equal, including if they are both null. - *

Note: In platform versions 1.1 and earlier, this method only worked well if - * both the arguments were instances of String.

- * - * @param a first CharSequence to check - * @param b second CharSequence to check - * @return true if a and b are equal - * - * NOTE: Logic slightly change due to strict policy on CI - - * "Inner assignments should be avoided" - */ - static boolean equals(CharSequence a, CharSequence b) { - if (a == b) return true; - if (a != null && b != null) { - int length = a.length(); - if (length == b.length()) { - if (a instanceof String && b instanceof String) { - return a.equals(b); - } else { - for (int i = 0; i < length; i++) { - if (a.charAt(i) != b.charAt(i)) return false; - } - return true; - } - } + /** + * Returns true if a and b are equal, including if they are both null. + *

Note: In platform versions 1.1 and earlier, this method only worked well if + * both the arguments were instances of String.

+ * + * @param a first CharSequence to check + * @param b second CharSequence to check + * + * @return true if a and b are equal + * + * NOTE: Logic slightly change due to strict policy on CI - + * "Inner assignments should be avoided" + */ + static boolean equals(CharSequence a, CharSequence b) { + if (a == b) return true; + if (a != null && b != null) { + int length = a.length(); + if (length == b.length()) { + if (a instanceof String && b instanceof String) { + return a.equals(b); + } else { + for (int i = 0; i < length; i++) { + if (a.charAt(i) != b.charAt(i)) return false; + } + return true; } - return false; + } } + return false; + } - /** - * Copied from "android.util.Log.getStackTraceString()" in order to avoid usage of Android stack - * in unit tests. - * - * @return Stack trace in form of String - */ - static String getStackTraceString(Throwable tr) { - if (tr == null) { - return ""; - } - - // This is to reduce the amount of log spew that apps do in the non-error - // condition of the network being unavailable. - Throwable t = tr; - while (t != null) { - if (t instanceof UnknownHostException) { - return ""; - } - t = t.getCause(); - } + /** + * Copied from "android.util.Log.getStackTraceString()" in order to avoid usage of Android stack + * in unit tests. + * + * @return Stack trace in form of String + */ + static String getStackTraceString(Throwable tr) { + if (tr == null) { + return ""; + } - StringWriter sw = new StringWriter(); - PrintWriter pw = new PrintWriter(sw); - tr.printStackTrace(pw); - pw.flush(); - return sw.toString(); + // This is to reduce the amount of log spew that apps do in the non-error + // condition of the network being unavailable. + Throwable t = tr; + while (t != null) { + if (t instanceof UnknownHostException) { + return ""; + } + t = t.getCause(); } + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + tr.printStackTrace(pw); + pw.flush(); + return sw.toString(); + } + } diff --git a/logger/src/main/java/com/orhanobut/logger/LogTool.java b/logger/src/main/java/com/orhanobut/logger/LogAdapter.java similarity index 89% rename from logger/src/main/java/com/orhanobut/logger/LogTool.java rename to logger/src/main/java/com/orhanobut/logger/LogAdapter.java index a0b5a13b..cab5d8ce 100644 --- a/logger/src/main/java/com/orhanobut/logger/LogTool.java +++ b/logger/src/main/java/com/orhanobut/logger/LogAdapter.java @@ -1,6 +1,6 @@ package com.orhanobut.logger; -public interface LogTool { +public interface LogAdapter { void d(String tag, String message); void e(String tag, String message); diff --git a/logger/src/main/java/com/orhanobut/logger/Logger.java b/logger/src/main/java/com/orhanobut/logger/Logger.java index 02fa0c7a..77b772c7 100644 --- a/logger/src/main/java/com/orhanobut/logger/Logger.java +++ b/logger/src/main/java/com/orhanobut/logger/Logger.java @@ -34,7 +34,6 @@ public static Settings init(String tag) { public static void clear() { printer.clear(); - printer = null; } public static Printer t(String tag) { diff --git a/logger/src/main/java/com/orhanobut/logger/LoggerPrinter.java b/logger/src/main/java/com/orhanobut/logger/LoggerPrinter.java index 493be396..571ce922 100644 --- a/logger/src/main/java/com/orhanobut/logger/LoggerPrinter.java +++ b/logger/src/main/java/com/orhanobut/logger/LoggerPrinter.java @@ -15,12 +15,10 @@ import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; -/** - * Logger is a wrapper for logging utils - * But more pretty, simple and powerful - */ final class LoggerPrinter implements Printer { + private static final String DEFAULT_TAG = "PRETTYLOGGER"; + private static final int DEBUG = 3; private static final int ERROR = 6; private static final int ASSERT = 7; @@ -38,7 +36,7 @@ final class LoggerPrinter implements Printer { /** * It is used for json pretty print */ - private static final int JSON_INDENT = 4; + private static final int JSON_INDENT = 2; /** * The minimum stack trace index, starts at this class after two native calls. @@ -73,7 +71,11 @@ final class LoggerPrinter implements Printer { /** * It is used to determine log settings such as method count, thread info visibility */ - private Settings settings; + private final Settings settings = new Settings(); + + public LoggerPrinter() { + init(DEFAULT_TAG); + } /** * It is used to change the tag @@ -88,7 +90,6 @@ final class LoggerPrinter implements Printer { throw new IllegalStateException("tag may not be empty"); } this.tag = tag; - this.settings = new Settings(); return settings; } @@ -117,7 +118,7 @@ final class LoggerPrinter implements Printer { message += " : " + Helper.getStackTraceString(throwable); } if (throwable != null && message == null) { - message = throwable.toString(); + message = Helper.getStackTraceString(throwable); } if (message == null) { message = "No message/exception is set"; @@ -163,9 +164,11 @@ final class LoggerPrinter implements Printer { JSONArray jsonArray = new JSONArray(json); String message = jsonArray.toString(JSON_INDENT); d(message); + return; } + e("Invalid Json"); } catch (JSONException e) { - e(e.getCause().getMessage() + "\n" + json); + e("Invalid Json"); } } @@ -193,7 +196,7 @@ final class LoggerPrinter implements Printer { } @Override public void clear() { - settings = null; + settings.reset(); } /** @@ -296,24 +299,24 @@ private void logChunk(int logType, String tag, String chunk) { String finalTag = formatTag(tag); switch (logType) { case ERROR: - settings.getLogTool().e(finalTag, chunk); + settings.getLogAdapter().e(finalTag, chunk); break; case INFO: - settings.getLogTool().i(finalTag, chunk); + settings.getLogAdapter().i(finalTag, chunk); break; case VERBOSE: - settings.getLogTool().v(finalTag, chunk); + settings.getLogAdapter().v(finalTag, chunk); break; case WARN: - settings.getLogTool().w(finalTag, chunk); + settings.getLogAdapter().w(finalTag, chunk); break; case ASSERT: - settings.getLogTool().wtf(finalTag, chunk); + settings.getLogAdapter().wtf(finalTag, chunk); break; case DEBUG: // Fall through, log debug by default default: - settings.getLogTool().d(finalTag, chunk); + settings.getLogAdapter().d(finalTag, chunk); break; } } @@ -343,7 +346,7 @@ private String getTag() { } private String createMessage(String message, Object... args) { - return args.length == 0 ? message : String.format(message, args); + return args == null || args.length == 0 ? message : String.format(message, args); } private int getMethodCount() { @@ -363,6 +366,7 @@ private int getMethodCount() { * 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) { diff --git a/logger/src/main/java/com/orhanobut/logger/Settings.java b/logger/src/main/java/com/orhanobut/logger/Settings.java index 38bfeeeb..2431794c 100644 --- a/logger/src/main/java/com/orhanobut/logger/Settings.java +++ b/logger/src/main/java/com/orhanobut/logger/Settings.java @@ -5,10 +5,10 @@ public final class Settings { private int methodCount = 2; private boolean showThreadInfo = true; private int methodOffset = 0; - private LogTool logTool; + private LogAdapter logAdapter; /** - * Determines how logs will printed + * Determines to how logs will be printed */ private LogLevel logLevel = LogLevel.FULL; @@ -17,13 +17,6 @@ public Settings hideThreadInfo() { return this; } - /** - * Use {@link #methodCount} - */ - @Deprecated public Settings setMethodCount(int methodCount) { - return methodCount(methodCount); - } - public Settings methodCount(int methodCount) { if (methodCount < 0) { methodCount = 0; @@ -32,33 +25,18 @@ public Settings methodCount(int methodCount) { return this; } - /** - * Use {@link #logLevel} - */ - @Deprecated - public Settings setLogLevel(LogLevel logLevel) { - return logLevel(logLevel); - } - public Settings logLevel(LogLevel logLevel) { this.logLevel = logLevel; return this; } - /** - * Use {@link #methodOffset} - */ - @Deprecated public Settings setMethodOffset(int offset) { - return methodOffset(offset); - } - public Settings methodOffset(int offset) { this.methodOffset = offset; return this; } - public Settings logTool(LogTool logTool) { - this.logTool = logTool; + public Settings logAdapter(LogAdapter logAdapter) { + this.logAdapter = logAdapter; return this; } @@ -78,10 +56,17 @@ public int getMethodOffset() { return methodOffset; } - public LogTool getLogTool() { - if (logTool == null) { - logTool = new AndroidLogTool(); + public LogAdapter getLogAdapter() { + if (logAdapter == null) { + logAdapter = new AndroidLogAdapter(); } - return logTool; + return logAdapter; + } + + public void reset() { + methodCount = 2; + methodOffset = 0; + showThreadInfo = true; + logLevel = LogLevel.FULL; } } diff --git a/logger/src/test/java/com.orhanobut.logger/HelperTest.java b/logger/src/test/java/com.orhanobut.logger/HelperTest.java new file mode 100644 index 00000000..8be9ce5e --- /dev/null +++ b/logger/src/test/java/com.orhanobut.logger/HelperTest.java @@ -0,0 +1,43 @@ +package com.orhanobut.logger; + +import android.util.Log; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.RobolectricGradleTestRunner; +import org.robolectric.annotation.Config; + +import java.net.UnknownHostException; + +import static com.google.common.truth.Truth.assertThat; + +@RunWith(RobolectricGradleTestRunner.class) +@Config(sdk = 21, constants = BuildConfig.class) +public class HelperTest { + + @Test public void isEmpty() { + assertThat(Helper.isEmpty("")).isTrue(); + assertThat(Helper.isEmpty(null)).isTrue(); + } + + @Test public void equals() { + assertThat(Helper.equals("a", "a")).isTrue(); + assertThat(Helper.equals("as", "b")).isFalse(); + assertThat(Helper.equals(null, "b")).isFalse(); + assertThat(Helper.equals("a", null)).isFalse(); + } + + @Test public void getStackTraceString() { + Throwable throwable = new Throwable("test"); + String androidTraceString = Log.getStackTraceString(throwable); + assertThat(Helper.getStackTraceString(throwable)).isEqualTo(androidTraceString); + } + + @Test public void getStackTraceStringReturnsEmptyStringWithNull() { + assertThat(Helper.getStackTraceString(null)).isEqualTo(""); + } + + @Test public void getStackTraceStringReturnEmptyStringWithUnknownHostException() { + assertThat(Helper.getStackTraceString(new UnknownHostException())).isEqualTo(""); + } +} \ No newline at end of file diff --git a/logger/src/test/java/com.orhanobut.logger/LoggerTest.java b/logger/src/test/java/com.orhanobut.logger/LoggerTest.java index 085e2f94..bccf7649 100644 --- a/logger/src/test/java/com.orhanobut.logger/LoggerTest.java +++ b/logger/src/test/java/com.orhanobut.logger/LoggerTest.java @@ -1,6 +1,8 @@ package com.orhanobut.logger; import org.junit.After; +import org.junit.Before; +import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricGradleTestRunner; @@ -10,7 +12,7 @@ import java.util.List; -import static org.assertj.core.api.Assertions.assertThat; +import static com.google.common.truth.Truth.assertThat; @RunWith(RobolectricGradleTestRunner.class) @Config(constants = BuildConfig.class, sdk = 21) @@ -23,109 +25,149 @@ public class LoggerTest { public static final int VERBOSE = 2; public static final int WARN = 5; + String threadName; + + @Before public void setup() { + threadName = Thread.currentThread().getName(); + + Logger.init(); + } + @After public void tearDown() { Logger.clear(); } @Test public void debugLog() { - Logger.init(); Logger.d("message"); - assertLog(DEBUG, "message") - .hasTopBorder() - .hasThread("Test worker") - .hasMiddleBorder() - .skip() - .skip() - .hasMiddleBorder() - .hasMessage() - .hasBottomBorder() - .hasNoMoreMessages(); + + assertLog(DEBUG).hasMessageWithDefaultSettings("message"); } @Test public void verboseLog() { - Logger.init(); Logger.v("message"); - assertLog(VERBOSE, "message") - .hasTopBorder() - .hasThread("Test worker") - .hasMiddleBorder() - .skip() - .skip() - .hasMiddleBorder() - .hasMessage() - .hasBottomBorder() - .hasNoMoreMessages(); + + assertLog(VERBOSE).hasMessageWithDefaultSettings("message"); } @Test public void warningLog() { - Logger.init(); Logger.w("message"); - assertLog(WARN, "message") - .hasTopBorder() - .hasThread("Test worker") - .hasMiddleBorder() - .skip() - .skip() - .hasMiddleBorder() - .hasMessage() - .hasBottomBorder() - .hasNoMoreMessages(); + + assertLog(WARN).hasMessageWithDefaultSettings("message"); } @Test public void errorLog() { - Logger.init(); Logger.e("message"); - assertLog(ERROR, "message") - .hasTopBorder() - .hasThread("Test worker") - .hasMiddleBorder() - .skip() - .skip() - .hasMiddleBorder() - .hasMessage() - .hasBottomBorder() - .hasNoMoreMessages(); + + assertLog(ERROR).hasMessageWithDefaultSettings("message"); + } + + @Ignore("Through Terminal somehow not working, but on Studio it works, needs investigation") + @Test public void errorLogWithThrowable() { + Throwable throwable = new Throwable("throwable"); + Logger.e(throwable, "message"); + + String stackString = "message : " + Helper.getStackTraceString(throwable); + String[] stackItems = stackString.split("\\n"); + + assertLog(ERROR).hasMessageWithDefaultSettings(stackItems); + } + + @Ignore("Through Terminal somehow not working, but on Studio it works, needs investigation") + @Test public void errorLogWithThrowableWithoutMessage() { + Throwable throwable = new Throwable("throwable"); + Logger.e(throwable, null); + + String stackString = Helper.getStackTraceString(throwable); + String[] stackItems = stackString.split("\\n"); + + assertLog(ERROR).hasMessageWithDefaultSettings(stackItems); + } + + @Ignore("Through Terminal somehow not working, but on Studio it works, needs investigation") + @Test public void errorLogNoThrowableNoMessage() { + Logger.e(null, null); + + assertLog(ERROR).hasMessageWithDefaultSettings("No message/exception is set"); } @Test public void infoLog() { - Logger.init(); Logger.i("message"); - assertLog(INFO, "message") - .hasTopBorder() - .hasThread("Test worker") - .hasMiddleBorder() - .skip() - .skip() - .hasMiddleBorder() - .hasMessage() - .hasBottomBorder() - .hasNoMoreMessages(); + + assertLog(INFO).hasMessageWithDefaultSettings("message"); } @Test public void wtfLog() { - Logger.init(); Logger.wtf("message"); - assertLog(ASSERT, "message") - .hasTopBorder() - .hasThread("Test worker") - .hasMiddleBorder() - .skip() - .skip() - .hasMiddleBorder() - .hasMessage() - .hasBottomBorder() - .hasNoMoreMessages(); + + assertLog(ASSERT).hasMessageWithDefaultSettings("message"); + } + + @Test public void jsonLObjectLog() { + String[] messages = new String[]{"{", " \"key\": 3", "}"}; + + Logger.json(" {\"key\":3}"); + + assertLog(DEBUG).hasMessageWithDefaultSettings(messages); + } + + @Test public void jsonArrayLog() { + String[] messages = new String[]{ + "[", + " {", + " \"key\": 3", + " }", + "]" + }; + + Logger.json("[{\"key\":3}]"); + + assertLog(DEBUG).hasMessageWithDefaultSettings(messages); + } + + @Test public void testInvalidJsonLog() { + Logger.json("no json"); + assertLog(ERROR).hasMessageWithDefaultSettings("Invalid Json"); + + Logger.json("{ missing end"); + assertLog(ERROR).hasMessageWithDefaultSettings("Invalid Json"); + } + + @Test public void jsonLogEmptyOrNull() { + Logger.json(null); + assertLog(DEBUG).hasMessageWithDefaultSettings("Empty/Null json content"); + + Logger.json(""); + assertLog(DEBUG).hasMessageWithDefaultSettings("Empty/Null json content"); + } + + @Test public void xmlLog() { + String[] messages = new String[]{ + "", + "Test" + }; + + Logger.xml("Test"); + + assertLog(DEBUG).hasMessageWithDefaultSettings(messages); + } + + @Test public void xmlLogNullOrEmpty() { + Logger.xml(null); + assertLog(DEBUG).hasMessageWithDefaultSettings("Empty/Null xml content"); + + Logger.xml(""); + assertLog(DEBUG).hasMessageWithDefaultSettings("Empty/Null xml content"); } @Test public void logWithoutThread() { Logger.init().hideThreadInfo(); Logger.i("message"); - assertLog(INFO, "message") + assertLog(INFO) .hasTopBorder() .skip() .skip() .hasMiddleBorder() - .hasMessage() + .hasMessage("message") .hasBottomBorder() .hasNoMoreMessages(); } @@ -133,14 +175,14 @@ public class LoggerTest { @Test public void logWithCustomTag() { Logger.init("CustomTag"); Logger.i("message"); - assertLog("CustomTag", INFO, "message") + assertLog("CustomTag", INFO) .hasTopBorder() - .hasThread("Test worker") + .hasThread(threadName) .hasMiddleBorder() .skip() .skip() .hasMiddleBorder() - .hasMessage() + .hasMessage("message") .hasBottomBorder() .hasNoMoreMessages(); } @@ -148,13 +190,13 @@ public class LoggerTest { @Test public void logWithOneMethodInfo() { Logger.init().methodCount(1); Logger.i("message"); - assertLog(INFO, "message") + assertLog(INFO) .hasTopBorder() - .hasThread("Test worker") + .hasThread(threadName) .hasMiddleBorder() .skip() .hasMiddleBorder() - .hasMessage() + .hasMessage("message") .hasBottomBorder() .hasNoMoreMessages(); } @@ -163,11 +205,11 @@ public class LoggerTest { Logger.init().methodCount(0); Logger.i("message"); - assertLog(INFO, "message") + assertLog(INFO) .hasTopBorder() - .hasThread("Test worker") + .hasThread(threadName) .hasMiddleBorder() - .hasMessage() + .hasMessage("message") .hasBottomBorder() .hasNoMoreMessages(); } @@ -176,9 +218,9 @@ public class LoggerTest { Logger.init().methodCount(0).hideThreadInfo(); Logger.i("message"); - assertLog(INFO, "message") + assertLog(INFO) .hasTopBorder() - .hasMessage() + .hasMessage("message") .hasBottomBorder() .hasNoMoreMessages(); } @@ -188,13 +230,13 @@ public class LoggerTest { Logger.t("CustomTag").i("message"); Logger.i("message"); - assertLog("PRETTYLOGGER-CustomTag", INFO, "message") + assertLog("PRETTYLOGGER-CustomTag", INFO) .hasTopBorder() - .hasMessage() + .hasMessage("message") .hasBottomBorder() .defaultTag() .hasTopBorder() - .hasMessage() + .hasMessage("message") .hasBottomBorder() .hasNoMoreMessages(); } @@ -204,14 +246,14 @@ public class LoggerTest { Logger.t(1).i("message"); Logger.i("message"); - assertLog(INFO, "message") + assertLog(INFO) .hasTopBorder() .skip() .hasMiddleBorder() - .hasMessage() + .hasMessage("message") .hasBottomBorder() .hasTopBorder() - .hasMessage() + .hasMessage("message") .hasBottomBorder() .hasNoMoreMessages(); } @@ -221,15 +263,15 @@ public class LoggerTest { Logger.t("CustomTag", 1).i("message"); Logger.i("message"); - assertLog("PRETTYLOGGER-CustomTag", INFO, "message") + assertLog("PRETTYLOGGER-CustomTag", INFO) .hasTopBorder() .skip() .hasMiddleBorder() - .hasMessage() + .hasMessage("message") .hasBottomBorder() .defaultTag() .hasTopBorder() - .hasMessage() + .hasMessage("message") .hasBottomBorder() .hasNoMoreMessages(); } @@ -238,16 +280,30 @@ public class LoggerTest { Logger.init().logLevel(LogLevel.NONE); Logger.i("message"); - assertLog(INFO, "message") + assertLog(INFO) + .hasNoMoreMessages(); + } + + @Test public void useDefaultSettingsIfInitNotCalled() { + Logger.i("message"); + assertLog(INFO) + .hasTopBorder() + .hasThread(threadName) + .hasMiddleBorder() + .skip() + .skip() + .hasMiddleBorder() + .hasMessage("message") + .hasBottomBorder() .hasNoMoreMessages(); } - private static LogAssert assertLog(int priority, String message) { - return assertLog(null, priority, message); + private static LogAssert assertLog(int priority) { + return assertLog(null, priority); } - private static LogAssert assertLog(String tag, int priority, String message) { - return new LogAssert(ShadowLog.getLogs(), tag, priority, message); + private static LogAssert assertLog(String tag, int priority) { + return new LogAssert(ShadowLog.getLogs(), tag, priority); } private static final class LogAssert { @@ -264,18 +320,16 @@ private static final class LogAssert { private static final String MIDDLE_BORDER = MIDDLE_CORNER + SINGLE_DIVIDER + SINGLE_DIVIDER; private final List items; - private final String message; private final int priority; private String tag; private int index = 0; - private LogAssert(List items, String tag, int priority, String message) { + private LogAssert(List items, String tag, int priority) { this.items = items; this.tag = tag == null ? DEFAULT_TAG : tag; this.priority = priority; - this.message = message; } public LogAssert hasTopBorder() { @@ -298,7 +352,7 @@ public LogAssert hasMethodInfo(String methodInfo) { return hasLog(priority, tag, HORIZONTAL_DOUBLE_LINE + " " + methodInfo); } - public LogAssert hasMessage() { + public LogAssert hasMessage(String message) { return hasLog(priority, tag, HORIZONTAL_DOUBLE_LINE + " " + message); } @@ -322,6 +376,25 @@ public LogAssert defaultTag() { public void hasNoMoreMessages() { assertThat(items).hasSize(index); + ShadowLog.getLogs().clear(); + } + + public LogAssert hasMessageWithDefaultSettings(String... messages) { + hasTopBorder(); + skip(); + hasMiddleBorder(); + skip(); + skip(); + hasMiddleBorder(); + + for (String message : messages) { + hasMessage(message); + } + + hasBottomBorder(); + hasNoMoreMessages(); + + return this; } } } diff --git a/logger/src/test/java/com.orhanobut.logger/SettingsTest.java b/logger/src/test/java/com.orhanobut.logger/SettingsTest.java index b8ff88bf..b3058b59 100644 --- a/logger/src/test/java/com.orhanobut.logger/SettingsTest.java +++ b/logger/src/test/java/com.orhanobut.logger/SettingsTest.java @@ -1,27 +1,13 @@ package com.orhanobut.logger; -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; +import static com.google.common.truth.Truth.assertThat; +import static org.mockito.Mockito.mock; -@RunWith(RobolectricGradleTestRunner.class) -@Config(constants = BuildConfig.class, sdk = 21) public class SettingsTest { - private Settings settings; - - @Before public void setup() { - settings = new Settings(); - } - - @After public void tearDown() { - settings = null; - } + private Settings settings = new Settings(); @Test public void testDefaultShowThreadInfo() { assertThat(settings.isShowThreadInfo()).isTrue(); @@ -29,6 +15,7 @@ public class SettingsTest { @Test public void testCustomShowThreadInfo() { settings.hideThreadInfo(); + assertThat(settings.isShowThreadInfo()).isFalse(); } @@ -45,7 +32,7 @@ public class SettingsTest { } @Test public void testMethodCount() { - //default + //default 2 assertThat(settings.getMethodCount()).isEqualTo(2); settings.methodCount(4); @@ -66,4 +53,25 @@ public class SettingsTest { settings.methodOffset(-10); assertThat(settings.getMethodOffset()).isEqualTo(-10); } + + @Test public void testLogAdapter() { + LogAdapter logAdapter = mock(LogAdapter.class); + settings.logAdapter(logAdapter); + + assertThat(settings.getLogAdapter()).isEqualTo(logAdapter); + } + + @Test public void testReset() { + settings.methodCount(4); + settings.logLevel(LogLevel.NONE); + settings.methodOffset(100); + settings.hideThreadInfo(); + + settings.reset(); + + assertThat(settings.getMethodCount()).isEqualTo(2); + assertThat(settings.getLogLevel()).isEqualTo(LogLevel.FULL); + assertThat(settings.getMethodOffset()).isEqualTo(0); + assertThat(settings.isShowThreadInfo()).isTrue(); + } } diff --git a/maven_push.gradle b/maven_push.gradle new file mode 100644 index 00000000..50e961d3 --- /dev/null +++ b/maven_push.gradle @@ -0,0 +1,99 @@ +apply plugin: 'maven' +apply plugin: 'signing' + +version = VERSION_NAME +group = GROUP + +def isReleaseBuild() { + return version.contains("SNAPSHOT") == false +} + +def sonatypeRepositoryUrl +if (isReleaseBuild()) { + println 'RELEASE BUILD' + sonatypeRepositoryUrl = hasProperty('RELEASE_REPOSITORY_URL') ? RELEASE_REPOSITORY_URL + : "https://oss.sonatype.org/service/local/staging/deploy/maven2/" +} else { + println 'DEBUG BUILD' + sonatypeRepositoryUrl = hasProperty('SNAPSHOT_REPOSITORY_URL') ? SNAPSHOT_REPOSITORY_URL + : "https://oss.sonatype.org/content/repositories/snapshots/" +} + +afterEvaluate { project -> + uploadArchives { + repositories { + mavenDeployer { + beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) } + pom.artifactId = POM_ARTIFACT_ID + repository(url: sonatypeRepositoryUrl) { + try { + authentication(userName: mavenUser, password: mavenPassword) + } catch (Exception e) { + println "mavenUser or mavenPassword is missing" + } + } + pom.project { + name POM_NAME + packaging POM_PACKAGING + description POM_DESCRIPTION + url POM_URL + scm { + url POM_SCM_URL + connection POM_SCM_CONNECTION + developerConnection POM_SCM_DEV_CONNECTION + } + licenses { + license { + name POM_LICENCE_NAME + url POM_LICENCE_URL + distribution POM_LICENCE_DIST + } + } + developers { + developer { + id POM_DEVELOPER_ID + name POM_DEVELOPER_NAME + } + } + } + } + } + } + signing { + required { isReleaseBuild() && gradle.taskGraph.hasTask("uploadArchives") } + sign configurations.archives + } + task androidJavadocs(type: Javadoc) { + source = android.sourceSets.main.java.sourceFiles + } + task androidJavadocsJar(type: Jar) { + classifier = 'javadoc' + from androidJavadocs.destinationDir + } + task androidSourcesJar(type: Jar) { + classifier = 'sources' + from android.sourceSets.main.java.sourceFiles + } + artifacts { + archives androidSourcesJar + archives androidJavadocsJar + } +} + +// build a jar with source files +task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + classifier = 'sources' +} + +task javadoc(type: Javadoc) { + failOnError false + source = android.sourceSets.main.java.sourceFiles + classpath += project.files(android.getBootClasspath().join(File.pathSeparator)) +} + +// build a jar with javadoc +task javadocJar(type: Jar, dependsOn: javadoc) { + classifier = 'javadoc' + from javadoc.destinationDir +} \ No newline at end of file diff --git a/settings.gradle b/settings.gradle index 4b6c2a7e..559512e6 100644 --- a/settings.gradle +++ b/settings.gradle @@ -1 +1 @@ -include ':logger' +include ':logger' \ No newline at end of file