Repository: orhanobut/logger Branch: master Commit: c64a72c2ce3d Files: 48 Total size: 95.9 KB Directory structure: gitextract_lpzk4f8q/ ├── .github/ │ └── ISSUE_TEMPLATE.md ├── .gitignore ├── .idea/ │ ├── codeStyles/ │ │ ├── Project.xml │ │ └── codeStyleConfig.xml │ ├── encodings.xml │ └── vcs.xml ├── .travis.yml ├── LICENSE ├── README.md ├── build.gradle ├── checkstyle.xml ├── gradle/ │ ├── maven_push.gradle │ └── wrapper/ │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradle.properties ├── gradlew ├── gradlew.bat ├── logger/ │ ├── build.gradle │ ├── gradle.properties │ └── src/ │ ├── main/ │ │ ├── AndroidManifest.xml │ │ └── java/ │ │ └── com/ │ │ └── orhanobut/ │ │ └── logger/ │ │ ├── AndroidLogAdapter.java │ │ ├── CsvFormatStrategy.java │ │ ├── DiskLogAdapter.java │ │ ├── DiskLogStrategy.java │ │ ├── FormatStrategy.java │ │ ├── LogAdapter.java │ │ ├── LogStrategy.java │ │ ├── LogcatLogStrategy.java │ │ ├── Logger.java │ │ ├── LoggerPrinter.java │ │ ├── PrettyFormatStrategy.java │ │ ├── Printer.java │ │ └── Utils.java │ └── test/ │ └── java/ │ └── com.orhanobut.logger/ │ ├── AndroidLogAdapterTest.kt │ ├── CsvFormatStrategyTest.kt │ ├── DiskLogAdapterTest.kt │ ├── DiskLogStrategyTest.kt │ ├── LogAssert.kt │ ├── LogcatLogStrategyTest.kt │ ├── LoggerPrinterTest.kt │ ├── LoggerTest.kt │ ├── PrettyFormatStrategyTest.kt │ └── UtilsTest.kt ├── sample/ │ ├── build.gradle │ └── src/ │ └── main/ │ ├── AndroidManifest.xml │ ├── java/ │ │ └── com/ │ │ └── orhanobut/ │ │ └── sample/ │ │ └── MainActivity.java │ └── res/ │ └── layout/ │ └── activity_main.xml └── settings.gradle ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/ISSUE_TEMPLATE.md ================================================ Please try to fill all questions below before submitting an issue. - Android studio version: - Android gradle plugin version: - Logger version: - Emulator/phone information: - If possible, please add how did you initialize Logger? - Is it flaky or does it happen all the time? ================================================ FILE: .gitignore ================================================ local.properties # Generated files build/ # Mac store .DS_Store # Gradle files .gradle/ /captures # Log Files *.log # IDEA/Android Studio *.iml *.ipr *.iws **/.idea/shelf **/.idea/workspace.xml **/.idea/tasks.xml **/.idea/datasources.xml **/.idea/dataSources.ids **/.idea/gradle.xml **/.idea/misc.xml **/.idea/modules.xml **/.idea/libraries **/.idea/dictionaries **/.idea/runConfigurations.xml .idea/caches # layout inspector view captures captures sample/libs/ ================================================ FILE: .idea/codeStyles/Project.xml ================================================ ================================================ FILE: .idea/codeStyles/codeStyleConfig.xml ================================================ ================================================ FILE: .idea/encodings.xml ================================================ ================================================ FILE: .idea/vcs.xml ================================================ ================================================ FILE: .travis.yml ================================================ language: android jdk: oraclejdk8 android: components: - tools - platform-tools - build-tools-27.0.3 - android-27 before_install: - yes | sdkmanager "platforms;android-27" script: - ./gradlew check ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: README.md ================================================ [![Android Arsenal](https://img.shields.io/badge/Android%20Arsenal-Logger-brightgreen.svg?style=flat)](http://android-arsenal.com/details/1/1658) [![](https://img.shields.io/badge/AndroidWeekly-%23147-blue.svg)](http://androidweekly.net/issues/issue-147) [![Join the chat at https://gitter.im/orhanobut/logger](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/orhanobut/logger?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![Build Status](https://travis-ci.org/orhanobut/logger.svg?branch=master)](https://travis-ci.org/orhanobut/logger) ### Logger Simple, pretty and powerful logger for android ### Setup Download ```groovy implementation 'com.orhanobut:logger:2.2.0' ``` Initialize ```java Logger.addLogAdapter(new AndroidLogAdapter()); ``` And use ```java Logger.d("hello"); ``` ### Output ### Options ```java Logger.d("debug"); Logger.e("error"); Logger.w("warning"); Logger.v("verbose"); Logger.i("information"); Logger.wtf("What a Terrible Failure"); ``` String format arguments are supported ```java Logger.d("hello %s", "world"); ``` Collections are supported (only available for debug logs) ```java Logger.d(MAP); Logger.d(SET); Logger.d(LIST); Logger.d(ARRAY); ``` Json and Xml support (output will be in debug level) ```java Logger.json(JSON_CONTENT); Logger.xml(XML_CONTENT); ``` ### Advanced ```java FormatStrategy formatStrategy = PrettyFormatStrategy.newBuilder() .showThreadInfo(false) // (Optional) Whether to show thread info or not. Default true .methodCount(0) // (Optional) How many method line to show. Default 2 .methodOffset(7) // (Optional) Hides internal method calls up to offset. Default 5 .logStrategy(customLog) // (Optional) Changes the log strategy to print out. Default LogCat .tag("My custom tag") // (Optional) Global tag for every log. Default PRETTY_LOGGER .build(); Logger.addLogAdapter(new AndroidLogAdapter(formatStrategy)); ``` ### Loggable Log adapter checks whether the log should be printed or not by checking this function. If you want to disable/hide logs for output, override `isLoggable` method. `true` will print the log message, `false` will ignore it. ```java Logger.addLogAdapter(new AndroidLogAdapter() { @Override public boolean isLoggable(int priority, String tag) { return BuildConfig.DEBUG; } }); ``` ### Save logs to the file //TODO: More information will be added later ```java Logger.addLogAdapter(new DiskLogAdapter()); ``` Add custom tag to Csv format strategy ```java FormatStrategy formatStrategy = CsvFormatStrategy.newBuilder() .tag("custom") .build(); Logger.addLogAdapter(new DiskLogAdapter(formatStrategy)); ``` ### How it works ### More - Use filter for a better result. PRETTY_LOGGER or your custom tag - Make sure that wrap option is disabled - You can also simplify output by changing settings. - Timber Integration ```java // Set methodOffset to 5 in order to hide internal method calls Timber.plant(new Timber.DebugTree() { @Override protected void log(int priority, String tag, String message, Throwable t) { Logger.log(priority, tag, message, t); } }); ``` ### License
Copyright 2018 Orhan Obut

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
================================================ FILE: build.gradle ================================================ buildscript { ext.kotlinVersion = '1.2.51' repositories { google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:3.2.0' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion" } } allprojects { repositories { google() jcenter() } } subprojects { project -> group = GROUP version = VERSION_NAME apply plugin: 'checkstyle' task checkstyle(type: Checkstyle) { configFile rootProject.file('checkstyle.xml') source 'src/main/java' ignoreFailures false showViolations true include '**/*.java' classpath = files() } afterEvaluate { if (project.tasks.findByName('check')) { check.dependsOn('checkstyle') } } } task clean(type: Delete) { delete rootProject.buildDir } ext { minSdkVersion = 8 targetSdkVersion = 28 compileSdkVersion = 28 buildToolsVersion = '28.0.2' } ext.deps = [ junit : 'junit:junit:4.12', truth : 'com.google.truth:truth:0.28', robolectric : 'org.robolectric:robolectric:3.3', mockito : "org.mockito:mockito-core:2.8.9", json : "org.json:json:20160810", supportAnnotations: 'androidx.annotation:annotation:1.0.0', kotlin : "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlinVersion" ] ================================================ FILE: checkstyle.xml ================================================ ================================================ FILE: gradle/maven_push.gradle ================================================ 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: NEXUS_USERNAME, password: NEXUS_PASSWORD) } catch (Exception ignored) { 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 } ================================================ FILE: gradle/wrapper/gradle-wrapper.properties ================================================ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-4.6-all.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists ================================================ FILE: gradle.properties ================================================ VERSION_NAME=2.2.0 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 android.useAndroidX=true android.enableJetifier=true ================================================ FILE: gradlew ================================================ #!/usr/bin/env sh ############################################################################## ## ## Gradle start up script for UN*X ## ############################################################################## # Attempt to set APP_HOME # Resolve links: $0 may be a link PRG="$0" # Need this for relative symlinks. while [ -h "$PRG" ] ; do ls=`ls -ld "$PRG"` link=`expr "$ls" : '.*-> \(.*\)$'` if expr "$link" : '/.*' > /dev/null; then PRG="$link" else PRG=`dirname "$PRG"`"/$link" fi done SAVED="`pwd`" cd "`dirname \"$PRG\"`/" >/dev/null APP_HOME="`pwd -P`" cd "$SAVED" >/dev/null APP_NAME="Gradle" APP_BASE_NAME=`basename "$0"` # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS="" # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD="maximum" warn () { echo "$*" } die () { echo echo "$*" echo exit 1 } # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false case "`uname`" in CYGWIN* ) cygwin=true ;; Darwin* ) darwin=true ;; MINGW* ) msys=true ;; NONSTOP* ) nonstop=true ;; esac CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables JAVACMD="$JAVA_HOME/jre/sh/java" else JAVACMD="$JAVA_HOME/bin/java" fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else JAVACMD="java" which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi # Increase the maximum file descriptors if we can. if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then MAX_FD_LIMIT=`ulimit -H -n` if [ $? -eq 0 ] ; then if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then MAX_FD="$MAX_FD_LIMIT" fi ulimit -n $MAX_FD if [ $? -ne 0 ] ; then warn "Could not set maximum file descriptor limit: $MAX_FD" fi else warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" fi fi # For Darwin, add options to specify how the application appears in the dock if $darwin; then GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" fi # For Cygwin, switch paths to Windows format before running java if $cygwin ; then APP_HOME=`cygpath --path --mixed "$APP_HOME"` CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` JAVACMD=`cygpath --unix "$JAVACMD"` # We build the pattern for arguments to be converted via cygpath ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` SEP="" for dir in $ROOTDIRSRAW ; do ROOTDIRS="$ROOTDIRS$SEP$dir" SEP="|" done OURCYGPATTERN="(^($ROOTDIRS))" # Add a user-defined pattern to the cygpath arguments if [ "$GRADLE_CYGPATTERN" != "" ] ; then OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" fi # Now convert the arguments - kludge to limit ourselves to /bin/sh i=0 for arg in "$@" ; do CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` else eval `echo args$i`="\"$arg\"" fi i=$((i+1)) done case $i in (0) set -- ;; (1) set -- "$args0" ;; (2) set -- "$args0" "$args1" ;; (3) set -- "$args0" "$args1" "$args2" ;; (4) set -- "$args0" "$args1" "$args2" "$args3" ;; (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; esac fi # Escape application args save () { for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done echo " " } APP_ARGS=$(save "$@") # Collect all arguments for the java command, following the shell quoting and substitution rules eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then cd "$(dirname "$0")" fi exec "$JAVACMD" "$@" ================================================ FILE: gradlew.bat ================================================ @if "%DEBUG%" == "" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @rem @rem ########################################################################## @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 if "%DIRNAME%" == "" set DIRNAME=. set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. set DEFAULT_JVM_OPTS= @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if "%ERRORLEVEL%" == "0" goto init echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto init echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :init @rem Get command-line arguments, handling Windows variants if not "%OS%" == "Windows_NT" goto win9xME_args :win9xME_args @rem Slurp the command line arguments. set CMD_LINE_ARGS= set _SKIP=2 :win9xME_args_slurp if "x%~1" == "x" goto execute set CMD_LINE_ARGS=%* :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar @rem Execute Gradle "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% :end @rem End local scope for the variables with windows NT shell if "%ERRORLEVEL%"=="0" goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 exit /b 1 :mainEnd if "%OS%"=="Windows_NT" endlocal :omega ================================================ FILE: logger/build.gradle ================================================ apply plugin: 'com.android.library' apply plugin: 'kotlin-android' android { compileSdkVersion rootProject.ext.compileSdkVersion buildToolsVersion rootProject.ext.buildToolsVersion defaultConfig { minSdkVersion rootProject.ext.minSdkVersion } lintOptions { textReport true textOutput 'stdout' } testOptions { unitTests.returnDefaultValues = true } } dependencies { implementation deps.supportAnnotations testImplementation deps.junit testImplementation deps.truth testImplementation deps.robolectric testImplementation deps.mockito testImplementation deps.json testImplementation deps.kotlin } apply from: rootProject.file('gradle/maven_push.gradle') ================================================ FILE: logger/gradle.properties ================================================ POM_NAME=Logger POM_ARTIFACT_ID=logger POM_PACKAGING=aar ================================================ FILE: logger/src/main/AndroidManifest.xml ================================================ ================================================ FILE: logger/src/main/java/com/orhanobut/logger/AndroidLogAdapter.java ================================================ package com.orhanobut.logger; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import static com.orhanobut.logger.Utils.checkNotNull; /** * Android terminal log output implementation for {@link LogAdapter}. * * Prints output to LogCat with pretty borders. * *
 *  ┌──────────────────────────
 *  │ Method stack history
 *  ├┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
 *  │ Log message
 *  └──────────────────────────
 * 
*/ public class AndroidLogAdapter implements LogAdapter { @NonNull private final FormatStrategy formatStrategy; public AndroidLogAdapter() { this.formatStrategy = PrettyFormatStrategy.newBuilder().build(); } public AndroidLogAdapter(@NonNull FormatStrategy formatStrategy) { this.formatStrategy = checkNotNull(formatStrategy); } @Override public boolean isLoggable(int priority, @Nullable String tag) { return true; } @Override public void log(int priority, @Nullable String tag, @NonNull String message) { formatStrategy.log(priority, tag, message); } } ================================================ FILE: logger/src/main/java/com/orhanobut/logger/CsvFormatStrategy.java ================================================ package com.orhanobut.logger; import android.os.Environment; import android.os.Handler; import android.os.HandlerThread; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import static com.orhanobut.logger.Utils.checkNotNull; /** * CSV formatted file logging for Android. * Writes to CSV the following data: * epoch timestamp, ISO8601 timestamp (human-readable), log level, tag, log message. */ public class CsvFormatStrategy implements FormatStrategy { private static final String NEW_LINE = System.getProperty("line.separator"); private static final String NEW_LINE_REPLACEMENT = "
"; private static final String SEPARATOR = ","; @NonNull private final Date date; @NonNull private final SimpleDateFormat dateFormat; @NonNull private final LogStrategy logStrategy; @Nullable private final String tag; private CsvFormatStrategy(@NonNull Builder builder) { checkNotNull(builder); date = builder.date; dateFormat = builder.dateFormat; logStrategy = builder.logStrategy; tag = builder.tag; } @NonNull public static Builder newBuilder() { return new Builder(); } @Override public void log(int priority, @Nullable String onceOnlyTag, @NonNull String message) { checkNotNull(message); String tag = formatTag(onceOnlyTag); date.setTime(System.currentTimeMillis()); StringBuilder builder = new StringBuilder(); // machine-readable date/time builder.append(Long.toString(date.getTime())); // human-readable date/time builder.append(SEPARATOR); builder.append(dateFormat.format(date)); // level builder.append(SEPARATOR); builder.append(Utils.logLevel(priority)); // tag builder.append(SEPARATOR); builder.append(tag); // message if (message.contains(NEW_LINE)) { // a new line would break the CSV format, so we replace it here message = message.replaceAll(NEW_LINE, NEW_LINE_REPLACEMENT); } builder.append(SEPARATOR); builder.append(message); // new line builder.append(NEW_LINE); logStrategy.log(priority, tag, builder.toString()); } @Nullable private String formatTag(@Nullable String tag) { if (!Utils.isEmpty(tag) && !Utils.equals(this.tag, tag)) { return this.tag + "-" + tag; } return this.tag; } public static final class Builder { private static final int MAX_BYTES = 500 * 1024; // 500K averages to a 4000 lines per file Date date; SimpleDateFormat dateFormat; LogStrategy logStrategy; String tag = "PRETTY_LOGGER"; private Builder() { } @NonNull public Builder date(@Nullable Date val) { date = val; return this; } @NonNull public Builder dateFormat(@Nullable SimpleDateFormat val) { dateFormat = val; return this; } @NonNull public Builder logStrategy(@Nullable LogStrategy val) { logStrategy = val; return this; } @NonNull public Builder tag(@Nullable String tag) { this.tag = tag; return this; } @NonNull public CsvFormatStrategy build() { if (date == null) { date = new Date(); } if (dateFormat == null) { dateFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss.SSS", Locale.UK); } if (logStrategy == null) { String diskPath = Environment.getExternalStorageDirectory().getAbsolutePath(); String folder = diskPath + File.separatorChar + "logger"; HandlerThread ht = new HandlerThread("AndroidFileLogger." + folder); ht.start(); Handler handler = new DiskLogStrategy.WriteHandler(ht.getLooper(), folder, MAX_BYTES); logStrategy = new DiskLogStrategy(handler); } return new CsvFormatStrategy(this); } } } ================================================ FILE: logger/src/main/java/com/orhanobut/logger/DiskLogAdapter.java ================================================ package com.orhanobut.logger; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import static com.orhanobut.logger.Utils.checkNotNull; /** * This is used to saves log messages to the disk. * By default it uses {@link CsvFormatStrategy} to translates text message into CSV format. */ public class DiskLogAdapter implements LogAdapter { @NonNull private final FormatStrategy formatStrategy; public DiskLogAdapter() { formatStrategy = CsvFormatStrategy.newBuilder().build(); } public DiskLogAdapter(@NonNull FormatStrategy formatStrategy) { this.formatStrategy = checkNotNull(formatStrategy); } @Override public boolean isLoggable(int priority, @Nullable String tag) { return true; } @Override public void log(int priority, @Nullable String tag, @NonNull String message) { formatStrategy.log(priority, tag, message); } } ================================================ FILE: logger/src/main/java/com/orhanobut/logger/DiskLogStrategy.java ================================================ package com.orhanobut.logger; import android.os.Handler; import android.os.Looper; import android.os.Message; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import java.io.File; import java.io.FileWriter; import java.io.IOException; import static com.orhanobut.logger.Utils.checkNotNull; /** * Abstract class that takes care of background threading the file log operation on Android. * implementing classes are free to directly perform I/O operations there. * * Writes all logs to the disk with CSV format. */ public class DiskLogStrategy implements LogStrategy { @NonNull private final Handler handler; public DiskLogStrategy(@NonNull Handler handler) { this.handler = checkNotNull(handler); } @Override public void log(int level, @Nullable String tag, @NonNull String message) { checkNotNull(message); // do nothing on the calling thread, simply pass the tag/msg to the background thread handler.sendMessage(handler.obtainMessage(level, message)); } static class WriteHandler extends Handler { @NonNull private final String folder; private final int maxFileSize; WriteHandler(@NonNull Looper looper, @NonNull String folder, int maxFileSize) { super(checkNotNull(looper)); this.folder = checkNotNull(folder); this.maxFileSize = maxFileSize; } @SuppressWarnings("checkstyle:emptyblock") @Override public void handleMessage(@NonNull Message msg) { String content = (String) msg.obj; FileWriter fileWriter = null; File logFile = getLogFile(folder, "logs"); try { fileWriter = new FileWriter(logFile, true); writeLog(fileWriter, content); fileWriter.flush(); fileWriter.close(); } catch (IOException e) { if (fileWriter != null) { try { fileWriter.flush(); fileWriter.close(); } catch (IOException e1) { /* fail silently */ } } } } /** * This is always called on a single background thread. * Implementing classes must ONLY write to the fileWriter and nothing more. * The abstract class takes care of everything else including close the stream and catching IOException * * @param fileWriter an instance of FileWriter already initialised to the correct file */ private void writeLog(@NonNull FileWriter fileWriter, @NonNull String content) throws IOException { checkNotNull(fileWriter); checkNotNull(content); fileWriter.append(content); } private File getLogFile(@NonNull String folderName, @NonNull String fileName) { checkNotNull(folderName); checkNotNull(fileName); File folder = new File(folderName); if (!folder.exists()) { //TODO: What if folder is not created, what happens then? folder.mkdirs(); } int newFileCount = 0; File newFile; File existingFile = null; newFile = new File(folder, String.format("%s_%s.csv", fileName, newFileCount)); while (newFile.exists()) { existingFile = newFile; newFileCount++; newFile = new File(folder, String.format("%s_%s.csv", fileName, newFileCount)); } if (existingFile != null) { if (existingFile.length() >= maxFileSize) { return newFile; } return existingFile; } return newFile; } } } ================================================ FILE: logger/src/main/java/com/orhanobut/logger/FormatStrategy.java ================================================ package com.orhanobut.logger; import androidx.annotation.NonNull; import androidx.annotation.Nullable; /** * Used to determine how messages should be printed or saved. * * @see PrettyFormatStrategy * @see CsvFormatStrategy */ public interface FormatStrategy { void log(int priority, @Nullable String tag, @NonNull String message); } ================================================ FILE: logger/src/main/java/com/orhanobut/logger/LogAdapter.java ================================================ package com.orhanobut.logger; import androidx.annotation.NonNull; import androidx.annotation.Nullable; /** * Provides a common interface to emits logs through. This is a required contract for Logger. * * @see AndroidLogAdapter * @see DiskLogAdapter */ public interface LogAdapter { /** * Used to determine whether log should be printed out or not. * * @param priority is the log level e.g. DEBUG, WARNING * @param tag is the given tag for the log message * * @return is used to determine if log should printed. * If it is true, it will be printed, otherwise it'll be ignored. */ boolean isLoggable(int priority, @Nullable String tag); /** * Each log will use this pipeline * * @param priority is the log level e.g. DEBUG, WARNING * @param tag is the given tag for the log message. * @param message is the given message for the log message. */ void log(int priority, @Nullable String tag, @NonNull String message); } ================================================ FILE: logger/src/main/java/com/orhanobut/logger/LogStrategy.java ================================================ package com.orhanobut.logger; import androidx.annotation.NonNull; import androidx.annotation.Nullable; /** * Determines destination target for the logs such as Disk, Logcat etc. * * @see LogcatLogStrategy * @see DiskLogStrategy */ public interface LogStrategy { /** * This is invoked by Logger each time a log message is processed. * Interpret this method as last destination of the log in whole pipeline. * * @param priority is the log level e.g. DEBUG, WARNING * @param tag is the given tag for the log message. * @param message is the given message for the log message. */ void log(int priority, @Nullable String tag, @NonNull String message); } ================================================ FILE: logger/src/main/java/com/orhanobut/logger/LogcatLogStrategy.java ================================================ package com.orhanobut.logger; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import android.util.Log; import static com.orhanobut.logger.Utils.checkNotNull; /** * LogCat implementation for {@link LogStrategy} * * This simply prints out all logs to Logcat by using standard {@link Log} class. */ public class LogcatLogStrategy implements LogStrategy { static final String DEFAULT_TAG = "NO_TAG"; @Override public void log(int priority, @Nullable String tag, @NonNull String message) { checkNotNull(message); if (tag == null) { tag = DEFAULT_TAG; } Log.println(priority, tag, message); } } ================================================ FILE: logger/src/main/java/com/orhanobut/logger/Logger.java ================================================ package com.orhanobut.logger; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import static com.orhanobut.logger.Utils.checkNotNull; /** *
 *  ┌────────────────────────────────────────────
 *  │ LOGGER
 *  ├┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
 *  │ Standard logging mechanism
 *  ├┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
 *  │ But more pretty, simple and powerful
 *  └────────────────────────────────────────────
 * 
* *

How to use it

* Initialize it first *

 *   Logger.addLogAdapter(new AndroidLogAdapter());
 * 
* * And use the appropriate static Logger methods. * *

 *   Logger.d("debug");
 *   Logger.e("error");
 *   Logger.w("warning");
 *   Logger.v("verbose");
 *   Logger.i("information");
 *   Logger.wtf("What a Terrible Failure");
 * 
* *

String format arguments are supported

*

 *   Logger.d("hello %s", "world");
 * 
* *

Collections are support ed(only available for debug logs)

*

 *   Logger.d(MAP);
 *   Logger.d(SET);
 *   Logger.d(LIST);
 *   Logger.d(ARRAY);
 * 
* *

Json and Xml support (output will be in debug level)

*

 *   Logger.json(JSON_CONTENT);
 *   Logger.xml(XML_CONTENT);
 * 
* *

Customize Logger

* Based on your needs, you can change the following settings: *
    *
  • Different {@link LogAdapter}
  • *
  • Different {@link FormatStrategy}
  • *
  • Different {@link LogStrategy}
  • *
* * @see LogAdapter * @see FormatStrategy * @see LogStrategy */ public final class Logger { public static final int VERBOSE = 2; public static final int DEBUG = 3; public static final int INFO = 4; public static final int WARN = 5; public static final int ERROR = 6; public static final int ASSERT = 7; @NonNull private static Printer printer = new LoggerPrinter(); private Logger() { //no instance } public static void printer(@NonNull Printer printer) { Logger.printer = checkNotNull(printer); } public static void addLogAdapter(@NonNull LogAdapter adapter) { printer.addAdapter(checkNotNull(adapter)); } public static void clearLogAdapters() { printer.clearLogAdapters(); } /** * Given tag will be used as tag only once for this method call regardless of the tag that's been * set during initialization. After this invocation, the general tag that's been set will * be used for the subsequent log calls */ public static Printer t(@Nullable String tag) { return printer.t(tag); } /** * General log function that accepts all configurations as parameter */ public static void log(int priority, @Nullable String tag, @Nullable String message, @Nullable Throwable throwable) { printer.log(priority, tag, message, throwable); } public static void d(@NonNull String message, @Nullable Object... args) { printer.d(message, args); } public static void d(@Nullable Object object) { printer.d(object); } public static void e(@NonNull String message, @Nullable Object... args) { printer.e(null, message, args); } public static void e(@Nullable Throwable throwable, @NonNull String message, @Nullable Object... args) { printer.e(throwable, message, args); } public static void i(@NonNull String message, @Nullable Object... args) { printer.i(message, args); } public static void v(@NonNull String message, @Nullable Object... args) { printer.v(message, args); } public static void w(@NonNull String message, @Nullable Object... args) { printer.w(message, args); } /** * Tip: Use this for exceptional situations to log * ie: Unexpected errors etc */ public static void wtf(@NonNull String message, @Nullable Object... args) { printer.wtf(message, args); } /** * Formats the given json content and print it */ public static void json(@Nullable String json) { printer.json(json); } /** * Formats the given xml content and print it */ public static void xml(@Nullable String xml) { printer.xml(xml); } } ================================================ FILE: logger/src/main/java/com/orhanobut/logger/LoggerPrinter.java ================================================ package com.orhanobut.logger; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.StringReader; import java.io.StringWriter; import java.util.ArrayList; import java.util.List; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import static com.orhanobut.logger.Logger.ASSERT; import static com.orhanobut.logger.Logger.DEBUG; import static com.orhanobut.logger.Logger.ERROR; import static com.orhanobut.logger.Logger.INFO; import static com.orhanobut.logger.Logger.VERBOSE; import static com.orhanobut.logger.Logger.WARN; import static com.orhanobut.logger.Utils.checkNotNull; class LoggerPrinter implements Printer { /** * It is used for json pretty print */ private static final int JSON_INDENT = 2; /** * Provides one-time used tag for the log message */ private final ThreadLocal localTag = new ThreadLocal<>(); private final List logAdapters = new ArrayList<>(); @Override public Printer t(String tag) { if (tag != null) { localTag.set(tag); } return this; } @Override public void d(@NonNull String message, @Nullable Object... args) { log(DEBUG, null, message, args); } @Override public void d(@Nullable Object object) { log(DEBUG, null, Utils.toString(object)); } @Override public void e(@NonNull String message, @Nullable Object... args) { e(null, message, args); } @Override public void e(@Nullable Throwable throwable, @NonNull String message, @Nullable Object... args) { log(ERROR, throwable, message, args); } @Override public void w(@NonNull String message, @Nullable Object... args) { log(WARN, null, message, args); } @Override public void i(@NonNull String message, @Nullable Object... args) { log(INFO, null, message, args); } @Override public void v(@NonNull String message, @Nullable Object... args) { log(VERBOSE, null, message, args); } @Override public void wtf(@NonNull String message, @Nullable Object... args) { log(ASSERT, null, message, args); } @Override public void json(@Nullable String json) { if (Utils.isEmpty(json)) { d("Empty/Null json content"); return; } try { json = json.trim(); 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); return; } e("Invalid Json"); } catch (JSONException e) { e("Invalid Json"); } } @Override public void xml(@Nullable String xml) { if (Utils.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("Invalid xml"); } } @Override public synchronized void log(int priority, @Nullable String tag, @Nullable String message, @Nullable Throwable throwable) { if (throwable != null && message != null) { message += " : " + Utils.getStackTraceString(throwable); } if (throwable != null && message == null) { message = Utils.getStackTraceString(throwable); } if (Utils.isEmpty(message)) { message = "Empty/NULL log message"; } for (LogAdapter adapter : logAdapters) { if (adapter.isLoggable(priority, tag)) { adapter.log(priority, tag, message); } } } @Override public void clearLogAdapters() { logAdapters.clear(); } @Override public void addAdapter(@NonNull LogAdapter adapter) { logAdapters.add(checkNotNull(adapter)); } /** * This method is synchronized in order to avoid messy of logs' order. */ private synchronized void log(int priority, @Nullable Throwable throwable, @NonNull String msg, @Nullable Object... args) { checkNotNull(msg); String tag = getTag(); String message = createMessage(msg, args); log(priority, tag, message, throwable); } /** * @return the appropriate tag based on local or global */ @Nullable private String getTag() { String tag = localTag.get(); if (tag != null) { localTag.remove(); return tag; } return null; } @NonNull private String createMessage(@NonNull String message, @Nullable Object... args) { return args == null || args.length == 0 ? message : String.format(message, args); } } ================================================ FILE: logger/src/main/java/com/orhanobut/logger/PrettyFormatStrategy.java ================================================ package com.orhanobut.logger; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import static com.orhanobut.logger.Utils.checkNotNull; /** * Draws borders around the given log message along with additional information such as : * *
    *
  • Thread information
  • *
  • Method stack trace
  • *
* *
 *  ┌──────────────────────────
 *  │ Method stack history
 *  ├┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
 *  │ Thread information
 *  ├┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
 *  │ Log message
 *  └──────────────────────────
 * 
* *

Customize

*

 *   FormatStrategy formatStrategy = PrettyFormatStrategy.newBuilder()
 *       .showThreadInfo(false)  // (Optional) Whether to show thread info or not. Default true
 *       .methodCount(0)         // (Optional) How many method line to show. Default 2
 *       .methodOffset(7)        // (Optional) Hides internal method calls up to offset. Default 5
 *       .logStrategy(customLog) // (Optional) Changes the log strategy to print out. Default LogCat
 *       .tag("My custom tag")   // (Optional) Global tag for every log. Default PRETTY_LOGGER
 *       .build();
 * 
*/ public class PrettyFormatStrategy implements FormatStrategy { /** * 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; /** * The minimum stack trace index, starts at this class after two native calls. */ private static final int MIN_STACK_OFFSET = 5; /** * 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_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; private final int methodCount; private final int methodOffset; private final boolean showThreadInfo; @NonNull private final LogStrategy logStrategy; @Nullable private final String tag; private PrettyFormatStrategy(@NonNull Builder builder) { checkNotNull(builder); methodCount = builder.methodCount; methodOffset = builder.methodOffset; showThreadInfo = builder.showThreadInfo; logStrategy = builder.logStrategy; tag = builder.tag; } @NonNull public static Builder newBuilder() { return new Builder(); } @Override public void log(int priority, @Nullable String onceOnlyTag, @NonNull String message) { checkNotNull(message); String tag = formatTag(onceOnlyTag); logTopBorder(priority, tag); logHeaderContent(priority, 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(priority, tag); } logContent(priority, tag, message); logBottomBorder(priority, tag); return; } if (methodCount > 0) { logDivider(priority, 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(priority, tag, new String(bytes, i, count)); } logBottomBorder(priority, tag); } private void logTopBorder(int logType, @Nullable String tag) { logChunk(logType, tag, TOP_BORDER); } @SuppressWarnings("StringBufferReplaceableByString") private void logHeaderContent(int logType, @Nullable String tag, int methodCount) { StackTraceElement[] trace = Thread.currentThread().getStackTrace(); if (showThreadInfo) { logChunk(logType, tag, HORIZONTAL_LINE + " Thread: " + Thread.currentThread().getName()); logDivider(logType, tag); } String level = ""; int stackOffset = getStackOffset(trace) + methodOffset; //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(HORIZONTAL_LINE) .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 logBottomBorder(int logType, @Nullable String tag) { logChunk(logType, tag, BOTTOM_BORDER); } private void logDivider(int logType, @Nullable String tag) { logChunk(logType, tag, MIDDLE_BORDER); } private void logContent(int logType, @Nullable String tag, @NonNull String chunk) { checkNotNull(chunk); String[] lines = chunk.split(System.getProperty("line.separator")); for (String line : lines) { logChunk(logType, tag, HORIZONTAL_LINE + " " + line); } } private void logChunk(int priority, @Nullable String tag, @NonNull String chunk) { checkNotNull(chunk); logStrategy.log(priority, tag, chunk); } private String getSimpleClassName(@NonNull String name) { checkNotNull(name); int lastIndex = name.lastIndexOf("."); return name.substring(lastIndex + 1); } /** * 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(@NonNull StackTraceElement[] trace) { checkNotNull(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; } @Nullable private String formatTag(@Nullable String tag) { if (!Utils.isEmpty(tag) && !Utils.equals(this.tag, tag)) { return this.tag + "-" + tag; } return this.tag; } public static class Builder { int methodCount = 2; int methodOffset = 0; boolean showThreadInfo = true; @Nullable LogStrategy logStrategy; @Nullable String tag = "PRETTY_LOGGER"; private Builder() { } @NonNull public Builder methodCount(int val) { methodCount = val; return this; } @NonNull public Builder methodOffset(int val) { methodOffset = val; return this; } @NonNull public Builder showThreadInfo(boolean val) { showThreadInfo = val; return this; } @NonNull public Builder logStrategy(@Nullable LogStrategy val) { logStrategy = val; return this; } @NonNull public Builder tag(@Nullable String tag) { this.tag = tag; return this; } @NonNull public PrettyFormatStrategy build() { if (logStrategy == null) { logStrategy = new LogcatLogStrategy(); } return new PrettyFormatStrategy(this); } } } ================================================ FILE: logger/src/main/java/com/orhanobut/logger/Printer.java ================================================ package com.orhanobut.logger; import androidx.annotation.NonNull; import androidx.annotation.Nullable; /** * A proxy interface to enable additional operations. * Contains all possible Log message usages. */ public interface Printer { void addAdapter(@NonNull LogAdapter adapter); Printer t(@Nullable String tag); void d(@NonNull String message, @Nullable Object... args); void d(@Nullable Object object); void e(@NonNull String message, @Nullable Object... args); void e(@Nullable Throwable throwable, @NonNull String message, @Nullable Object... args); void w(@NonNull String message, @Nullable Object... args); void i(@NonNull String message, @Nullable Object... args); void v(@NonNull String message, @Nullable Object... args); void wtf(@NonNull String message, @Nullable Object... args); /** * Formats the given json content and print it */ void json(@Nullable String json); /** * Formats the given xml content and print it */ void xml(@Nullable String xml); void log(int priority, @Nullable String tag, @Nullable String message, @Nullable Throwable throwable); void clearLogAdapters(); } ================================================ FILE: logger/src/main/java/com/orhanobut/logger/Utils.java ================================================ package com.orhanobut.logger; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import java.io.PrintWriter; import java.io.StringWriter; import java.net.UnknownHostException; import java.util.Arrays; import static com.orhanobut.logger.Logger.ASSERT; import static com.orhanobut.logger.Logger.DEBUG; import static com.orhanobut.logger.Logger.ERROR; import static com.orhanobut.logger.Logger.INFO; import static com.orhanobut.logger.Logger.VERBOSE; import static com.orhanobut.logger.Logger.WARN; /** * Provides convenient methods to some common operations */ final class Utils { private Utils() { // 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 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; } /** * 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(); } StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); tr.printStackTrace(pw); pw.flush(); return sw.toString(); } static String logLevel(int value) { switch (value) { case VERBOSE: return "VERBOSE"; case DEBUG: return "DEBUG"; case INFO: return "INFO"; case WARN: return "WARN"; case ERROR: return "ERROR"; case ASSERT: return "ASSERT"; default: return "UNKNOWN"; } } public static String toString(Object object) { if (object == null) { return "null"; } if (!object.getClass().isArray()) { return object.toString(); } if (object instanceof boolean[]) { return Arrays.toString((boolean[]) object); } if (object instanceof byte[]) { return Arrays.toString((byte[]) object); } if (object instanceof char[]) { return Arrays.toString((char[]) object); } if (object instanceof short[]) { return Arrays.toString((short[]) object); } if (object instanceof int[]) { return Arrays.toString((int[]) object); } if (object instanceof long[]) { return Arrays.toString((long[]) object); } if (object instanceof float[]) { return Arrays.toString((float[]) object); } if (object instanceof double[]) { return Arrays.toString((double[]) object); } if (object instanceof Object[]) { return Arrays.deepToString((Object[]) object); } return "Couldn't find a correct type for the object"; } @NonNull static T checkNotNull(@Nullable final T obj) { if (obj == null) { throw new NullPointerException(); } return obj; } } ================================================ FILE: logger/src/test/java/com.orhanobut.logger/AndroidLogAdapterTest.kt ================================================ package com.orhanobut.logger import org.junit.Test import com.google.common.truth.Truth.assertThat import com.orhanobut.logger.Logger.DEBUG import org.mockito.Mockito.mock import org.mockito.Mockito.verify class AndroidLogAdapterTest { @Test fun isLoggable() { val logAdapter = AndroidLogAdapter() assertThat(logAdapter.isLoggable(DEBUG, "tag")).isTrue() } @Test fun log() { val formatStrategy = mock(FormatStrategy::class.java) val logAdapter = AndroidLogAdapter(formatStrategy) logAdapter.log(DEBUG, null, "message") verify(formatStrategy).log(DEBUG, null, "message") } } ================================================ FILE: logger/src/test/java/com.orhanobut.logger/CsvFormatStrategyTest.kt ================================================ package com.orhanobut.logger import org.junit.Test import com.google.common.truth.Truth.assertThat class CsvFormatStrategyTest { @Test fun log() { val formatStrategy = CsvFormatStrategy.newBuilder() .logStrategy { priority, tag, message -> assertThat(tag).isEqualTo("PRETTY_LOGGER-tag") assertThat(priority).isEqualTo(Logger.VERBOSE) assertThat(message).contains("VERBOSE,PRETTY_LOGGER-tag,message") } .build() formatStrategy.log(Logger.VERBOSE, "tag", "message") } @Test fun defaultTag() { val formatStrategy = CsvFormatStrategy.newBuilder() .logStrategy { priority, tag, message -> assertThat(tag).isEqualTo("PRETTY_LOGGER") } .build() formatStrategy.log(Logger.VERBOSE, null, "message") } @Test fun customTag() { val formatStrategy = CsvFormatStrategy.newBuilder() .tag("custom") .logStrategy { priority, tag, message -> assertThat(tag).isEqualTo("custom") } .build() formatStrategy.log(Logger.VERBOSE, null, "message") } } ================================================ FILE: logger/src/test/java/com.orhanobut.logger/DiskLogAdapterTest.kt ================================================ package com.orhanobut.logger import com.google.common.truth.Truth.assertThat import org.junit.Before import org.junit.Test import org.mockito.Mock import org.mockito.Mockito.verify import org.mockito.MockitoAnnotations.initMocks class DiskLogAdapterTest { @Mock private lateinit var formatStrategy: FormatStrategy @Before fun setup() { initMocks(this) } @Test fun isLoggableTrue() { val logAdapter = DiskLogAdapter(formatStrategy) assertThat(logAdapter.isLoggable(Logger.VERBOSE, "tag")).isTrue() } @Test fun isLoggableFalse() { val logAdapter = object : DiskLogAdapter(formatStrategy) { override fun isLoggable(priority: Int, tag: String?): Boolean { return false } } assertThat(logAdapter.isLoggable(Logger.VERBOSE, "tag")).isFalse() } @Test fun log() { val logAdapter = DiskLogAdapter(formatStrategy) logAdapter.log(Logger.VERBOSE, "tag", "message") verify(formatStrategy).log(Logger.VERBOSE, "tag", "message") } } ================================================ FILE: logger/src/test/java/com.orhanobut.logger/DiskLogStrategyTest.kt ================================================ package com.orhanobut.logger import android.os.Handler import org.junit.Test import com.orhanobut.logger.Logger.DEBUG import org.mockito.Mockito.mock import org.mockito.Mockito.verify class DiskLogStrategyTest { @Test fun log() { val handler = mock(Handler::class.java) val logStrategy = DiskLogStrategy(handler) logStrategy.log(DEBUG, "tag", "message") verify(handler).sendMessage(handler.obtainMessage(DEBUG, "message")) } } ================================================ FILE: logger/src/test/java/com.orhanobut.logger/LogAssert.kt ================================================ package com.orhanobut.logger import com.google.common.truth.Truth.assertThat internal class LogAssert(private val items: MutableList, tag: String?, private val priority: Int) { private val tag: String private var index = 0 init { this.tag = tag ?: DEFAULT_TAG } fun hasTopBorder(): LogAssert { return hasLog(priority, tag, TOP_BORDER) } fun hasBottomBorder(): LogAssert { return hasLog(priority, tag, BOTTOM_BORDER) } fun hasMiddleBorder(): LogAssert { return hasLog(priority, tag, MIDDLE_BORDER) } fun hasThread(threadName: String): LogAssert { return hasLog(priority, tag, "$HORIZONTAL_LINE Thread: $threadName") } fun hasMethodInfo(methodInfo: String): LogAssert { return hasLog(priority, tag, "$HORIZONTAL_LINE $methodInfo") } fun hasMessage(message: String): LogAssert { return hasLog(priority, tag, "$HORIZONTAL_LINE $message") } private fun hasLog(priority: Int, tag: String, message: String): LogAssert = apply { val item = items[index++] assertThat(item.priority).isEqualTo(priority) assertThat(item.tag).isEqualTo(tag) assertThat(item.message).isEqualTo(message) } fun skip(): LogAssert = apply { index++ } fun hasNoMoreMessages() { assertThat(items).hasSize(index) items.clear() } internal class LogItem(val priority: Int, val tag: String, val message: String) companion object { private const val DEFAULT_TAG = "PRETTY_LOGGER" private const val TOP_LEFT_CORNER = '┌' private const val BOTTOM_LEFT_CORNER = '└' private const val MIDDLE_CORNER = '├' private const val HORIZONTAL_LINE = '│' private const val DOUBLE_DIVIDER = "────────────────────────────────────────────────────────" private const val SINGLE_DIVIDER = "┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄" private val TOP_BORDER = TOP_LEFT_CORNER + DOUBLE_DIVIDER + DOUBLE_DIVIDER private val BOTTOM_BORDER = BOTTOM_LEFT_CORNER + DOUBLE_DIVIDER + DOUBLE_DIVIDER private val MIDDLE_BORDER = MIDDLE_CORNER + SINGLE_DIVIDER + SINGLE_DIVIDER } } ================================================ FILE: logger/src/test/java/com.orhanobut.logger/LogcatLogStrategyTest.kt ================================================ package com.orhanobut.logger import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config import org.robolectric.shadows.ShadowLog import com.google.common.truth.Truth.assertThat import com.orhanobut.logger.Logger.DEBUG @RunWith(RobolectricTestRunner::class) class LogcatLogStrategyTest { @Test fun log() { val logStrategy = LogcatLogStrategy() logStrategy.log(DEBUG, "tag", "message") val logItems = ShadowLog.getLogs() assertThat(logItems[0].type).isEqualTo(DEBUG) assertThat(logItems[0].msg).isEqualTo("message") assertThat(logItems[0].tag).isEqualTo("tag") } @Test fun logWithNullTag() { val logStrategy = LogcatLogStrategy() logStrategy.log(DEBUG, null, "message") val logItems = ShadowLog.getLogs() assertThat(logItems[0].tag).isEqualTo(LogcatLogStrategy.DEFAULT_TAG) } } ================================================ FILE: logger/src/test/java/com.orhanobut.logger/LoggerPrinterTest.kt ================================================ package com.orhanobut.logger import com.orhanobut.logger.Logger.* import org.junit.Before import org.junit.Test import org.mockito.Matchers.any import org.mockito.Matchers.contains import org.mockito.Matchers.eq import org.mockito.Matchers.isNull import org.mockito.Mock import org.mockito.Mockito.`when` import org.mockito.Mockito.mock import org.mockito.Mockito.never import org.mockito.Mockito.times import org.mockito.Mockito.verify import org.mockito.Mockito.verifyZeroInteractions import org.mockito.MockitoAnnotations.initMocks import java.util.* class LoggerPrinterTest { private val printer = LoggerPrinter() @Mock private lateinit var adapter: LogAdapter @Before fun setup() { initMocks(this) `when`(adapter!!.isLoggable(any(Int::class.java), any(String::class.java))).thenReturn(true) printer.addAdapter(adapter!!) } @Test fun logDebug() { printer.d("message %s", "sent") verify(adapter).log(DEBUG, null, "message sent") } @Test fun logError() { printer.e("message %s", "sent") verify(adapter).log(ERROR, null, "message sent") } @Test fun logErrorWithThrowable() { val throwable = Throwable("exception") printer.e(throwable, "message %s", "sent") verify(adapter).log(eq(ERROR), isNull(String::class.java), contains("message sent : java.lang.Throwable: exception")) } @Test fun logWarning() { printer.w("message %s", "sent") verify(adapter).log(WARN, null, "message sent") } @Test fun logInfo() { printer.i("message %s", "sent") verify(adapter).log(INFO, null, "message sent") } @Test fun logWtf() { printer.wtf("message %s", "sent") verify(adapter).log(ASSERT, null, "message sent") } @Test fun logVerbose() { printer.v("message %s", "sent") verify(adapter).log(VERBOSE, null, "message sent") } @Test fun oneTimeTag() { printer.t("tag").d("message") verify(adapter).log(DEBUG, "tag", "message") } @Test fun logObject() { val `object` = "Test" printer.d(`object`) verify(adapter).log(DEBUG, null, "Test") } @Test fun logArray() { val `object` = intArrayOf(1, 6, 7, 30, 33) printer.d(`object`) verify(adapter).log(DEBUG, null, "[1, 6, 7, 30, 33]") } @Test fun logStringArray() { val `object` = arrayOf("a", "b", "c") printer.d(`object`) verify(adapter).log(DEBUG, null, "[a, b, c]") } @Test fun logMultiDimensionArray() { val doubles = arrayOf(doubleArrayOf(1.0, 6.0), doubleArrayOf(1.2, 33.0)) printer.d(doubles) verify(adapter).log(DEBUG, null, "[[1.0, 6.0], [1.2, 33.0]]") } @Test fun logList() { val list = Arrays.asList("foo", "bar") printer.d(list) verify(adapter).log(DEBUG, null, list.toString()) } @Test fun logMap() { val map = HashMap() map["key"] = "value" map["key2"] = "value2" printer.d(map) verify(adapter).log(DEBUG, null, map.toString()) } @Test fun logSet() { val set = HashSet() set.add("key") set.add("key1") printer.d(set) verify(adapter).log(DEBUG, null, set.toString()) } @Test fun logJsonObject() { printer.json(" {\"key\":3}") verify(adapter).log(DEBUG, null, "{\"key\": 3}") } @Test fun logJsonArray() { printer.json("[{\"key\":3}]") verify(adapter).log(DEBUG, null, "[{\"key\": 3}]") } @Test fun logInvalidJsonObject() { printer.json("no json") printer.json("{ missing end") verify(adapter, times(2)).log(ERROR, null, "Invalid Json") } @Test fun jsonLogEmptyOrNull() { printer.json(null) printer.json("") verify(adapter, times(2)).log(DEBUG, null, "Empty/Null json content") } @Test fun xmlLog() { printer.xml("Test") verify(adapter).log(DEBUG, null, "\nTest\n") } @Test fun invalidXmlLog() { printer.xml("xml>Test") verify(adapter).log(ERROR, null, "Invalid xml") } @Test fun xmlLogNullOrEmpty() { printer.xml(null) printer.xml("") verify(adapter, times(2)).log(DEBUG, null, "Empty/Null xml content") } @Test fun clearLogAdapters() { printer.clearLogAdapters() printer.d("") verifyZeroInteractions(adapter) } @Test fun addAdapter() { printer.clearLogAdapters() val adapter1 = mock(LogAdapter::class.java) val adapter2 = mock(LogAdapter::class.java) printer.addAdapter(adapter1) printer.addAdapter(adapter2) printer.d("message") verify(adapter1).isLoggable(DEBUG, null) verify(adapter2).isLoggable(DEBUG, null) } @Test fun doNotLogIfNotLoggable() { printer.clearLogAdapters() val adapter1 = mock(LogAdapter::class.java) `when`(adapter1.isLoggable(DEBUG, null)).thenReturn(false) val adapter2 = mock(LogAdapter::class.java) `when`(adapter2.isLoggable(DEBUG, null)).thenReturn(true) printer.addAdapter(adapter1) printer.addAdapter(adapter2) printer.d("message") verify(adapter1, never()).log(DEBUG, null, "message") verify(adapter2).log(DEBUG, null, "message") } @Test fun logWithoutMessageAndThrowable() { printer.log(DEBUG, null, null, null) verify(adapter).log(DEBUG, null, "Empty/NULL log message") } @Test fun logWithOnlyThrowableWithoutMessage() { val throwable = Throwable("exception") printer.log(DEBUG, null, null, throwable) verify(adapter).log(eq(DEBUG), isNull(String::class.java), contains("java.lang.Throwable: exception")) } } ================================================ FILE: logger/src/test/java/com.orhanobut.logger/LoggerTest.kt ================================================ package com.orhanobut.logger import org.junit.Before import org.junit.Test import org.mockito.Mock import org.mockito.Mockito.mock import org.mockito.Mockito.verify import org.mockito.Mockito.`when` import org.mockito.MockitoAnnotations.initMocks class LoggerTest { @Mock private lateinit var printer: Printer @Before fun setup() { initMocks(this) Logger.printer(printer) } @Test fun log() { val throwable = Throwable() Logger.log(Logger.VERBOSE, "tag", "message", throwable) verify(printer).log(Logger.VERBOSE, "tag", "message", throwable) } @Test fun debugLog() { Logger.d("message %s", "arg") verify(printer).d("message %s", "arg") } @Test fun verboseLog() { Logger.v("message %s", "arg") verify(printer).v("message %s", "arg") } @Test fun warningLog() { Logger.w("message %s", "arg") verify(printer).w("message %s", "arg") } @Test fun errorLog() { Logger.e("message %s", "arg") verify(printer).e(null as Throwable?, "message %s", "arg") } @Test fun errorLogWithThrowable() { val throwable = Throwable("throwable") Logger.e(throwable, "message %s", "arg") verify(printer).e(throwable, "message %s", "arg") } @Test fun infoLog() { Logger.i("message %s", "arg") verify(printer).i("message %s", "arg") } @Test fun wtfLog() { Logger.wtf("message %s", "arg") verify(printer).wtf("message %s", "arg") } @Test fun logObject() { val `object` = Any() Logger.d(`object`) verify(printer).d(`object`) } @Test fun jsonLog() { Logger.json("json") verify(printer).json("json") } @Test fun xmlLog() { Logger.xml("xml") verify(printer).xml("xml") } @Test fun oneTimeTag() { `when`(printer.t("tag")).thenReturn(printer) Logger.t("tag").d("message") verify(printer).t("tag") verify(printer).d("message") } @Test fun addAdapter() { val adapter = mock(LogAdapter::class.java) Logger.addLogAdapter(adapter) verify(printer).addAdapter(adapter) } @Test fun clearLogAdapters() { Logger.clearLogAdapters() verify(printer).clearLogAdapters() } } ================================================ FILE: logger/src/test/java/com.orhanobut.logger/PrettyFormatStrategyTest.kt ================================================ package com.orhanobut.logger import org.junit.Test import java.util.ArrayList import com.orhanobut.logger.Logger.DEBUG class PrettyFormatStrategyTest { private val threadName = Thread.currentThread().name private val logStrategy = MockLogStrategy() private val builder = PrettyFormatStrategy.newBuilder().logStrategy(logStrategy) //TODO: Check the actual method info @Test fun defaultLog() { val formatStrategy = builder.build() formatStrategy.log(DEBUG, null, "message") assertLog(DEBUG) .hasTopBorder() .hasThread(threadName) .hasMiddleBorder() .skip() .skip() .hasMiddleBorder() .hasMessage("message") .hasBottomBorder() .hasNoMoreMessages() } @Test fun logWithoutThreadInfo() { val formatStrategy = builder.showThreadInfo(false).build() formatStrategy.log(DEBUG, null, "message") assertLog(DEBUG) .hasTopBorder() .skip() .skip() .hasMiddleBorder() .hasMessage("message") .hasBottomBorder() .hasNoMoreMessages() } @Test fun logWithoutMethodInfo() { val formatStrategy = builder.methodCount(0).build() formatStrategy.log(DEBUG, null, "message") assertLog(DEBUG) .hasTopBorder() .hasThread(threadName) .hasMiddleBorder() .hasMessage("message") .hasBottomBorder() .hasNoMoreMessages() } @Test fun logWithOnlyMessage() { val formatStrategy = builder .methodCount(0) .showThreadInfo(false) .build() formatStrategy.log(DEBUG, null, "message") assertLog(DEBUG) .hasTopBorder() .hasMessage("message") .hasBottomBorder() .hasNoMoreMessages() } //TODO: Check the actual method info @Test fun logWithCustomMethodOffset() { val formatStrategy = builder .methodOffset(2) .showThreadInfo(false) .build() formatStrategy.log(DEBUG, null, "message") assertLog(DEBUG) .hasTopBorder() .skip() .skip() .hasMiddleBorder() .hasMessage("message") .hasBottomBorder() .hasNoMoreMessages() } @Test fun logWithCustomTag() { val formatStrategy = builder .tag("custom") .build() formatStrategy.log(DEBUG, null, "message") assertLog("custom", DEBUG) .hasTopBorder() .hasThread(threadName) .hasMiddleBorder() .skip() .skip() .hasMiddleBorder() .hasMessage("message") .hasBottomBorder() .hasNoMoreMessages() } @Test fun logWithOneTimeTag() { val formatStrategy = builder .tag("custom") .build() formatStrategy.log(DEBUG, "tag", "message") assertLog("custom-tag", DEBUG) .hasTopBorder() .hasThread(threadName) .hasMiddleBorder() .skip() .skip() .hasMiddleBorder() .hasMessage("message") .hasBottomBorder() .hasNoMoreMessages() } // TODO: assert values, for now this checks that Logger doesn't crash @Test fun logWithExceedingMethodCount() { val formatStrategy = builder .methodCount(50) .build() formatStrategy.log(DEBUG, null, "message") } @Test fun logWithBigChunk() { val formatStrategy = builder.build() val chunk1 = StringBuilder() for (i in 0..399) { chunk1.append("1234567890") } val chunk2 = StringBuilder() for (i in 0..9) { chunk2.append("ABCDEFGD") } formatStrategy.log(DEBUG, null, chunk1.toString() + chunk2.toString()) assertLog(DEBUG) .hasTopBorder() .hasThread(threadName) .hasMiddleBorder() .skip() .skip() .hasMiddleBorder() .hasMessage(chunk1.toString()) .hasMessage(chunk2.toString()) .hasBottomBorder() .hasNoMoreMessages() } private class MockLogStrategy : LogStrategy { internal var logItems: MutableList = ArrayList() override fun log(priority: Int, tag: String?, message: String) { logItems.add(LogAssert.LogItem(priority, tag ?: "", message)) } } private fun assertLog(priority: Int): LogAssert { return assertLog(null, priority) } private fun assertLog(tag: String?, priority: Int): LogAssert { return LogAssert(logStrategy.logItems, tag, priority) } } ================================================ FILE: logger/src/test/java/com.orhanobut.logger/UtilsTest.kt ================================================ package com.orhanobut.logger import android.util.Log import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config import java.net.UnknownHostException import com.google.common.truth.Truth.assertThat @RunWith(RobolectricTestRunner::class) class UtilsTest { @Test fun isEmpty() { assertThat(Utils.isEmpty("")).isTrue() assertThat(Utils.isEmpty(null)).isTrue() } @Test fun equals() { assertThat(Utils.equals("a", "a")).isTrue() assertThat(Utils.equals("as", "b")).isFalse() assertThat(Utils.equals(null, "b")).isFalse() assertThat(Utils.equals("a", null)).isFalse() } @Test fun getStackTraceString() { val throwable = Throwable("test") val androidTraceString = Log.getStackTraceString(throwable) assertThat(Utils.getStackTraceString(throwable)).isEqualTo(androidTraceString) } @Test fun getStackTraceStringReturnsEmptyStringWithNull() { assertThat(Utils.getStackTraceString(null)).isEqualTo("") } @Test fun getStackTraceStringReturnEmptyStringWithUnknownHostException() { assertThat(Utils.getStackTraceString(UnknownHostException())).isEqualTo("") } @Test fun logLevels() { assertThat(Utils.logLevel(Logger.DEBUG)).isEqualTo("DEBUG") assertThat(Utils.logLevel(Logger.WARN)).isEqualTo("WARN") assertThat(Utils.logLevel(Logger.INFO)).isEqualTo("INFO") assertThat(Utils.logLevel(Logger.VERBOSE)).isEqualTo("VERBOSE") assertThat(Utils.logLevel(Logger.ASSERT)).isEqualTo("ASSERT") assertThat(Utils.logLevel(Logger.ERROR)).isEqualTo("ERROR") assertThat(Utils.logLevel(100)).isEqualTo("UNKNOWN") } @Test fun objectToString() { val `object` = "Test" assertThat(Utils.toString(`object`)).isEqualTo("Test") } @Test fun toStringWithNull() { assertThat(Utils.toString(null)).isEqualTo("null") } @Test fun primitiveArrayToString() { val booleanArray = booleanArrayOf(true, false, true) assertThat(Utils.toString(booleanArray)).isEqualTo("[true, false, true]") val byteArray = byteArrayOf(1, 0, 1) assertThat(Utils.toString(byteArray)).isEqualTo("[1, 0, 1]") val charArray = charArrayOf('a', 'b', 'c') assertThat(Utils.toString(charArray)).isEqualTo("[a, b, c]") val shortArray = shortArrayOf(1, 3, 5) assertThat(Utils.toString(shortArray)).isEqualTo("[1, 3, 5]") val intArray = intArrayOf(1, 3, 5) assertThat(Utils.toString(intArray)).isEqualTo("[1, 3, 5]") val longArray = longArrayOf(1, 3, 5) assertThat(Utils.toString(longArray)).isEqualTo("[1, 3, 5]") val floatArray = floatArrayOf(1f, 3f, 5f) assertThat(Utils.toString(floatArray)).isEqualTo("[1.0, 3.0, 5.0]") val doubleArray = doubleArrayOf(1.0, 3.0, 5.0) assertThat(Utils.toString(doubleArray)).isEqualTo("[1.0, 3.0, 5.0]") } @Test fun multiDimensionArrayToString() { val `object` = arrayOf(intArrayOf(1, 2, 3), intArrayOf(4, 5, 6)) assertThat(Utils.toString(`object`)).isEqualTo("[[1, 2, 3], [4, 5, 6]]") } } ================================================ FILE: sample/build.gradle ================================================ apply plugin: 'com.android.application' android { compileSdkVersion rootProject.ext.compileSdkVersion buildToolsVersion rootProject.ext.buildToolsVersion defaultConfig { applicationId "com.orhanobut.sample" minSdkVersion 23 targetSdkVersion 27 versionCode 1 versionName "1.0" testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner' } } dependencies { implementation project(":logger") } ================================================ FILE: sample/src/main/AndroidManifest.xml ================================================ ================================================ FILE: sample/src/main/java/com/orhanobut/sample/MainActivity.java ================================================ package com.orhanobut.sample; import android.app.Activity; import android.os.Bundle; import android.util.Log; import com.orhanobut.logger.AndroidLogAdapter; import com.orhanobut.logger.DiskLogAdapter; import com.orhanobut.logger.FormatStrategy; import com.orhanobut.logger.Logger; import com.orhanobut.logger.PrettyFormatStrategy; import java.util.Arrays; import java.util.HashMap; import java.util.Map; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.d("Tag", "I'm a log which you don't see easily, hehe"); Log.d("json content", "{ \"key\": 3, \n \"value\": something}"); Log.d("error", "There is a crash somewhere or any warning"); Logger.addLogAdapter(new AndroidLogAdapter()); Logger.d("message"); Logger.clearLogAdapters(); FormatStrategy formatStrategy = PrettyFormatStrategy.newBuilder() .showThreadInfo(false) // (Optional) Whether to show thread info or not. Default true .methodCount(0) // (Optional) How many method line to show. Default 2 .methodOffset(3) // (Optional) Skips some method invokes in stack trace. Default 5 // .logStrategy(customLog) // (Optional) Changes the log strategy to print out. Default LogCat .tag("My custom tag") // (Optional) Custom tag for each log. Default PRETTY_LOGGER .build(); Logger.addLogAdapter(new AndroidLogAdapter(formatStrategy)); Logger.addLogAdapter(new AndroidLogAdapter() { @Override public boolean isLoggable(int priority, String tag) { return BuildConfig.DEBUG; } }); Logger.addLogAdapter(new DiskLogAdapter()); Logger.w("no thread info and only 1 method"); Logger.clearLogAdapters(); formatStrategy = PrettyFormatStrategy.newBuilder() .showThreadInfo(false) .methodCount(0) .build(); Logger.addLogAdapter(new AndroidLogAdapter(formatStrategy)); Logger.i("no thread info and method info"); Logger.t("tag").e("Custom tag for only one use"); Logger.json("{ \"key\": 3, \"value\": something}"); Logger.d(Arrays.asList("foo", "bar")); Map map = new HashMap<>(); map.put("key", "value"); map.put("key1", "value2"); Logger.d(map); Logger.clearLogAdapters(); formatStrategy = PrettyFormatStrategy.newBuilder() .showThreadInfo(false) .methodCount(0) .tag("MyTag") .build(); Logger.addLogAdapter(new AndroidLogAdapter(formatStrategy)); Logger.w("my log message with my tag"); } } ================================================ FILE: sample/src/main/res/layout/activity_main.xml ================================================ ================================================ FILE: settings.gradle ================================================ include ':logger', ':sample'