├── .github └── ISSUE_TEMPLATE.md ├── .gitignore ├── .idea ├── caches │ └── build_file_checksums.ser ├── codeStyles │ ├── Project.xml │ └── codeStyleConfig.xml ├── encodings.xml └── vcs.xml ├── .travis.yml ├── LICENSE ├── README.md ├── art ├── how_it_works.png ├── logcat_options.png ├── logger-logo.png └── logger_output.png ├── build.gradle ├── checkstyle.xml ├── gradle.properties ├── gradle ├── maven_push.gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.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 │ └── mipmap-xxxhdpi │ └── ic_launcher.png └── settings.gradle /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | Please try to fill all questions below before submitting an issue. 2 | 3 | - Android studio version: 4 | - Android gradle plugin version: 5 | - Logger version: 6 | - Emulator/phone information: 7 | - If possible, please add how did you initialize Logger? 8 | - Is it flaky or does it happen all the time? 9 | 10 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | local.properties 2 | 3 | # Generated files 4 | build/ 5 | 6 | # Mac store 7 | .DS_Store 8 | 9 | # Gradle files 10 | .gradle/ 11 | 12 | /captures 13 | 14 | # Log Files 15 | *.log 16 | 17 | # IDEA/Android Studio 18 | *.iml 19 | *.ipr 20 | *.iws 21 | **/.idea/shelf 22 | **/.idea/workspace.xml 23 | **/.idea/tasks.xml 24 | **/.idea/datasources.xml 25 | **/.idea/dataSources.ids 26 | **/.idea/gradle.xml 27 | **/.idea/misc.xml 28 | **/.idea/modules.xml 29 | **/.idea/libraries 30 | **/.idea/dictionaries 31 | **/.idea/runConfigurations.xml 32 | .idea/caches 33 | 34 | # layout inspector view captures 35 | captures 36 | sample/libs/ 37 | -------------------------------------------------------------------------------- /.idea/caches/build_file_checksums.ser: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/orhanobut/logger/c64a72c2ce3d0fcdebe829b091e3a530c94ca6bd/.idea/caches/build_file_checksums.ser -------------------------------------------------------------------------------- /.idea/codeStyles/Project.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 15 | 16 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 34 | 35 | 36 | 44 | 45 | 46 | 50 | 51 | 52 | 60 | 61 | -------------------------------------------------------------------------------- /.idea/codeStyles/codeStyleConfig.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | -------------------------------------------------------------------------------- /.idea/encodings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: android 2 | jdk: oraclejdk8 3 | 4 | android: 5 | components: 6 | - tools 7 | - platform-tools 8 | - build-tools-27.0.3 9 | - android-27 10 | 11 | before_install: 12 | - yes | sdkmanager "platforms;android-27" 13 | 14 | script: 15 | - ./gradlew check 16 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![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) 2 | [![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) 3 | 4 | 5 | 6 | ### Logger 7 | Simple, pretty and powerful logger for android 8 | 9 | ### Setup 10 | Download 11 | ```groovy 12 | implementation 'com.orhanobut:logger:2.2.0' 13 | ``` 14 | 15 | Initialize 16 | ```java 17 | Logger.addLogAdapter(new AndroidLogAdapter()); 18 | ``` 19 | And use 20 | ```java 21 | Logger.d("hello"); 22 | ``` 23 | 24 | ### Output 25 | 26 | 27 | 28 | ### Options 29 | ```java 30 | Logger.d("debug"); 31 | Logger.e("error"); 32 | Logger.w("warning"); 33 | Logger.v("verbose"); 34 | Logger.i("information"); 35 | Logger.wtf("What a Terrible Failure"); 36 | ``` 37 | 38 | String format arguments are supported 39 | ```java 40 | Logger.d("hello %s", "world"); 41 | ``` 42 | 43 | Collections are supported (only available for debug logs) 44 | ```java 45 | Logger.d(MAP); 46 | Logger.d(SET); 47 | Logger.d(LIST); 48 | Logger.d(ARRAY); 49 | ``` 50 | 51 | Json and Xml support (output will be in debug level) 52 | ```java 53 | Logger.json(JSON_CONTENT); 54 | Logger.xml(XML_CONTENT); 55 | ``` 56 | 57 | ### Advanced 58 | ```java 59 | FormatStrategy formatStrategy = PrettyFormatStrategy.newBuilder() 60 | .showThreadInfo(false) // (Optional) Whether to show thread info or not. Default true 61 | .methodCount(0) // (Optional) How many method line to show. Default 2 62 | .methodOffset(7) // (Optional) Hides internal method calls up to offset. Default 5 63 | .logStrategy(customLog) // (Optional) Changes the log strategy to print out. Default LogCat 64 | .tag("My custom tag") // (Optional) Global tag for every log. Default PRETTY_LOGGER 65 | .build(); 66 | 67 | Logger.addLogAdapter(new AndroidLogAdapter(formatStrategy)); 68 | ``` 69 | 70 | ### Loggable 71 | Log adapter checks whether the log should be printed or not by checking this function. 72 | If you want to disable/hide logs for output, override `isLoggable` method. 73 | `true` will print the log message, `false` will ignore it. 74 | ```java 75 | Logger.addLogAdapter(new AndroidLogAdapter() { 76 | @Override public boolean isLoggable(int priority, String tag) { 77 | return BuildConfig.DEBUG; 78 | } 79 | }); 80 | ``` 81 | 82 | ### Save logs to the file 83 | //TODO: More information will be added later 84 | ```java 85 | Logger.addLogAdapter(new DiskLogAdapter()); 86 | ``` 87 | 88 | Add custom tag to Csv format strategy 89 | ```java 90 | FormatStrategy formatStrategy = CsvFormatStrategy.newBuilder() 91 | .tag("custom") 92 | .build(); 93 | 94 | Logger.addLogAdapter(new DiskLogAdapter(formatStrategy)); 95 | ``` 96 | 97 | ### How it works 98 | 99 | 100 | 101 | ### More 102 | - Use filter for a better result. PRETTY_LOGGER or your custom tag 103 | - Make sure that wrap option is disabled 104 | - You can also simplify output by changing settings. 105 | 106 | 107 | 108 | - Timber Integration 109 | ```java 110 | // Set methodOffset to 5 in order to hide internal method calls 111 | Timber.plant(new Timber.DebugTree() { 112 | @Override protected void log(int priority, String tag, String message, Throwable t) { 113 | Logger.log(priority, tag, message, t); 114 | } 115 | }); 116 | ``` 117 | 118 | ### License 119 |
120 | Copyright 2018 Orhan Obut
121 | 
122 | Licensed under the Apache License, Version 2.0 (the "License");
123 | you may not use this file except in compliance with the License.
124 | You may obtain a copy of the License at
125 | 
126 |    http://www.apache.org/licenses/LICENSE-2.0
127 | 
128 | Unless required by applicable law or agreed to in writing, software
129 | distributed under the License is distributed on an "AS IS" BASIS,
130 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
131 | See the License for the specific language governing permissions and
132 | limitations under the License.
133 | 
134 | -------------------------------------------------------------------------------- /art/how_it_works.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/orhanobut/logger/c64a72c2ce3d0fcdebe829b091e3a530c94ca6bd/art/how_it_works.png -------------------------------------------------------------------------------- /art/logcat_options.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/orhanobut/logger/c64a72c2ce3d0fcdebe829b091e3a530c94ca6bd/art/logcat_options.png -------------------------------------------------------------------------------- /art/logger-logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/orhanobut/logger/c64a72c2ce3d0fcdebe829b091e3a530c94ca6bd/art/logger-logo.png -------------------------------------------------------------------------------- /art/logger_output.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/orhanobut/logger/c64a72c2ce3d0fcdebe829b091e3a530c94ca6bd/art/logger_output.png -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | ext.kotlinVersion = '1.2.51' 3 | repositories { 4 | google() 5 | jcenter() 6 | } 7 | dependencies { 8 | classpath 'com.android.tools.build:gradle:3.2.0' 9 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion" 10 | } 11 | } 12 | 13 | allprojects { 14 | repositories { 15 | google() 16 | jcenter() 17 | } 18 | } 19 | 20 | subprojects { project -> 21 | group = GROUP 22 | version = VERSION_NAME 23 | 24 | apply plugin: 'checkstyle' 25 | 26 | task checkstyle(type: Checkstyle) { 27 | configFile rootProject.file('checkstyle.xml') 28 | source 'src/main/java' 29 | ignoreFailures false 30 | showViolations true 31 | include '**/*.java' 32 | 33 | classpath = files() 34 | } 35 | 36 | afterEvaluate { 37 | if (project.tasks.findByName('check')) { 38 | check.dependsOn('checkstyle') 39 | } 40 | } 41 | } 42 | 43 | task clean(type: Delete) { 44 | delete rootProject.buildDir 45 | } 46 | 47 | ext { 48 | minSdkVersion = 8 49 | targetSdkVersion = 28 50 | compileSdkVersion = 28 51 | buildToolsVersion = '28.0.2' 52 | } 53 | 54 | ext.deps = [ 55 | junit : 'junit:junit:4.12', 56 | truth : 'com.google.truth:truth:0.28', 57 | robolectric : 'org.robolectric:robolectric:3.3', 58 | mockito : "org.mockito:mockito-core:2.8.9", 59 | json : "org.json:json:20160810", 60 | supportAnnotations: 'androidx.annotation:annotation:1.0.0', 61 | kotlin : "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlinVersion" 62 | ] -------------------------------------------------------------------------------- /checkstyle.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | VERSION_NAME=2.2.0 2 | GROUP=com.orhanobut 3 | 4 | POM_DESCRIPTION=Simple, Pretty and Advanced Logger 5 | POM_URL=https://github.com/orhanobut/logger 6 | POM_SCM_URL=https://github.com/orhanobut/logger 7 | POM_SCM_CONNECTION=scm:git@https://github.com/orhanobut/logger.git 8 | POM_SCM_DEV_CONNECTION=scm:git@https://github.com/orhanobut/logger.git 9 | POM_LICENCE_NAME=The Apache Software License, Version 2.0 10 | POM_LICENCE_URL=http://www.apache.org/licenses/LICENSE-2.0.txt 11 | POM_LICENCE_DIST=repo 12 | POM_DEVELOPER_ID=nr4bt 13 | POM_DEVELOPER_NAME=Orhan Obut 14 | android.useAndroidX=true 15 | android.enableJetifier=true -------------------------------------------------------------------------------- /gradle/maven_push.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'maven' 2 | apply plugin: 'signing' 3 | 4 | version = VERSION_NAME 5 | group = GROUP 6 | 7 | def isReleaseBuild() { 8 | return version.contains("SNAPSHOT") == false 9 | } 10 | 11 | def sonatypeRepositoryUrl 12 | if (isReleaseBuild()) { 13 | println 'RELEASE BUILD' 14 | sonatypeRepositoryUrl = hasProperty('RELEASE_REPOSITORY_URL') ? RELEASE_REPOSITORY_URL 15 | : "https://oss.sonatype.org/service/local/staging/deploy/maven2/" 16 | } else { 17 | println 'DEBUG BUILD' 18 | sonatypeRepositoryUrl = hasProperty('SNAPSHOT_REPOSITORY_URL') ? SNAPSHOT_REPOSITORY_URL 19 | : "https://oss.sonatype.org/content/repositories/snapshots/" 20 | } 21 | 22 | afterEvaluate { project -> 23 | uploadArchives { 24 | repositories { 25 | mavenDeployer { 26 | beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) } 27 | pom.artifactId = POM_ARTIFACT_ID 28 | repository(url: sonatypeRepositoryUrl) { 29 | try { 30 | authentication(userName: NEXUS_USERNAME, password: NEXUS_PASSWORD) 31 | } catch (Exception ignored) { 32 | println "mavenUser or mavenPassword is missing" 33 | } 34 | } 35 | pom.project { 36 | name POM_NAME 37 | packaging POM_PACKAGING 38 | description POM_DESCRIPTION 39 | url POM_URL 40 | scm { 41 | url POM_SCM_URL 42 | connection POM_SCM_CONNECTION 43 | developerConnection POM_SCM_DEV_CONNECTION 44 | } 45 | licenses { 46 | license { 47 | name POM_LICENCE_NAME 48 | url POM_LICENCE_URL 49 | distribution POM_LICENCE_DIST 50 | } 51 | } 52 | developers { 53 | developer { 54 | id POM_DEVELOPER_ID 55 | name POM_DEVELOPER_NAME 56 | } 57 | } 58 | } 59 | } 60 | } 61 | } 62 | signing { 63 | required { isReleaseBuild() && gradle.taskGraph.hasTask("uploadArchives") } 64 | sign configurations.archives 65 | } 66 | task androidJavadocs(type: Javadoc) { 67 | source = android.sourceSets.main.java.sourceFiles 68 | } 69 | task androidJavadocsJar(type: Jar) { 70 | classifier = 'javadoc' 71 | from androidJavadocs.destinationDir 72 | } 73 | task androidSourcesJar(type: Jar) { 74 | classifier = 'sources' 75 | from android.sourceSets.main.java.sourceFiles 76 | } 77 | artifacts { 78 | archives androidSourcesJar 79 | archives androidJavadocsJar 80 | } 81 | } 82 | 83 | // build a jar with source files 84 | task sourcesJar(type: Jar) { 85 | from android.sourceSets.main.java.srcDirs 86 | classifier = 'sources' 87 | } 88 | 89 | task javadoc(type: Javadoc) { 90 | failOnError false 91 | source = android.sourceSets.main.java.sourceFiles 92 | classpath += project.files(android.getBootClasspath().join(File.pathSeparator)) 93 | } 94 | 95 | // build a jar with javadoc 96 | task javadocJar(type: Jar, dependsOn: javadoc) { 97 | classifier = 'javadoc' 98 | from javadoc.destinationDir 99 | } -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/orhanobut/logger/c64a72c2ce3d0fcdebe829b091e3a530c94ca6bd/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-4.6-all.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /logger/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | apply plugin: 'kotlin-android' 3 | 4 | android { 5 | compileSdkVersion rootProject.ext.compileSdkVersion 6 | buildToolsVersion rootProject.ext.buildToolsVersion 7 | 8 | defaultConfig { 9 | minSdkVersion rootProject.ext.minSdkVersion 10 | } 11 | 12 | lintOptions { 13 | textReport true 14 | textOutput 'stdout' 15 | } 16 | 17 | testOptions { 18 | unitTests.returnDefaultValues = true 19 | } 20 | } 21 | 22 | dependencies { 23 | implementation deps.supportAnnotations 24 | 25 | testImplementation deps.junit 26 | testImplementation deps.truth 27 | testImplementation deps.robolectric 28 | testImplementation deps.mockito 29 | testImplementation deps.json 30 | testImplementation deps.kotlin 31 | } 32 | 33 | apply from: rootProject.file('gradle/maven_push.gradle') 34 | -------------------------------------------------------------------------------- /logger/gradle.properties: -------------------------------------------------------------------------------- 1 | POM_NAME=Logger 2 | POM_ARTIFACT_ID=logger 3 | POM_PACKAGING=aar -------------------------------------------------------------------------------- /logger/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /logger/src/main/java/com/orhanobut/logger/AndroidLogAdapter.java: -------------------------------------------------------------------------------- 1 | package com.orhanobut.logger; 2 | 3 | import androidx.annotation.NonNull; 4 | import androidx.annotation.Nullable; 5 | 6 | import static com.orhanobut.logger.Utils.checkNotNull; 7 | 8 | /** 9 | * Android terminal log output implementation for {@link LogAdapter}. 10 | * 11 | * Prints output to LogCat with pretty borders. 12 | * 13 | *
14 |  *  ┌──────────────────────────
15 |  *  │ Method stack history
16 |  *  ├┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
17 |  *  │ Log message
18 |  *  └──────────────────────────
19 |  * 
20 | */ 21 | public class AndroidLogAdapter implements LogAdapter { 22 | 23 | @NonNull private final FormatStrategy formatStrategy; 24 | 25 | public AndroidLogAdapter() { 26 | this.formatStrategy = PrettyFormatStrategy.newBuilder().build(); 27 | } 28 | 29 | public AndroidLogAdapter(@NonNull FormatStrategy formatStrategy) { 30 | this.formatStrategy = checkNotNull(formatStrategy); 31 | } 32 | 33 | @Override public boolean isLoggable(int priority, @Nullable String tag) { 34 | return true; 35 | } 36 | 37 | @Override public void log(int priority, @Nullable String tag, @NonNull String message) { 38 | formatStrategy.log(priority, tag, message); 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /logger/src/main/java/com/orhanobut/logger/CsvFormatStrategy.java: -------------------------------------------------------------------------------- 1 | package com.orhanobut.logger; 2 | 3 | import android.os.Environment; 4 | import android.os.Handler; 5 | import android.os.HandlerThread; 6 | import androidx.annotation.NonNull; 7 | import androidx.annotation.Nullable; 8 | 9 | import java.io.File; 10 | import java.text.SimpleDateFormat; 11 | import java.util.Date; 12 | import java.util.Locale; 13 | 14 | import static com.orhanobut.logger.Utils.checkNotNull; 15 | 16 | /** 17 | * CSV formatted file logging for Android. 18 | * Writes to CSV the following data: 19 | * epoch timestamp, ISO8601 timestamp (human-readable), log level, tag, log message. 20 | */ 21 | public class CsvFormatStrategy implements FormatStrategy { 22 | 23 | private static final String NEW_LINE = System.getProperty("line.separator"); 24 | private static final String NEW_LINE_REPLACEMENT = "
"; 25 | private static final String SEPARATOR = ","; 26 | 27 | @NonNull private final Date date; 28 | @NonNull private final SimpleDateFormat dateFormat; 29 | @NonNull private final LogStrategy logStrategy; 30 | @Nullable private final String tag; 31 | 32 | private CsvFormatStrategy(@NonNull Builder builder) { 33 | checkNotNull(builder); 34 | 35 | date = builder.date; 36 | dateFormat = builder.dateFormat; 37 | logStrategy = builder.logStrategy; 38 | tag = builder.tag; 39 | } 40 | 41 | @NonNull public static Builder newBuilder() { 42 | return new Builder(); 43 | } 44 | 45 | @Override public void log(int priority, @Nullable String onceOnlyTag, @NonNull String message) { 46 | checkNotNull(message); 47 | 48 | String tag = formatTag(onceOnlyTag); 49 | 50 | date.setTime(System.currentTimeMillis()); 51 | 52 | StringBuilder builder = new StringBuilder(); 53 | 54 | // machine-readable date/time 55 | builder.append(Long.toString(date.getTime())); 56 | 57 | // human-readable date/time 58 | builder.append(SEPARATOR); 59 | builder.append(dateFormat.format(date)); 60 | 61 | // level 62 | builder.append(SEPARATOR); 63 | builder.append(Utils.logLevel(priority)); 64 | 65 | // tag 66 | builder.append(SEPARATOR); 67 | builder.append(tag); 68 | 69 | // message 70 | if (message.contains(NEW_LINE)) { 71 | // a new line would break the CSV format, so we replace it here 72 | message = message.replaceAll(NEW_LINE, NEW_LINE_REPLACEMENT); 73 | } 74 | builder.append(SEPARATOR); 75 | builder.append(message); 76 | 77 | // new line 78 | builder.append(NEW_LINE); 79 | 80 | logStrategy.log(priority, tag, builder.toString()); 81 | } 82 | 83 | @Nullable private String formatTag(@Nullable String tag) { 84 | if (!Utils.isEmpty(tag) && !Utils.equals(this.tag, tag)) { 85 | return this.tag + "-" + tag; 86 | } 87 | return this.tag; 88 | } 89 | 90 | public static final class Builder { 91 | private static final int MAX_BYTES = 500 * 1024; // 500K averages to a 4000 lines per file 92 | 93 | Date date; 94 | SimpleDateFormat dateFormat; 95 | LogStrategy logStrategy; 96 | String tag = "PRETTY_LOGGER"; 97 | 98 | private Builder() { 99 | } 100 | 101 | @NonNull public Builder date(@Nullable Date val) { 102 | date = val; 103 | return this; 104 | } 105 | 106 | @NonNull public Builder dateFormat(@Nullable SimpleDateFormat val) { 107 | dateFormat = val; 108 | return this; 109 | } 110 | 111 | @NonNull public Builder logStrategy(@Nullable LogStrategy val) { 112 | logStrategy = val; 113 | return this; 114 | } 115 | 116 | @NonNull public Builder tag(@Nullable String tag) { 117 | this.tag = tag; 118 | return this; 119 | } 120 | 121 | @NonNull public CsvFormatStrategy build() { 122 | if (date == null) { 123 | date = new Date(); 124 | } 125 | if (dateFormat == null) { 126 | dateFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss.SSS", Locale.UK); 127 | } 128 | if (logStrategy == null) { 129 | String diskPath = Environment.getExternalStorageDirectory().getAbsolutePath(); 130 | String folder = diskPath + File.separatorChar + "logger"; 131 | 132 | HandlerThread ht = new HandlerThread("AndroidFileLogger." + folder); 133 | ht.start(); 134 | Handler handler = new DiskLogStrategy.WriteHandler(ht.getLooper(), folder, MAX_BYTES); 135 | logStrategy = new DiskLogStrategy(handler); 136 | } 137 | return new CsvFormatStrategy(this); 138 | } 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /logger/src/main/java/com/orhanobut/logger/DiskLogAdapter.java: -------------------------------------------------------------------------------- 1 | package com.orhanobut.logger; 2 | 3 | import androidx.annotation.NonNull; 4 | import androidx.annotation.Nullable; 5 | 6 | import static com.orhanobut.logger.Utils.checkNotNull; 7 | 8 | /** 9 | * This is used to saves log messages to the disk. 10 | * By default it uses {@link CsvFormatStrategy} to translates text message into CSV format. 11 | */ 12 | public class DiskLogAdapter implements LogAdapter { 13 | 14 | @NonNull private final FormatStrategy formatStrategy; 15 | 16 | public DiskLogAdapter() { 17 | formatStrategy = CsvFormatStrategy.newBuilder().build(); 18 | } 19 | 20 | public DiskLogAdapter(@NonNull FormatStrategy formatStrategy) { 21 | this.formatStrategy = checkNotNull(formatStrategy); 22 | } 23 | 24 | @Override public boolean isLoggable(int priority, @Nullable String tag) { 25 | return true; 26 | } 27 | 28 | @Override public void log(int priority, @Nullable String tag, @NonNull String message) { 29 | formatStrategy.log(priority, tag, message); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /logger/src/main/java/com/orhanobut/logger/DiskLogStrategy.java: -------------------------------------------------------------------------------- 1 | package com.orhanobut.logger; 2 | 3 | import android.os.Handler; 4 | import android.os.Looper; 5 | import android.os.Message; 6 | import androidx.annotation.NonNull; 7 | import androidx.annotation.Nullable; 8 | 9 | import java.io.File; 10 | import java.io.FileWriter; 11 | import java.io.IOException; 12 | 13 | import static com.orhanobut.logger.Utils.checkNotNull; 14 | 15 | /** 16 | * Abstract class that takes care of background threading the file log operation on Android. 17 | * implementing classes are free to directly perform I/O operations there. 18 | * 19 | * Writes all logs to the disk with CSV format. 20 | */ 21 | public class DiskLogStrategy implements LogStrategy { 22 | 23 | @NonNull private final Handler handler; 24 | 25 | public DiskLogStrategy(@NonNull Handler handler) { 26 | this.handler = checkNotNull(handler); 27 | } 28 | 29 | @Override public void log(int level, @Nullable String tag, @NonNull String message) { 30 | checkNotNull(message); 31 | 32 | // do nothing on the calling thread, simply pass the tag/msg to the background thread 33 | handler.sendMessage(handler.obtainMessage(level, message)); 34 | } 35 | 36 | static class WriteHandler extends Handler { 37 | 38 | @NonNull private final String folder; 39 | private final int maxFileSize; 40 | 41 | WriteHandler(@NonNull Looper looper, @NonNull String folder, int maxFileSize) { 42 | super(checkNotNull(looper)); 43 | this.folder = checkNotNull(folder); 44 | this.maxFileSize = maxFileSize; 45 | } 46 | 47 | @SuppressWarnings("checkstyle:emptyblock") 48 | @Override public void handleMessage(@NonNull Message msg) { 49 | String content = (String) msg.obj; 50 | 51 | FileWriter fileWriter = null; 52 | File logFile = getLogFile(folder, "logs"); 53 | 54 | try { 55 | fileWriter = new FileWriter(logFile, true); 56 | 57 | writeLog(fileWriter, content); 58 | 59 | fileWriter.flush(); 60 | fileWriter.close(); 61 | } catch (IOException e) { 62 | if (fileWriter != null) { 63 | try { 64 | fileWriter.flush(); 65 | fileWriter.close(); 66 | } catch (IOException e1) { /* fail silently */ } 67 | } 68 | } 69 | } 70 | 71 | /** 72 | * This is always called on a single background thread. 73 | * Implementing classes must ONLY write to the fileWriter and nothing more. 74 | * The abstract class takes care of everything else including close the stream and catching IOException 75 | * 76 | * @param fileWriter an instance of FileWriter already initialised to the correct file 77 | */ 78 | private void writeLog(@NonNull FileWriter fileWriter, @NonNull String content) throws IOException { 79 | checkNotNull(fileWriter); 80 | checkNotNull(content); 81 | 82 | fileWriter.append(content); 83 | } 84 | 85 | private File getLogFile(@NonNull String folderName, @NonNull String fileName) { 86 | checkNotNull(folderName); 87 | checkNotNull(fileName); 88 | 89 | File folder = new File(folderName); 90 | if (!folder.exists()) { 91 | //TODO: What if folder is not created, what happens then? 92 | folder.mkdirs(); 93 | } 94 | 95 | int newFileCount = 0; 96 | File newFile; 97 | File existingFile = null; 98 | 99 | newFile = new File(folder, String.format("%s_%s.csv", fileName, newFileCount)); 100 | while (newFile.exists()) { 101 | existingFile = newFile; 102 | newFileCount++; 103 | newFile = new File(folder, String.format("%s_%s.csv", fileName, newFileCount)); 104 | } 105 | 106 | if (existingFile != null) { 107 | if (existingFile.length() >= maxFileSize) { 108 | return newFile; 109 | } 110 | return existingFile; 111 | } 112 | 113 | return newFile; 114 | } 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /logger/src/main/java/com/orhanobut/logger/FormatStrategy.java: -------------------------------------------------------------------------------- 1 | package com.orhanobut.logger; 2 | 3 | import androidx.annotation.NonNull; 4 | import androidx.annotation.Nullable; 5 | 6 | /** 7 | * Used to determine how messages should be printed or saved. 8 | * 9 | * @see PrettyFormatStrategy 10 | * @see CsvFormatStrategy 11 | */ 12 | public interface FormatStrategy { 13 | 14 | void log(int priority, @Nullable String tag, @NonNull String message); 15 | } 16 | -------------------------------------------------------------------------------- /logger/src/main/java/com/orhanobut/logger/LogAdapter.java: -------------------------------------------------------------------------------- 1 | package com.orhanobut.logger; 2 | 3 | import androidx.annotation.NonNull; 4 | import androidx.annotation.Nullable; 5 | 6 | /** 7 | * Provides a common interface to emits logs through. This is a required contract for Logger. 8 | * 9 | * @see AndroidLogAdapter 10 | * @see DiskLogAdapter 11 | */ 12 | public interface LogAdapter { 13 | 14 | /** 15 | * Used to determine whether log should be printed out or not. 16 | * 17 | * @param priority is the log level e.g. DEBUG, WARNING 18 | * @param tag is the given tag for the log message 19 | * 20 | * @return is used to determine if log should printed. 21 | * If it is true, it will be printed, otherwise it'll be ignored. 22 | */ 23 | boolean isLoggable(int priority, @Nullable String tag); 24 | 25 | /** 26 | * Each log will use this pipeline 27 | * 28 | * @param priority is the log level e.g. DEBUG, WARNING 29 | * @param tag is the given tag for the log message. 30 | * @param message is the given message for the log message. 31 | */ 32 | void log(int priority, @Nullable String tag, @NonNull String message); 33 | } -------------------------------------------------------------------------------- /logger/src/main/java/com/orhanobut/logger/LogStrategy.java: -------------------------------------------------------------------------------- 1 | package com.orhanobut.logger; 2 | 3 | import androidx.annotation.NonNull; 4 | import androidx.annotation.Nullable; 5 | 6 | /** 7 | * Determines destination target for the logs such as Disk, Logcat etc. 8 | * 9 | * @see LogcatLogStrategy 10 | * @see DiskLogStrategy 11 | */ 12 | public interface LogStrategy { 13 | 14 | /** 15 | * This is invoked by Logger each time a log message is processed. 16 | * Interpret this method as last destination of the log in whole pipeline. 17 | * 18 | * @param priority is the log level e.g. DEBUG, WARNING 19 | * @param tag is the given tag for the log message. 20 | * @param message is the given message for the log message. 21 | */ 22 | void log(int priority, @Nullable String tag, @NonNull String message); 23 | } 24 | -------------------------------------------------------------------------------- /logger/src/main/java/com/orhanobut/logger/LogcatLogStrategy.java: -------------------------------------------------------------------------------- 1 | package com.orhanobut.logger; 2 | 3 | import androidx.annotation.NonNull; 4 | import androidx.annotation.Nullable; 5 | import android.util.Log; 6 | 7 | import static com.orhanobut.logger.Utils.checkNotNull; 8 | 9 | /** 10 | * LogCat implementation for {@link LogStrategy} 11 | * 12 | * This simply prints out all logs to Logcat by using standard {@link Log} class. 13 | */ 14 | public class LogcatLogStrategy implements LogStrategy { 15 | 16 | static final String DEFAULT_TAG = "NO_TAG"; 17 | 18 | @Override public void log(int priority, @Nullable String tag, @NonNull String message) { 19 | checkNotNull(message); 20 | 21 | if (tag == null) { 22 | tag = DEFAULT_TAG; 23 | } 24 | 25 | Log.println(priority, tag, message); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /logger/src/main/java/com/orhanobut/logger/Logger.java: -------------------------------------------------------------------------------- 1 | package com.orhanobut.logger; 2 | 3 | import androidx.annotation.NonNull; 4 | import androidx.annotation.Nullable; 5 | 6 | import static com.orhanobut.logger.Utils.checkNotNull; 7 | 8 | /** 9 | *
 10 |  *  ┌────────────────────────────────────────────
 11 |  *  │ LOGGER
 12 |  *  ├┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
 13 |  *  │ Standard logging mechanism
 14 |  *  ├┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
 15 |  *  │ But more pretty, simple and powerful
 16 |  *  └────────────────────────────────────────────
 17 |  * 
18 | * 19 | *

How to use it

20 | * Initialize it first 21 | *

 22 |  *   Logger.addLogAdapter(new AndroidLogAdapter());
 23 |  * 
24 | * 25 | * And use the appropriate static Logger methods. 26 | * 27 | *

 28 |  *   Logger.d("debug");
 29 |  *   Logger.e("error");
 30 |  *   Logger.w("warning");
 31 |  *   Logger.v("verbose");
 32 |  *   Logger.i("information");
 33 |  *   Logger.wtf("What a Terrible Failure");
 34 |  * 
35 | * 36 | *

String format arguments are supported

37 | *

 38 |  *   Logger.d("hello %s", "world");
 39 |  * 
40 | * 41 | *

Collections are support ed(only available for debug logs)

42 | *

 43 |  *   Logger.d(MAP);
 44 |  *   Logger.d(SET);
 45 |  *   Logger.d(LIST);
 46 |  *   Logger.d(ARRAY);
 47 |  * 
48 | * 49 | *

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

50 | *

 51 |  *   Logger.json(JSON_CONTENT);
 52 |  *   Logger.xml(XML_CONTENT);
 53 |  * 
54 | * 55 | *

Customize Logger

56 | * Based on your needs, you can change the following settings: 57 | *
    58 | *
  • Different {@link LogAdapter}
  • 59 | *
  • Different {@link FormatStrategy}
  • 60 | *
  • Different {@link LogStrategy}
  • 61 | *
62 | * 63 | * @see LogAdapter 64 | * @see FormatStrategy 65 | * @see LogStrategy 66 | */ 67 | public final class Logger { 68 | 69 | public static final int VERBOSE = 2; 70 | public static final int DEBUG = 3; 71 | public static final int INFO = 4; 72 | public static final int WARN = 5; 73 | public static final int ERROR = 6; 74 | public static final int ASSERT = 7; 75 | 76 | @NonNull private static Printer printer = new LoggerPrinter(); 77 | 78 | private Logger() { 79 | //no instance 80 | } 81 | 82 | public static void printer(@NonNull Printer printer) { 83 | Logger.printer = checkNotNull(printer); 84 | } 85 | 86 | public static void addLogAdapter(@NonNull LogAdapter adapter) { 87 | printer.addAdapter(checkNotNull(adapter)); 88 | } 89 | 90 | public static void clearLogAdapters() { 91 | printer.clearLogAdapters(); 92 | } 93 | 94 | /** 95 | * Given tag will be used as tag only once for this method call regardless of the tag that's been 96 | * set during initialization. After this invocation, the general tag that's been set will 97 | * be used for the subsequent log calls 98 | */ 99 | public static Printer t(@Nullable String tag) { 100 | return printer.t(tag); 101 | } 102 | 103 | /** 104 | * General log function that accepts all configurations as parameter 105 | */ 106 | public static void log(int priority, @Nullable String tag, @Nullable String message, @Nullable Throwable throwable) { 107 | printer.log(priority, tag, message, throwable); 108 | } 109 | 110 | public static void d(@NonNull String message, @Nullable Object... args) { 111 | printer.d(message, args); 112 | } 113 | 114 | public static void d(@Nullable Object object) { 115 | printer.d(object); 116 | } 117 | 118 | public static void e(@NonNull String message, @Nullable Object... args) { 119 | printer.e(null, message, args); 120 | } 121 | 122 | public static void e(@Nullable Throwable throwable, @NonNull String message, @Nullable Object... args) { 123 | printer.e(throwable, message, args); 124 | } 125 | 126 | public static void i(@NonNull String message, @Nullable Object... args) { 127 | printer.i(message, args); 128 | } 129 | 130 | public static void v(@NonNull String message, @Nullable Object... args) { 131 | printer.v(message, args); 132 | } 133 | 134 | public static void w(@NonNull String message, @Nullable Object... args) { 135 | printer.w(message, args); 136 | } 137 | 138 | /** 139 | * Tip: Use this for exceptional situations to log 140 | * ie: Unexpected errors etc 141 | */ 142 | public static void wtf(@NonNull String message, @Nullable Object... args) { 143 | printer.wtf(message, args); 144 | } 145 | 146 | /** 147 | * Formats the given json content and print it 148 | */ 149 | public static void json(@Nullable String json) { 150 | printer.json(json); 151 | } 152 | 153 | /** 154 | * Formats the given xml content and print it 155 | */ 156 | public static void xml(@Nullable String xml) { 157 | printer.xml(xml); 158 | } 159 | 160 | } 161 | -------------------------------------------------------------------------------- /logger/src/main/java/com/orhanobut/logger/LoggerPrinter.java: -------------------------------------------------------------------------------- 1 | package com.orhanobut.logger; 2 | 3 | import androidx.annotation.NonNull; 4 | import androidx.annotation.Nullable; 5 | 6 | import org.json.JSONArray; 7 | import org.json.JSONException; 8 | import org.json.JSONObject; 9 | 10 | import java.io.StringReader; 11 | import java.io.StringWriter; 12 | import java.util.ArrayList; 13 | import java.util.List; 14 | 15 | import javax.xml.transform.OutputKeys; 16 | import javax.xml.transform.Source; 17 | import javax.xml.transform.Transformer; 18 | import javax.xml.transform.TransformerException; 19 | import javax.xml.transform.TransformerFactory; 20 | import javax.xml.transform.stream.StreamResult; 21 | import javax.xml.transform.stream.StreamSource; 22 | 23 | import static com.orhanobut.logger.Logger.ASSERT; 24 | import static com.orhanobut.logger.Logger.DEBUG; 25 | import static com.orhanobut.logger.Logger.ERROR; 26 | import static com.orhanobut.logger.Logger.INFO; 27 | import static com.orhanobut.logger.Logger.VERBOSE; 28 | import static com.orhanobut.logger.Logger.WARN; 29 | import static com.orhanobut.logger.Utils.checkNotNull; 30 | 31 | class LoggerPrinter implements Printer { 32 | 33 | /** 34 | * It is used for json pretty print 35 | */ 36 | private static final int JSON_INDENT = 2; 37 | 38 | /** 39 | * Provides one-time used tag for the log message 40 | */ 41 | private final ThreadLocal localTag = new ThreadLocal<>(); 42 | 43 | private final List logAdapters = new ArrayList<>(); 44 | 45 | @Override public Printer t(String tag) { 46 | if (tag != null) { 47 | localTag.set(tag); 48 | } 49 | return this; 50 | } 51 | 52 | @Override public void d(@NonNull String message, @Nullable Object... args) { 53 | log(DEBUG, null, message, args); 54 | } 55 | 56 | @Override public void d(@Nullable Object object) { 57 | log(DEBUG, null, Utils.toString(object)); 58 | } 59 | 60 | @Override public void e(@NonNull String message, @Nullable Object... args) { 61 | e(null, message, args); 62 | } 63 | 64 | @Override public void e(@Nullable Throwable throwable, @NonNull String message, @Nullable Object... args) { 65 | log(ERROR, throwable, message, args); 66 | } 67 | 68 | @Override public void w(@NonNull String message, @Nullable Object... args) { 69 | log(WARN, null, message, args); 70 | } 71 | 72 | @Override public void i(@NonNull String message, @Nullable Object... args) { 73 | log(INFO, null, message, args); 74 | } 75 | 76 | @Override public void v(@NonNull String message, @Nullable Object... args) { 77 | log(VERBOSE, null, message, args); 78 | } 79 | 80 | @Override public void wtf(@NonNull String message, @Nullable Object... args) { 81 | log(ASSERT, null, message, args); 82 | } 83 | 84 | @Override public void json(@Nullable String json) { 85 | if (Utils.isEmpty(json)) { 86 | d("Empty/Null json content"); 87 | return; 88 | } 89 | try { 90 | json = json.trim(); 91 | if (json.startsWith("{")) { 92 | JSONObject jsonObject = new JSONObject(json); 93 | String message = jsonObject.toString(JSON_INDENT); 94 | d(message); 95 | return; 96 | } 97 | if (json.startsWith("[")) { 98 | JSONArray jsonArray = new JSONArray(json); 99 | String message = jsonArray.toString(JSON_INDENT); 100 | d(message); 101 | return; 102 | } 103 | e("Invalid Json"); 104 | } catch (JSONException e) { 105 | e("Invalid Json"); 106 | } 107 | } 108 | 109 | @Override public void xml(@Nullable String xml) { 110 | if (Utils.isEmpty(xml)) { 111 | d("Empty/Null xml content"); 112 | return; 113 | } 114 | try { 115 | Source xmlInput = new StreamSource(new StringReader(xml)); 116 | StreamResult xmlOutput = new StreamResult(new StringWriter()); 117 | Transformer transformer = TransformerFactory.newInstance().newTransformer(); 118 | transformer.setOutputProperty(OutputKeys.INDENT, "yes"); 119 | transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); 120 | transformer.transform(xmlInput, xmlOutput); 121 | d(xmlOutput.getWriter().toString().replaceFirst(">", ">\n")); 122 | } catch (TransformerException e) { 123 | e("Invalid xml"); 124 | } 125 | } 126 | 127 | @Override public synchronized void log(int priority, 128 | @Nullable String tag, 129 | @Nullable String message, 130 | @Nullable Throwable throwable) { 131 | if (throwable != null && message != null) { 132 | message += " : " + Utils.getStackTraceString(throwable); 133 | } 134 | if (throwable != null && message == null) { 135 | message = Utils.getStackTraceString(throwable); 136 | } 137 | if (Utils.isEmpty(message)) { 138 | message = "Empty/NULL log message"; 139 | } 140 | 141 | for (LogAdapter adapter : logAdapters) { 142 | if (adapter.isLoggable(priority, tag)) { 143 | adapter.log(priority, tag, message); 144 | } 145 | } 146 | } 147 | 148 | @Override public void clearLogAdapters() { 149 | logAdapters.clear(); 150 | } 151 | 152 | @Override public void addAdapter(@NonNull LogAdapter adapter) { 153 | logAdapters.add(checkNotNull(adapter)); 154 | } 155 | 156 | /** 157 | * This method is synchronized in order to avoid messy of logs' order. 158 | */ 159 | private synchronized void log(int priority, 160 | @Nullable Throwable throwable, 161 | @NonNull String msg, 162 | @Nullable Object... args) { 163 | checkNotNull(msg); 164 | 165 | String tag = getTag(); 166 | String message = createMessage(msg, args); 167 | log(priority, tag, message, throwable); 168 | } 169 | 170 | /** 171 | * @return the appropriate tag based on local or global 172 | */ 173 | @Nullable private String getTag() { 174 | String tag = localTag.get(); 175 | if (tag != null) { 176 | localTag.remove(); 177 | return tag; 178 | } 179 | return null; 180 | } 181 | 182 | @NonNull private String createMessage(@NonNull String message, @Nullable Object... args) { 183 | return args == null || args.length == 0 ? message : String.format(message, args); 184 | } 185 | } 186 | -------------------------------------------------------------------------------- /logger/src/main/java/com/orhanobut/logger/PrettyFormatStrategy.java: -------------------------------------------------------------------------------- 1 | package com.orhanobut.logger; 2 | 3 | import androidx.annotation.NonNull; 4 | import androidx.annotation.Nullable; 5 | 6 | import static com.orhanobut.logger.Utils.checkNotNull; 7 | 8 | /** 9 | * Draws borders around the given log message along with additional information such as : 10 | * 11 | *
    12 | *
  • Thread information
  • 13 | *
  • Method stack trace
  • 14 | *
15 | * 16 | *
 17 |  *  ┌──────────────────────────
 18 |  *  │ Method stack history
 19 |  *  ├┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
 20 |  *  │ Thread information
 21 |  *  ├┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
 22 |  *  │ Log message
 23 |  *  └──────────────────────────
 24 |  * 
25 | * 26 | *

Customize

27 | *

 28 |  *   FormatStrategy formatStrategy = PrettyFormatStrategy.newBuilder()
 29 |  *       .showThreadInfo(false)  // (Optional) Whether to show thread info or not. Default true
 30 |  *       .methodCount(0)         // (Optional) How many method line to show. Default 2
 31 |  *       .methodOffset(7)        // (Optional) Hides internal method calls up to offset. Default 5
 32 |  *       .logStrategy(customLog) // (Optional) Changes the log strategy to print out. Default LogCat
 33 |  *       .tag("My custom tag")   // (Optional) Global tag for every log. Default PRETTY_LOGGER
 34 |  *       .build();
 35 |  * 
36 | */ 37 | public class PrettyFormatStrategy implements FormatStrategy { 38 | 39 | /** 40 | * Android's max limit for a log entry is ~4076 bytes, 41 | * so 4000 bytes is used as chunk size since default charset 42 | * is UTF-8 43 | */ 44 | private static final int CHUNK_SIZE = 4000; 45 | 46 | /** 47 | * The minimum stack trace index, starts at this class after two native calls. 48 | */ 49 | private static final int MIN_STACK_OFFSET = 5; 50 | 51 | /** 52 | * Drawing toolbox 53 | */ 54 | private static final char TOP_LEFT_CORNER = '┌'; 55 | private static final char BOTTOM_LEFT_CORNER = '└'; 56 | private static final char MIDDLE_CORNER = '├'; 57 | private static final char HORIZONTAL_LINE = '│'; 58 | private static final String DOUBLE_DIVIDER = "────────────────────────────────────────────────────────"; 59 | private static final String SINGLE_DIVIDER = "┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄"; 60 | private static final String TOP_BORDER = TOP_LEFT_CORNER + DOUBLE_DIVIDER + DOUBLE_DIVIDER; 61 | private static final String BOTTOM_BORDER = BOTTOM_LEFT_CORNER + DOUBLE_DIVIDER + DOUBLE_DIVIDER; 62 | private static final String MIDDLE_BORDER = MIDDLE_CORNER + SINGLE_DIVIDER + SINGLE_DIVIDER; 63 | 64 | private final int methodCount; 65 | private final int methodOffset; 66 | private final boolean showThreadInfo; 67 | @NonNull private final LogStrategy logStrategy; 68 | @Nullable private final String tag; 69 | 70 | private PrettyFormatStrategy(@NonNull Builder builder) { 71 | checkNotNull(builder); 72 | 73 | methodCount = builder.methodCount; 74 | methodOffset = builder.methodOffset; 75 | showThreadInfo = builder.showThreadInfo; 76 | logStrategy = builder.logStrategy; 77 | tag = builder.tag; 78 | } 79 | 80 | @NonNull public static Builder newBuilder() { 81 | return new Builder(); 82 | } 83 | 84 | @Override public void log(int priority, @Nullable String onceOnlyTag, @NonNull String message) { 85 | checkNotNull(message); 86 | 87 | String tag = formatTag(onceOnlyTag); 88 | 89 | logTopBorder(priority, tag); 90 | logHeaderContent(priority, tag, methodCount); 91 | 92 | //get bytes of message with system's default charset (which is UTF-8 for Android) 93 | byte[] bytes = message.getBytes(); 94 | int length = bytes.length; 95 | if (length <= CHUNK_SIZE) { 96 | if (methodCount > 0) { 97 | logDivider(priority, tag); 98 | } 99 | logContent(priority, tag, message); 100 | logBottomBorder(priority, tag); 101 | return; 102 | } 103 | if (methodCount > 0) { 104 | logDivider(priority, tag); 105 | } 106 | for (int i = 0; i < length; i += CHUNK_SIZE) { 107 | int count = Math.min(length - i, CHUNK_SIZE); 108 | //create a new String with system's default charset (which is UTF-8 for Android) 109 | logContent(priority, tag, new String(bytes, i, count)); 110 | } 111 | logBottomBorder(priority, tag); 112 | } 113 | 114 | private void logTopBorder(int logType, @Nullable String tag) { 115 | logChunk(logType, tag, TOP_BORDER); 116 | } 117 | 118 | @SuppressWarnings("StringBufferReplaceableByString") 119 | private void logHeaderContent(int logType, @Nullable String tag, int methodCount) { 120 | StackTraceElement[] trace = Thread.currentThread().getStackTrace(); 121 | if (showThreadInfo) { 122 | logChunk(logType, tag, HORIZONTAL_LINE + " Thread: " + Thread.currentThread().getName()); 123 | logDivider(logType, tag); 124 | } 125 | String level = ""; 126 | 127 | int stackOffset = getStackOffset(trace) + methodOffset; 128 | 129 | //corresponding method count with the current stack may exceeds the stack trace. Trims the count 130 | if (methodCount + stackOffset > trace.length) { 131 | methodCount = trace.length - stackOffset - 1; 132 | } 133 | 134 | for (int i = methodCount; i > 0; i--) { 135 | int stackIndex = i + stackOffset; 136 | if (stackIndex >= trace.length) { 137 | continue; 138 | } 139 | StringBuilder builder = new StringBuilder(); 140 | builder.append(HORIZONTAL_LINE) 141 | .append(' ') 142 | .append(level) 143 | .append(getSimpleClassName(trace[stackIndex].getClassName())) 144 | .append(".") 145 | .append(trace[stackIndex].getMethodName()) 146 | .append(" ") 147 | .append(" (") 148 | .append(trace[stackIndex].getFileName()) 149 | .append(":") 150 | .append(trace[stackIndex].getLineNumber()) 151 | .append(")"); 152 | level += " "; 153 | logChunk(logType, tag, builder.toString()); 154 | } 155 | } 156 | 157 | private void logBottomBorder(int logType, @Nullable String tag) { 158 | logChunk(logType, tag, BOTTOM_BORDER); 159 | } 160 | 161 | private void logDivider(int logType, @Nullable String tag) { 162 | logChunk(logType, tag, MIDDLE_BORDER); 163 | } 164 | 165 | private void logContent(int logType, @Nullable String tag, @NonNull String chunk) { 166 | checkNotNull(chunk); 167 | 168 | String[] lines = chunk.split(System.getProperty("line.separator")); 169 | for (String line : lines) { 170 | logChunk(logType, tag, HORIZONTAL_LINE + " " + line); 171 | } 172 | } 173 | 174 | private void logChunk(int priority, @Nullable String tag, @NonNull String chunk) { 175 | checkNotNull(chunk); 176 | 177 | logStrategy.log(priority, tag, chunk); 178 | } 179 | 180 | private String getSimpleClassName(@NonNull String name) { 181 | checkNotNull(name); 182 | 183 | int lastIndex = name.lastIndexOf("."); 184 | return name.substring(lastIndex + 1); 185 | } 186 | 187 | /** 188 | * Determines the starting index of the stack trace, after method calls made by this class. 189 | * 190 | * @param trace the stack trace 191 | * @return the stack offset 192 | */ 193 | private int getStackOffset(@NonNull StackTraceElement[] trace) { 194 | checkNotNull(trace); 195 | 196 | for (int i = MIN_STACK_OFFSET; i < trace.length; i++) { 197 | StackTraceElement e = trace[i]; 198 | String name = e.getClassName(); 199 | if (!name.equals(LoggerPrinter.class.getName()) && !name.equals(Logger.class.getName())) { 200 | return --i; 201 | } 202 | } 203 | return -1; 204 | } 205 | 206 | @Nullable private String formatTag(@Nullable String tag) { 207 | if (!Utils.isEmpty(tag) && !Utils.equals(this.tag, tag)) { 208 | return this.tag + "-" + tag; 209 | } 210 | return this.tag; 211 | } 212 | 213 | public static class Builder { 214 | int methodCount = 2; 215 | int methodOffset = 0; 216 | boolean showThreadInfo = true; 217 | @Nullable LogStrategy logStrategy; 218 | @Nullable String tag = "PRETTY_LOGGER"; 219 | 220 | private Builder() { 221 | } 222 | 223 | @NonNull public Builder methodCount(int val) { 224 | methodCount = val; 225 | return this; 226 | } 227 | 228 | @NonNull public Builder methodOffset(int val) { 229 | methodOffset = val; 230 | return this; 231 | } 232 | 233 | @NonNull public Builder showThreadInfo(boolean val) { 234 | showThreadInfo = val; 235 | return this; 236 | } 237 | 238 | @NonNull public Builder logStrategy(@Nullable LogStrategy val) { 239 | logStrategy = val; 240 | return this; 241 | } 242 | 243 | @NonNull public Builder tag(@Nullable String tag) { 244 | this.tag = tag; 245 | return this; 246 | } 247 | 248 | @NonNull public PrettyFormatStrategy build() { 249 | if (logStrategy == null) { 250 | logStrategy = new LogcatLogStrategy(); 251 | } 252 | return new PrettyFormatStrategy(this); 253 | } 254 | } 255 | 256 | } 257 | -------------------------------------------------------------------------------- /logger/src/main/java/com/orhanobut/logger/Printer.java: -------------------------------------------------------------------------------- 1 | package com.orhanobut.logger; 2 | 3 | import androidx.annotation.NonNull; 4 | import androidx.annotation.Nullable; 5 | 6 | /** 7 | * A proxy interface to enable additional operations. 8 | * Contains all possible Log message usages. 9 | */ 10 | public interface Printer { 11 | 12 | void addAdapter(@NonNull LogAdapter adapter); 13 | 14 | Printer t(@Nullable String tag); 15 | 16 | void d(@NonNull String message, @Nullable Object... args); 17 | 18 | void d(@Nullable Object object); 19 | 20 | void e(@NonNull String message, @Nullable Object... args); 21 | 22 | void e(@Nullable Throwable throwable, @NonNull String message, @Nullable Object... args); 23 | 24 | void w(@NonNull String message, @Nullable Object... args); 25 | 26 | void i(@NonNull String message, @Nullable Object... args); 27 | 28 | void v(@NonNull String message, @Nullable Object... args); 29 | 30 | void wtf(@NonNull String message, @Nullable Object... args); 31 | 32 | /** 33 | * Formats the given json content and print it 34 | */ 35 | void json(@Nullable String json); 36 | 37 | /** 38 | * Formats the given xml content and print it 39 | */ 40 | void xml(@Nullable String xml); 41 | 42 | void log(int priority, @Nullable String tag, @Nullable String message, @Nullable Throwable throwable); 43 | 44 | void clearLogAdapters(); 45 | } 46 | -------------------------------------------------------------------------------- /logger/src/main/java/com/orhanobut/logger/Utils.java: -------------------------------------------------------------------------------- 1 | package com.orhanobut.logger; 2 | 3 | import androidx.annotation.NonNull; 4 | import androidx.annotation.Nullable; 5 | 6 | import java.io.PrintWriter; 7 | import java.io.StringWriter; 8 | import java.net.UnknownHostException; 9 | import java.util.Arrays; 10 | 11 | import static com.orhanobut.logger.Logger.ASSERT; 12 | import static com.orhanobut.logger.Logger.DEBUG; 13 | import static com.orhanobut.logger.Logger.ERROR; 14 | import static com.orhanobut.logger.Logger.INFO; 15 | import static com.orhanobut.logger.Logger.VERBOSE; 16 | import static com.orhanobut.logger.Logger.WARN; 17 | 18 | /** 19 | * Provides convenient methods to some common operations 20 | */ 21 | final class Utils { 22 | 23 | private Utils() { 24 | // Hidden constructor. 25 | } 26 | 27 | /** 28 | * Returns true if the string is null or 0-length. 29 | * 30 | * @param str the string to be examined 31 | * @return true if str is null or zero length 32 | */ 33 | static boolean isEmpty(CharSequence str) { 34 | return str == null || str.length() == 0; 35 | } 36 | 37 | /** 38 | * Returns true if a and b are equal, including if they are both null. 39 | *

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

41 | * 42 | * @param a first CharSequence to check 43 | * @param b second CharSequence to check 44 | * @return true if a and b are equal 45 | *

46 | * NOTE: Logic slightly change due to strict policy on CI - 47 | * "Inner assignments should be avoided" 48 | */ 49 | static boolean equals(CharSequence a, CharSequence b) { 50 | if (a == b) return true; 51 | if (a != null && b != null) { 52 | int length = a.length(); 53 | if (length == b.length()) { 54 | if (a instanceof String && b instanceof String) { 55 | return a.equals(b); 56 | } else { 57 | for (int i = 0; i < length; i++) { 58 | if (a.charAt(i) != b.charAt(i)) return false; 59 | } 60 | return true; 61 | } 62 | } 63 | } 64 | return false; 65 | } 66 | 67 | /** 68 | * Copied from "android.util.Log.getStackTraceString()" in order to avoid usage of Android stack 69 | * in unit tests. 70 | * 71 | * @return Stack trace in form of String 72 | */ 73 | static String getStackTraceString(Throwable tr) { 74 | if (tr == null) { 75 | return ""; 76 | } 77 | 78 | // This is to reduce the amount of log spew that apps do in the non-error 79 | // condition of the network being unavailable. 80 | Throwable t = tr; 81 | while (t != null) { 82 | if (t instanceof UnknownHostException) { 83 | return ""; 84 | } 85 | t = t.getCause(); 86 | } 87 | 88 | StringWriter sw = new StringWriter(); 89 | PrintWriter pw = new PrintWriter(sw); 90 | tr.printStackTrace(pw); 91 | pw.flush(); 92 | return sw.toString(); 93 | } 94 | 95 | static String logLevel(int value) { 96 | switch (value) { 97 | case VERBOSE: 98 | return "VERBOSE"; 99 | case DEBUG: 100 | return "DEBUG"; 101 | case INFO: 102 | return "INFO"; 103 | case WARN: 104 | return "WARN"; 105 | case ERROR: 106 | return "ERROR"; 107 | case ASSERT: 108 | return "ASSERT"; 109 | default: 110 | return "UNKNOWN"; 111 | } 112 | } 113 | 114 | public static String toString(Object object) { 115 | if (object == null) { 116 | return "null"; 117 | } 118 | if (!object.getClass().isArray()) { 119 | return object.toString(); 120 | } 121 | if (object instanceof boolean[]) { 122 | return Arrays.toString((boolean[]) object); 123 | } 124 | if (object instanceof byte[]) { 125 | return Arrays.toString((byte[]) object); 126 | } 127 | if (object instanceof char[]) { 128 | return Arrays.toString((char[]) object); 129 | } 130 | if (object instanceof short[]) { 131 | return Arrays.toString((short[]) object); 132 | } 133 | if (object instanceof int[]) { 134 | return Arrays.toString((int[]) object); 135 | } 136 | if (object instanceof long[]) { 137 | return Arrays.toString((long[]) object); 138 | } 139 | if (object instanceof float[]) { 140 | return Arrays.toString((float[]) object); 141 | } 142 | if (object instanceof double[]) { 143 | return Arrays.toString((double[]) object); 144 | } 145 | if (object instanceof Object[]) { 146 | return Arrays.deepToString((Object[]) object); 147 | } 148 | return "Couldn't find a correct type for the object"; 149 | } 150 | 151 | @NonNull static T checkNotNull(@Nullable final T obj) { 152 | if (obj == null) { 153 | throw new NullPointerException(); 154 | } 155 | return obj; 156 | } 157 | } 158 | -------------------------------------------------------------------------------- /logger/src/test/java/com.orhanobut.logger/AndroidLogAdapterTest.kt: -------------------------------------------------------------------------------- 1 | package com.orhanobut.logger 2 | 3 | import org.junit.Test 4 | 5 | import com.google.common.truth.Truth.assertThat 6 | import com.orhanobut.logger.Logger.DEBUG 7 | import org.mockito.Mockito.mock 8 | import org.mockito.Mockito.verify 9 | 10 | class AndroidLogAdapterTest { 11 | 12 | @Test fun isLoggable() { 13 | val logAdapter = AndroidLogAdapter() 14 | 15 | assertThat(logAdapter.isLoggable(DEBUG, "tag")).isTrue() 16 | } 17 | 18 | @Test fun log() { 19 | val formatStrategy = mock(FormatStrategy::class.java) 20 | val logAdapter = AndroidLogAdapter(formatStrategy) 21 | 22 | logAdapter.log(DEBUG, null, "message") 23 | 24 | verify(formatStrategy).log(DEBUG, null, "message") 25 | } 26 | 27 | } -------------------------------------------------------------------------------- /logger/src/test/java/com.orhanobut.logger/CsvFormatStrategyTest.kt: -------------------------------------------------------------------------------- 1 | package com.orhanobut.logger 2 | 3 | import org.junit.Test 4 | 5 | import com.google.common.truth.Truth.assertThat 6 | 7 | class CsvFormatStrategyTest { 8 | 9 | @Test fun log() { 10 | val formatStrategy = CsvFormatStrategy.newBuilder() 11 | .logStrategy { priority, tag, message -> 12 | assertThat(tag).isEqualTo("PRETTY_LOGGER-tag") 13 | assertThat(priority).isEqualTo(Logger.VERBOSE) 14 | assertThat(message).contains("VERBOSE,PRETTY_LOGGER-tag,message") 15 | } 16 | .build() 17 | 18 | formatStrategy.log(Logger.VERBOSE, "tag", "message") 19 | } 20 | 21 | @Test fun defaultTag() { 22 | val formatStrategy = CsvFormatStrategy.newBuilder() 23 | .logStrategy { priority, tag, message -> assertThat(tag).isEqualTo("PRETTY_LOGGER") } 24 | .build() 25 | 26 | formatStrategy.log(Logger.VERBOSE, null, "message") 27 | } 28 | 29 | @Test fun customTag() { 30 | val formatStrategy = CsvFormatStrategy.newBuilder() 31 | .tag("custom") 32 | .logStrategy { priority, tag, message -> assertThat(tag).isEqualTo("custom") } 33 | .build() 34 | 35 | formatStrategy.log(Logger.VERBOSE, null, "message") 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /logger/src/test/java/com.orhanobut.logger/DiskLogAdapterTest.kt: -------------------------------------------------------------------------------- 1 | package com.orhanobut.logger 2 | 3 | import com.google.common.truth.Truth.assertThat 4 | import org.junit.Before 5 | import org.junit.Test 6 | import org.mockito.Mock 7 | import org.mockito.Mockito.verify 8 | import org.mockito.MockitoAnnotations.initMocks 9 | 10 | class DiskLogAdapterTest { 11 | 12 | @Mock private lateinit var formatStrategy: FormatStrategy 13 | 14 | @Before fun setup() { 15 | initMocks(this) 16 | } 17 | 18 | @Test fun isLoggableTrue() { 19 | val logAdapter = DiskLogAdapter(formatStrategy) 20 | 21 | assertThat(logAdapter.isLoggable(Logger.VERBOSE, "tag")).isTrue() 22 | } 23 | 24 | @Test fun isLoggableFalse() { 25 | val logAdapter = object : DiskLogAdapter(formatStrategy) { 26 | override fun isLoggable(priority: Int, tag: String?): Boolean { 27 | return false 28 | } 29 | } 30 | 31 | assertThat(logAdapter.isLoggable(Logger.VERBOSE, "tag")).isFalse() 32 | } 33 | 34 | @Test fun log() { 35 | val logAdapter = DiskLogAdapter(formatStrategy) 36 | 37 | logAdapter.log(Logger.VERBOSE, "tag", "message") 38 | 39 | verify(formatStrategy).log(Logger.VERBOSE, "tag", "message") 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /logger/src/test/java/com.orhanobut.logger/DiskLogStrategyTest.kt: -------------------------------------------------------------------------------- 1 | package com.orhanobut.logger 2 | 3 | import android.os.Handler 4 | 5 | import org.junit.Test 6 | 7 | import com.orhanobut.logger.Logger.DEBUG 8 | import org.mockito.Mockito.mock 9 | import org.mockito.Mockito.verify 10 | 11 | class DiskLogStrategyTest { 12 | 13 | @Test fun log() { 14 | val handler = mock(Handler::class.java) 15 | val logStrategy = DiskLogStrategy(handler) 16 | 17 | logStrategy.log(DEBUG, "tag", "message") 18 | 19 | verify(handler).sendMessage(handler.obtainMessage(DEBUG, "message")) 20 | } 21 | 22 | } -------------------------------------------------------------------------------- /logger/src/test/java/com.orhanobut.logger/LogAssert.kt: -------------------------------------------------------------------------------- 1 | package com.orhanobut.logger 2 | 3 | import com.google.common.truth.Truth.assertThat 4 | 5 | internal class LogAssert(private val items: MutableList, tag: String?, private val priority: Int) { 6 | 7 | private val tag: String 8 | 9 | private var index = 0 10 | 11 | init { 12 | this.tag = tag ?: DEFAULT_TAG 13 | } 14 | 15 | fun hasTopBorder(): LogAssert { 16 | return hasLog(priority, tag, TOP_BORDER) 17 | } 18 | 19 | fun hasBottomBorder(): LogAssert { 20 | return hasLog(priority, tag, BOTTOM_BORDER) 21 | } 22 | 23 | fun hasMiddleBorder(): LogAssert { 24 | return hasLog(priority, tag, MIDDLE_BORDER) 25 | } 26 | 27 | fun hasThread(threadName: String): LogAssert { 28 | return hasLog(priority, tag, "$HORIZONTAL_LINE Thread: $threadName") 29 | } 30 | 31 | fun hasMethodInfo(methodInfo: String): LogAssert { 32 | return hasLog(priority, tag, "$HORIZONTAL_LINE $methodInfo") 33 | } 34 | 35 | fun hasMessage(message: String): LogAssert { 36 | return hasLog(priority, tag, "$HORIZONTAL_LINE $message") 37 | } 38 | 39 | private fun hasLog(priority: Int, tag: String, message: String): LogAssert = apply { 40 | val item = items[index++] 41 | assertThat(item.priority).isEqualTo(priority) 42 | assertThat(item.tag).isEqualTo(tag) 43 | assertThat(item.message).isEqualTo(message) 44 | } 45 | 46 | fun skip(): LogAssert = apply { 47 | index++ 48 | } 49 | 50 | fun hasNoMoreMessages() { 51 | assertThat(items).hasSize(index) 52 | items.clear() 53 | } 54 | 55 | internal class LogItem(val priority: Int, val tag: String, val message: String) 56 | 57 | companion object { 58 | private const val DEFAULT_TAG = "PRETTY_LOGGER" 59 | 60 | private const val TOP_LEFT_CORNER = '┌' 61 | private const val BOTTOM_LEFT_CORNER = '└' 62 | private const val MIDDLE_CORNER = '├' 63 | private const val HORIZONTAL_LINE = '│' 64 | private const val DOUBLE_DIVIDER = "────────────────────────────────────────────────────────" 65 | private const val SINGLE_DIVIDER = "┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄" 66 | private val TOP_BORDER = TOP_LEFT_CORNER + DOUBLE_DIVIDER + DOUBLE_DIVIDER 67 | private val BOTTOM_BORDER = BOTTOM_LEFT_CORNER + DOUBLE_DIVIDER + DOUBLE_DIVIDER 68 | private val MIDDLE_BORDER = MIDDLE_CORNER + SINGLE_DIVIDER + SINGLE_DIVIDER 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /logger/src/test/java/com.orhanobut.logger/LogcatLogStrategyTest.kt: -------------------------------------------------------------------------------- 1 | package com.orhanobut.logger 2 | 3 | import org.junit.Test 4 | import org.junit.runner.RunWith 5 | import org.robolectric.RobolectricTestRunner 6 | import org.robolectric.annotation.Config 7 | import org.robolectric.shadows.ShadowLog 8 | 9 | import com.google.common.truth.Truth.assertThat 10 | import com.orhanobut.logger.Logger.DEBUG 11 | 12 | @RunWith(RobolectricTestRunner::class) 13 | class LogcatLogStrategyTest { 14 | 15 | @Test fun log() { 16 | val logStrategy = LogcatLogStrategy() 17 | 18 | logStrategy.log(DEBUG, "tag", "message") 19 | 20 | val logItems = ShadowLog.getLogs() 21 | assertThat(logItems[0].type).isEqualTo(DEBUG) 22 | assertThat(logItems[0].msg).isEqualTo("message") 23 | assertThat(logItems[0].tag).isEqualTo("tag") 24 | } 25 | 26 | @Test fun logWithNullTag() { 27 | val logStrategy = LogcatLogStrategy() 28 | 29 | logStrategy.log(DEBUG, null, "message") 30 | 31 | val logItems = ShadowLog.getLogs() 32 | assertThat(logItems[0].tag).isEqualTo(LogcatLogStrategy.DEFAULT_TAG) 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /logger/src/test/java/com.orhanobut.logger/LoggerPrinterTest.kt: -------------------------------------------------------------------------------- 1 | package com.orhanobut.logger 2 | 3 | import com.orhanobut.logger.Logger.* 4 | import org.junit.Before 5 | import org.junit.Test 6 | import org.mockito.Matchers.any 7 | import org.mockito.Matchers.contains 8 | import org.mockito.Matchers.eq 9 | import org.mockito.Matchers.isNull 10 | import org.mockito.Mock 11 | import org.mockito.Mockito.`when` 12 | import org.mockito.Mockito.mock 13 | import org.mockito.Mockito.never 14 | import org.mockito.Mockito.times 15 | import org.mockito.Mockito.verify 16 | import org.mockito.Mockito.verifyZeroInteractions 17 | import org.mockito.MockitoAnnotations.initMocks 18 | import java.util.* 19 | 20 | class LoggerPrinterTest { 21 | 22 | private val printer = LoggerPrinter() 23 | 24 | @Mock private lateinit var adapter: LogAdapter 25 | 26 | @Before fun setup() { 27 | initMocks(this) 28 | `when`(adapter!!.isLoggable(any(Int::class.java), any(String::class.java))).thenReturn(true) 29 | printer.addAdapter(adapter!!) 30 | } 31 | 32 | @Test fun logDebug() { 33 | printer.d("message %s", "sent") 34 | 35 | verify(adapter).log(DEBUG, null, "message sent") 36 | } 37 | 38 | @Test fun logError() { 39 | printer.e("message %s", "sent") 40 | 41 | verify(adapter).log(ERROR, null, "message sent") 42 | } 43 | 44 | @Test fun logErrorWithThrowable() { 45 | val throwable = Throwable("exception") 46 | 47 | printer.e(throwable, "message %s", "sent") 48 | 49 | verify(adapter).log(eq(ERROR), isNull(String::class.java), contains("message sent : java.lang.Throwable: exception")) 50 | } 51 | 52 | @Test fun logWarning() { 53 | printer.w("message %s", "sent") 54 | 55 | verify(adapter).log(WARN, null, "message sent") 56 | } 57 | 58 | @Test fun logInfo() { 59 | printer.i("message %s", "sent") 60 | 61 | verify(adapter).log(INFO, null, "message sent") 62 | } 63 | 64 | @Test fun logWtf() { 65 | printer.wtf("message %s", "sent") 66 | 67 | verify(adapter).log(ASSERT, null, "message sent") 68 | } 69 | 70 | @Test fun logVerbose() { 71 | printer.v("message %s", "sent") 72 | 73 | verify(adapter).log(VERBOSE, null, "message sent") 74 | } 75 | 76 | @Test fun oneTimeTag() { 77 | printer.t("tag").d("message") 78 | 79 | verify(adapter).log(DEBUG, "tag", "message") 80 | } 81 | 82 | @Test fun logObject() { 83 | val `object` = "Test" 84 | 85 | printer.d(`object`) 86 | 87 | verify(adapter).log(DEBUG, null, "Test") 88 | } 89 | 90 | @Test fun logArray() { 91 | val `object` = intArrayOf(1, 6, 7, 30, 33) 92 | 93 | printer.d(`object`) 94 | 95 | verify(adapter).log(DEBUG, null, "[1, 6, 7, 30, 33]") 96 | } 97 | 98 | @Test fun logStringArray() { 99 | val `object` = arrayOf("a", "b", "c") 100 | 101 | printer.d(`object`) 102 | 103 | verify(adapter).log(DEBUG, null, "[a, b, c]") 104 | } 105 | 106 | @Test fun logMultiDimensionArray() { 107 | val doubles = arrayOf(doubleArrayOf(1.0, 6.0), doubleArrayOf(1.2, 33.0)) 108 | 109 | printer.d(doubles) 110 | 111 | verify(adapter).log(DEBUG, null, "[[1.0, 6.0], [1.2, 33.0]]") 112 | } 113 | 114 | @Test fun logList() { 115 | val list = Arrays.asList("foo", "bar") 116 | printer.d(list) 117 | 118 | verify(adapter).log(DEBUG, null, list.toString()) 119 | } 120 | 121 | @Test fun logMap() { 122 | val map = HashMap() 123 | map["key"] = "value" 124 | map["key2"] = "value2" 125 | 126 | printer.d(map) 127 | 128 | verify(adapter).log(DEBUG, null, map.toString()) 129 | } 130 | 131 | @Test fun logSet() { 132 | val set = HashSet() 133 | set.add("key") 134 | set.add("key1") 135 | 136 | printer.d(set) 137 | 138 | verify(adapter).log(DEBUG, null, set.toString()) 139 | } 140 | 141 | @Test fun logJsonObject() { 142 | printer.json(" {\"key\":3}") 143 | 144 | verify(adapter).log(DEBUG, null, "{\"key\": 3}") 145 | } 146 | 147 | @Test fun logJsonArray() { 148 | printer.json("[{\"key\":3}]") 149 | 150 | verify(adapter).log(DEBUG, null, "[{\"key\": 3}]") 151 | } 152 | 153 | 154 | @Test fun logInvalidJsonObject() { 155 | printer.json("no json") 156 | printer.json("{ missing end") 157 | 158 | verify(adapter, times(2)).log(ERROR, null, "Invalid Json") 159 | } 160 | 161 | @Test fun jsonLogEmptyOrNull() { 162 | printer.json(null) 163 | printer.json("") 164 | 165 | verify(adapter, times(2)).log(DEBUG, null, "Empty/Null json content") 166 | } 167 | 168 | @Test fun xmlLog() { 169 | printer.xml("Test") 170 | 171 | verify(adapter).log(DEBUG, null, 172 | "\nTest\n") 173 | } 174 | 175 | @Test fun invalidXmlLog() { 176 | printer.xml("xml>Test") 177 | 178 | verify(adapter).log(ERROR, null, "Invalid xml") 179 | } 180 | 181 | @Test fun xmlLogNullOrEmpty() { 182 | printer.xml(null) 183 | printer.xml("") 184 | 185 | verify(adapter, times(2)).log(DEBUG, null, "Empty/Null xml content") 186 | } 187 | 188 | @Test fun clearLogAdapters() { 189 | printer.clearLogAdapters() 190 | 191 | printer.d("") 192 | 193 | verifyZeroInteractions(adapter) 194 | } 195 | 196 | @Test fun addAdapter() { 197 | printer.clearLogAdapters() 198 | val adapter1 = mock(LogAdapter::class.java) 199 | val adapter2 = mock(LogAdapter::class.java) 200 | 201 | printer.addAdapter(adapter1) 202 | printer.addAdapter(adapter2) 203 | 204 | printer.d("message") 205 | 206 | verify(adapter1).isLoggable(DEBUG, null) 207 | verify(adapter2).isLoggable(DEBUG, null) 208 | } 209 | 210 | @Test fun doNotLogIfNotLoggable() { 211 | printer.clearLogAdapters() 212 | val adapter1 = mock(LogAdapter::class.java) 213 | `when`(adapter1.isLoggable(DEBUG, null)).thenReturn(false) 214 | 215 | val adapter2 = mock(LogAdapter::class.java) 216 | `when`(adapter2.isLoggable(DEBUG, null)).thenReturn(true) 217 | 218 | printer.addAdapter(adapter1) 219 | printer.addAdapter(adapter2) 220 | 221 | printer.d("message") 222 | 223 | verify(adapter1, never()).log(DEBUG, null, "message") 224 | verify(adapter2).log(DEBUG, null, "message") 225 | } 226 | 227 | @Test fun logWithoutMessageAndThrowable() { 228 | printer.log(DEBUG, null, null, null) 229 | 230 | verify(adapter).log(DEBUG, null, "Empty/NULL log message") 231 | } 232 | 233 | @Test fun logWithOnlyThrowableWithoutMessage() { 234 | val throwable = Throwable("exception") 235 | printer.log(DEBUG, null, null, throwable) 236 | 237 | verify(adapter).log(eq(DEBUG), isNull(String::class.java), contains("java.lang.Throwable: exception")) 238 | } 239 | } -------------------------------------------------------------------------------- /logger/src/test/java/com.orhanobut.logger/LoggerTest.kt: -------------------------------------------------------------------------------- 1 | package com.orhanobut.logger 2 | 3 | import org.junit.Before 4 | import org.junit.Test 5 | import org.mockito.Mock 6 | 7 | import org.mockito.Mockito.mock 8 | import org.mockito.Mockito.verify 9 | import org.mockito.Mockito.`when` 10 | import org.mockito.MockitoAnnotations.initMocks 11 | 12 | class LoggerTest { 13 | 14 | @Mock private lateinit var printer: Printer 15 | 16 | @Before fun setup() { 17 | initMocks(this) 18 | 19 | Logger.printer(printer) 20 | } 21 | 22 | @Test fun log() { 23 | val throwable = Throwable() 24 | Logger.log(Logger.VERBOSE, "tag", "message", throwable) 25 | 26 | verify(printer).log(Logger.VERBOSE, "tag", "message", throwable) 27 | } 28 | 29 | @Test fun debugLog() { 30 | Logger.d("message %s", "arg") 31 | 32 | verify(printer).d("message %s", "arg") 33 | } 34 | 35 | @Test fun verboseLog() { 36 | Logger.v("message %s", "arg") 37 | 38 | verify(printer).v("message %s", "arg") 39 | } 40 | 41 | @Test fun warningLog() { 42 | Logger.w("message %s", "arg") 43 | 44 | verify(printer).w("message %s", "arg") 45 | } 46 | 47 | @Test fun errorLog() { 48 | Logger.e("message %s", "arg") 49 | 50 | verify(printer).e(null as Throwable?, "message %s", "arg") 51 | } 52 | 53 | @Test fun errorLogWithThrowable() { 54 | val throwable = Throwable("throwable") 55 | Logger.e(throwable, "message %s", "arg") 56 | 57 | verify(printer).e(throwable, "message %s", "arg") 58 | } 59 | 60 | @Test fun infoLog() { 61 | Logger.i("message %s", "arg") 62 | 63 | verify(printer).i("message %s", "arg") 64 | } 65 | 66 | @Test fun wtfLog() { 67 | Logger.wtf("message %s", "arg") 68 | 69 | verify(printer).wtf("message %s", "arg") 70 | } 71 | 72 | @Test fun logObject() { 73 | val `object` = Any() 74 | Logger.d(`object`) 75 | 76 | verify(printer).d(`object`) 77 | } 78 | 79 | @Test fun jsonLog() { 80 | Logger.json("json") 81 | 82 | verify(printer).json("json") 83 | } 84 | 85 | @Test fun xmlLog() { 86 | Logger.xml("xml") 87 | 88 | verify(printer).xml("xml") 89 | } 90 | 91 | @Test fun oneTimeTag() { 92 | `when`(printer.t("tag")).thenReturn(printer) 93 | 94 | Logger.t("tag").d("message") 95 | 96 | verify(printer).t("tag") 97 | verify(printer).d("message") 98 | } 99 | 100 | @Test fun addAdapter() { 101 | val adapter = mock(LogAdapter::class.java) 102 | Logger.addLogAdapter(adapter) 103 | 104 | verify(printer).addAdapter(adapter) 105 | } 106 | 107 | @Test fun clearLogAdapters() { 108 | Logger.clearLogAdapters() 109 | 110 | verify(printer).clearLogAdapters() 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /logger/src/test/java/com.orhanobut.logger/PrettyFormatStrategyTest.kt: -------------------------------------------------------------------------------- 1 | package com.orhanobut.logger 2 | 3 | import org.junit.Test 4 | 5 | import java.util.ArrayList 6 | 7 | import com.orhanobut.logger.Logger.DEBUG 8 | 9 | class PrettyFormatStrategyTest { 10 | 11 | private val threadName = Thread.currentThread().name 12 | private val logStrategy = MockLogStrategy() 13 | private val builder = PrettyFormatStrategy.newBuilder().logStrategy(logStrategy) 14 | 15 | //TODO: Check the actual method info 16 | @Test fun defaultLog() { 17 | val formatStrategy = builder.build() 18 | 19 | formatStrategy.log(DEBUG, null, "message") 20 | 21 | assertLog(DEBUG) 22 | .hasTopBorder() 23 | .hasThread(threadName) 24 | .hasMiddleBorder() 25 | .skip() 26 | .skip() 27 | .hasMiddleBorder() 28 | .hasMessage("message") 29 | .hasBottomBorder() 30 | .hasNoMoreMessages() 31 | } 32 | 33 | @Test fun logWithoutThreadInfo() { 34 | val formatStrategy = builder.showThreadInfo(false).build() 35 | 36 | formatStrategy.log(DEBUG, null, "message") 37 | 38 | assertLog(DEBUG) 39 | .hasTopBorder() 40 | .skip() 41 | .skip() 42 | .hasMiddleBorder() 43 | .hasMessage("message") 44 | .hasBottomBorder() 45 | .hasNoMoreMessages() 46 | } 47 | 48 | @Test fun logWithoutMethodInfo() { 49 | val formatStrategy = builder.methodCount(0).build() 50 | 51 | formatStrategy.log(DEBUG, null, "message") 52 | 53 | assertLog(DEBUG) 54 | .hasTopBorder() 55 | .hasThread(threadName) 56 | .hasMiddleBorder() 57 | .hasMessage("message") 58 | .hasBottomBorder() 59 | .hasNoMoreMessages() 60 | } 61 | 62 | @Test fun logWithOnlyMessage() { 63 | val formatStrategy = builder 64 | .methodCount(0) 65 | .showThreadInfo(false) 66 | .build() 67 | 68 | formatStrategy.log(DEBUG, null, "message") 69 | 70 | assertLog(DEBUG) 71 | .hasTopBorder() 72 | .hasMessage("message") 73 | .hasBottomBorder() 74 | .hasNoMoreMessages() 75 | } 76 | 77 | //TODO: Check the actual method info 78 | @Test fun logWithCustomMethodOffset() { 79 | val formatStrategy = builder 80 | .methodOffset(2) 81 | .showThreadInfo(false) 82 | .build() 83 | 84 | formatStrategy.log(DEBUG, null, "message") 85 | 86 | assertLog(DEBUG) 87 | .hasTopBorder() 88 | .skip() 89 | .skip() 90 | .hasMiddleBorder() 91 | .hasMessage("message") 92 | .hasBottomBorder() 93 | .hasNoMoreMessages() 94 | } 95 | 96 | @Test fun logWithCustomTag() { 97 | val formatStrategy = builder 98 | .tag("custom") 99 | .build() 100 | 101 | formatStrategy.log(DEBUG, null, "message") 102 | 103 | assertLog("custom", DEBUG) 104 | .hasTopBorder() 105 | .hasThread(threadName) 106 | .hasMiddleBorder() 107 | .skip() 108 | .skip() 109 | .hasMiddleBorder() 110 | .hasMessage("message") 111 | .hasBottomBorder() 112 | .hasNoMoreMessages() 113 | } 114 | 115 | @Test fun logWithOneTimeTag() { 116 | val formatStrategy = builder 117 | .tag("custom") 118 | .build() 119 | 120 | formatStrategy.log(DEBUG, "tag", "message") 121 | 122 | assertLog("custom-tag", DEBUG) 123 | .hasTopBorder() 124 | .hasThread(threadName) 125 | .hasMiddleBorder() 126 | .skip() 127 | .skip() 128 | .hasMiddleBorder() 129 | .hasMessage("message") 130 | .hasBottomBorder() 131 | .hasNoMoreMessages() 132 | } 133 | 134 | // TODO: assert values, for now this checks that Logger doesn't crash 135 | @Test fun logWithExceedingMethodCount() { 136 | val formatStrategy = builder 137 | .methodCount(50) 138 | .build() 139 | 140 | formatStrategy.log(DEBUG, null, "message") 141 | } 142 | 143 | @Test fun logWithBigChunk() { 144 | val formatStrategy = builder.build() 145 | 146 | val chunk1 = StringBuilder() 147 | for (i in 0..399) { 148 | chunk1.append("1234567890") 149 | } 150 | val chunk2 = StringBuilder() 151 | for (i in 0..9) { 152 | chunk2.append("ABCDEFGD") 153 | } 154 | 155 | formatStrategy.log(DEBUG, null, chunk1.toString() + chunk2.toString()) 156 | 157 | assertLog(DEBUG) 158 | .hasTopBorder() 159 | .hasThread(threadName) 160 | .hasMiddleBorder() 161 | .skip() 162 | .skip() 163 | .hasMiddleBorder() 164 | .hasMessage(chunk1.toString()) 165 | .hasMessage(chunk2.toString()) 166 | .hasBottomBorder() 167 | .hasNoMoreMessages() 168 | } 169 | 170 | private class MockLogStrategy : LogStrategy { 171 | internal var logItems: MutableList = ArrayList() 172 | 173 | override fun log(priority: Int, tag: String?, message: String) { 174 | logItems.add(LogAssert.LogItem(priority, tag ?: "", message)) 175 | } 176 | } 177 | 178 | private fun assertLog(priority: Int): LogAssert { 179 | return assertLog(null, priority) 180 | } 181 | 182 | private fun assertLog(tag: String?, priority: Int): LogAssert { 183 | return LogAssert(logStrategy.logItems, tag, priority) 184 | } 185 | } 186 | -------------------------------------------------------------------------------- /logger/src/test/java/com.orhanobut.logger/UtilsTest.kt: -------------------------------------------------------------------------------- 1 | package com.orhanobut.logger 2 | 3 | import android.util.Log 4 | 5 | import org.junit.Test 6 | import org.junit.runner.RunWith 7 | import org.robolectric.RobolectricTestRunner 8 | import org.robolectric.annotation.Config 9 | 10 | import java.net.UnknownHostException 11 | 12 | import com.google.common.truth.Truth.assertThat 13 | 14 | @RunWith(RobolectricTestRunner::class) 15 | class UtilsTest { 16 | 17 | @Test fun isEmpty() { 18 | assertThat(Utils.isEmpty("")).isTrue() 19 | assertThat(Utils.isEmpty(null)).isTrue() 20 | } 21 | 22 | @Test fun equals() { 23 | assertThat(Utils.equals("a", "a")).isTrue() 24 | assertThat(Utils.equals("as", "b")).isFalse() 25 | assertThat(Utils.equals(null, "b")).isFalse() 26 | assertThat(Utils.equals("a", null)).isFalse() 27 | } 28 | 29 | @Test fun getStackTraceString() { 30 | val throwable = Throwable("test") 31 | val androidTraceString = Log.getStackTraceString(throwable) 32 | assertThat(Utils.getStackTraceString(throwable)).isEqualTo(androidTraceString) 33 | } 34 | 35 | @Test fun getStackTraceStringReturnsEmptyStringWithNull() { 36 | assertThat(Utils.getStackTraceString(null)).isEqualTo("") 37 | } 38 | 39 | @Test fun getStackTraceStringReturnEmptyStringWithUnknownHostException() { 40 | assertThat(Utils.getStackTraceString(UnknownHostException())).isEqualTo("") 41 | } 42 | 43 | @Test fun logLevels() { 44 | assertThat(Utils.logLevel(Logger.DEBUG)).isEqualTo("DEBUG") 45 | assertThat(Utils.logLevel(Logger.WARN)).isEqualTo("WARN") 46 | assertThat(Utils.logLevel(Logger.INFO)).isEqualTo("INFO") 47 | assertThat(Utils.logLevel(Logger.VERBOSE)).isEqualTo("VERBOSE") 48 | assertThat(Utils.logLevel(Logger.ASSERT)).isEqualTo("ASSERT") 49 | assertThat(Utils.logLevel(Logger.ERROR)).isEqualTo("ERROR") 50 | assertThat(Utils.logLevel(100)).isEqualTo("UNKNOWN") 51 | } 52 | 53 | @Test fun objectToString() { 54 | val `object` = "Test" 55 | 56 | assertThat(Utils.toString(`object`)).isEqualTo("Test") 57 | } 58 | 59 | @Test fun toStringWithNull() { 60 | assertThat(Utils.toString(null)).isEqualTo("null") 61 | } 62 | 63 | @Test fun primitiveArrayToString() { 64 | val booleanArray = booleanArrayOf(true, false, true) 65 | assertThat(Utils.toString(booleanArray)).isEqualTo("[true, false, true]") 66 | 67 | val byteArray = byteArrayOf(1, 0, 1) 68 | assertThat(Utils.toString(byteArray)).isEqualTo("[1, 0, 1]") 69 | 70 | val charArray = charArrayOf('a', 'b', 'c') 71 | assertThat(Utils.toString(charArray)).isEqualTo("[a, b, c]") 72 | 73 | val shortArray = shortArrayOf(1, 3, 5) 74 | assertThat(Utils.toString(shortArray)).isEqualTo("[1, 3, 5]") 75 | 76 | val intArray = intArrayOf(1, 3, 5) 77 | assertThat(Utils.toString(intArray)).isEqualTo("[1, 3, 5]") 78 | 79 | val longArray = longArrayOf(1, 3, 5) 80 | assertThat(Utils.toString(longArray)).isEqualTo("[1, 3, 5]") 81 | 82 | val floatArray = floatArrayOf(1f, 3f, 5f) 83 | assertThat(Utils.toString(floatArray)).isEqualTo("[1.0, 3.0, 5.0]") 84 | 85 | val doubleArray = doubleArrayOf(1.0, 3.0, 5.0) 86 | assertThat(Utils.toString(doubleArray)).isEqualTo("[1.0, 3.0, 5.0]") 87 | } 88 | 89 | @Test fun multiDimensionArrayToString() { 90 | val `object` = arrayOf(intArrayOf(1, 2, 3), intArrayOf(4, 5, 6)) 91 | 92 | assertThat(Utils.toString(`object`)).isEqualTo("[[1, 2, 3], [4, 5, 6]]") 93 | } 94 | } -------------------------------------------------------------------------------- /sample/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion rootProject.ext.compileSdkVersion 5 | buildToolsVersion rootProject.ext.buildToolsVersion 6 | 7 | defaultConfig { 8 | applicationId "com.orhanobut.sample" 9 | minSdkVersion 23 10 | targetSdkVersion 27 11 | versionCode 1 12 | versionName "1.0" 13 | 14 | testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner' 15 | 16 | } 17 | } 18 | 19 | dependencies { 20 | implementation project(":logger") 21 | } 22 | -------------------------------------------------------------------------------- /sample/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /sample/src/main/java/com/orhanobut/sample/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.orhanobut.sample; 2 | 3 | import android.app.Activity; 4 | import android.os.Bundle; 5 | import android.util.Log; 6 | 7 | import com.orhanobut.logger.AndroidLogAdapter; 8 | import com.orhanobut.logger.DiskLogAdapter; 9 | import com.orhanobut.logger.FormatStrategy; 10 | import com.orhanobut.logger.Logger; 11 | import com.orhanobut.logger.PrettyFormatStrategy; 12 | 13 | import java.util.Arrays; 14 | import java.util.HashMap; 15 | import java.util.Map; 16 | 17 | public class MainActivity extends Activity { 18 | 19 | @Override 20 | protected void onCreate(Bundle savedInstanceState) { 21 | super.onCreate(savedInstanceState); 22 | setContentView(R.layout.activity_main); 23 | 24 | Log.d("Tag", "I'm a log which you don't see easily, hehe"); 25 | Log.d("json content", "{ \"key\": 3, \n \"value\": something}"); 26 | Log.d("error", "There is a crash somewhere or any warning"); 27 | 28 | Logger.addLogAdapter(new AndroidLogAdapter()); 29 | Logger.d("message"); 30 | 31 | Logger.clearLogAdapters(); 32 | 33 | 34 | FormatStrategy formatStrategy = PrettyFormatStrategy.newBuilder() 35 | .showThreadInfo(false) // (Optional) Whether to show thread info or not. Default true 36 | .methodCount(0) // (Optional) How many method line to show. Default 2 37 | .methodOffset(3) // (Optional) Skips some method invokes in stack trace. Default 5 38 | // .logStrategy(customLog) // (Optional) Changes the log strategy to print out. Default LogCat 39 | .tag("My custom tag") // (Optional) Custom tag for each log. Default PRETTY_LOGGER 40 | .build(); 41 | 42 | Logger.addLogAdapter(new AndroidLogAdapter(formatStrategy)); 43 | 44 | Logger.addLogAdapter(new AndroidLogAdapter() { 45 | @Override public boolean isLoggable(int priority, String tag) { 46 | return BuildConfig.DEBUG; 47 | } 48 | }); 49 | 50 | Logger.addLogAdapter(new DiskLogAdapter()); 51 | 52 | 53 | Logger.w("no thread info and only 1 method"); 54 | 55 | Logger.clearLogAdapters(); 56 | formatStrategy = PrettyFormatStrategy.newBuilder() 57 | .showThreadInfo(false) 58 | .methodCount(0) 59 | .build(); 60 | 61 | Logger.addLogAdapter(new AndroidLogAdapter(formatStrategy)); 62 | Logger.i("no thread info and method info"); 63 | 64 | Logger.t("tag").e("Custom tag for only one use"); 65 | 66 | Logger.json("{ \"key\": 3, \"value\": something}"); 67 | 68 | Logger.d(Arrays.asList("foo", "bar")); 69 | 70 | Map map = new HashMap<>(); 71 | map.put("key", "value"); 72 | map.put("key1", "value2"); 73 | 74 | Logger.d(map); 75 | 76 | Logger.clearLogAdapters(); 77 | formatStrategy = PrettyFormatStrategy.newBuilder() 78 | .showThreadInfo(false) 79 | .methodCount(0) 80 | .tag("MyTag") 81 | .build(); 82 | Logger.addLogAdapter(new AndroidLogAdapter(formatStrategy)); 83 | 84 | Logger.w("my log message with my tag"); 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /sample/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/orhanobut/logger/c64a72c2ce3d0fcdebe829b091e3a530c94ca6bd/sample/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':logger', ':sample' --------------------------------------------------------------------------------