├── .gitignore ├── LICENSE ├── LogRecorder.java └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | # Built application files 2 | *.apk 3 | *.ap_ 4 | 5 | # Files for the Dalvik VM 6 | *.dex 7 | 8 | # Java class files 9 | *.class 10 | 11 | # Generated files 12 | bin/ 13 | gen/ 14 | 15 | # Gradle files 16 | .gradle/ 17 | build/ 18 | 19 | # Local configuration file (sdk path, etc) 20 | local.properties 21 | 22 | # Proguard folder generated by Eclipse 23 | proguard/ 24 | 25 | # Log Files 26 | *.log 27 | 28 | # Android Studio Navigation editor temp files 29 | .navigation/ 30 | 31 | # Android Studio captures folder 32 | captures/ 33 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /LogRecorder.java: -------------------------------------------------------------------------------- 1 | package cn.dxjia.logrecorder; 2 | 3 | import android.content.Context; 4 | import android.os.Environment; 5 | import android.os.Handler; 6 | import android.os.Message; 7 | import android.text.TextUtils; 8 | 9 | import java.io.BufferedReader; 10 | import java.io.File; 11 | import java.io.FileNotFoundException; 12 | import java.io.FileOutputStream; 13 | import java.io.IOException; 14 | import java.io.InputStreamReader; 15 | import java.text.SimpleDateFormat; 16 | import java.util.ArrayList; 17 | import java.util.Date; 18 | import java.util.List; 19 | 20 | /** 21 | * Reference to http://blog.csdn.net/way_ping_li/article/details/8487866 22 | * and improved some features... 23 | */ 24 | public class LogRecorder { 25 | 26 | public static final int LOG_LEVEL_NO_SET = 0; 27 | 28 | public static final int LOG_BUFFER_MAIN = 1; 29 | public static final int LOG_BUFFER_SYSTEM = 1 << 1; 30 | public static final int LOG_BUFFER_RADIO = 1 << 2; 31 | public static final int LOG_BUFFER_EVENTS = 1 << 3; 32 | public static final int LOG_BUFFER_KERNEL = 1 << 4; // not be supported by now 33 | 34 | public static final int LOG_BUFFER_DEFAULT = LOG_BUFFER_MAIN | LOG_BUFFER_SYSTEM; 35 | 36 | public static final int INVALID_PID = -1; 37 | 38 | public String mFileSuffix; 39 | public String mFolderPath; 40 | public int mFileSizeLimitation; 41 | public int mLevel; 42 | public List mFilterTags = new ArrayList<>(); 43 | public int mPID = INVALID_PID; 44 | 45 | public boolean mUseLogcatFileOut = false; 46 | 47 | private LogDumper mLogDumper = null; 48 | 49 | public static final int EVENT_RESTART_LOG = 1001; 50 | 51 | private RestartHandler mHandler; 52 | 53 | private static class RestartHandler extends Handler { 54 | final LogRecorder logRecorder; 55 | public RestartHandler(LogRecorder logRecorder) { 56 | this.logRecorder = logRecorder; 57 | } 58 | 59 | @Override 60 | public void handleMessage(Message msg) { 61 | if (msg.what == EVENT_RESTART_LOG) { 62 | logRecorder.stop(); 63 | logRecorder.start(); 64 | } 65 | } 66 | } 67 | 68 | public LogRecorder() { 69 | mHandler = new RestartHandler(this); 70 | } 71 | 72 | public void start() { 73 | // make sure the out folder exist 74 | // TODO support multi-phase path 75 | File file = new File(mFolderPath); 76 | if (!file.exists()) { 77 | file.mkdirs(); 78 | } 79 | 80 | String cmdStr = collectLogcatCommand(); 81 | 82 | if (mLogDumper != null) { 83 | mLogDumper.stopDumping(); 84 | mLogDumper = null; 85 | } 86 | 87 | mLogDumper = new LogDumper(mFolderPath, mFileSuffix, mFileSizeLimitation, cmdStr, mHandler); 88 | mLogDumper.start(); 89 | } 90 | 91 | public void stop() { 92 | // TODO maybe should clean the log buffer first? 93 | if (mLogDumper != null) { 94 | mLogDumper.stopDumping(); 95 | mLogDumper = null; 96 | } 97 | } 98 | 99 | private String collectLogcatCommand() { 100 | StringBuilder stringBuilder = new StringBuilder(); 101 | final String SPACE = " "; 102 | stringBuilder.append("logcat"); 103 | 104 | // TODO select ring buffer, -b 105 | 106 | // TODO set out format 107 | stringBuilder.append(SPACE); 108 | stringBuilder.append("-v time"); 109 | 110 | // append tag filters 111 | String levelStr = getLevelStr(); 112 | 113 | if (!mFilterTags.isEmpty()) { 114 | stringBuilder.append(SPACE); 115 | stringBuilder.append("-s"); 116 | for (int i = 0; i < mFilterTags.size(); i++) { 117 | String tag = mFilterTags.get(i) + ":" + levelStr; 118 | stringBuilder.append(SPACE); 119 | stringBuilder.append(tag); 120 | } 121 | } else { 122 | if (!TextUtils.isEmpty(levelStr)) { 123 | stringBuilder.append(SPACE); 124 | stringBuilder.append("*:" + levelStr); 125 | } 126 | } 127 | 128 | // logcat -f , but the rotated count default is 4? 129 | // can`t be sure to use that feature 130 | if (mPID != INVALID_PID) { 131 | mUseLogcatFileOut = false; 132 | String pidStr = adjustPIDStr(); 133 | if (!TextUtils.isEmpty(pidStr)) { 134 | stringBuilder.append(SPACE); 135 | stringBuilder.append("|"); 136 | stringBuilder.append(SPACE); 137 | stringBuilder.append("grep (" + pidStr + ")"); 138 | } 139 | } 140 | 141 | return stringBuilder.toString(); 142 | } 143 | 144 | private String getLevelStr() { 145 | switch (mLevel) { 146 | case 2: 147 | return "V"; 148 | case 3: 149 | return "D"; 150 | case 4: 151 | return "I"; 152 | case 5: 153 | return "W"; 154 | case 6: 155 | return "E"; 156 | case 7: 157 | return "F"; 158 | } 159 | 160 | return "V"; 161 | } 162 | 163 | /** 164 | * Android`s user app pid is bigger than 1000. 165 | * 166 | * @return 167 | */ 168 | private String adjustPIDStr() { 169 | if (mPID == INVALID_PID) { 170 | return null; 171 | } 172 | 173 | String pidStr = String.valueOf(mPID); 174 | int length = pidStr.length(); 175 | if (length < 4) { 176 | pidStr = " 0" + pidStr; 177 | } 178 | 179 | if (length == 4) { 180 | pidStr = " " + pidStr; 181 | } 182 | 183 | return pidStr; 184 | } 185 | 186 | 187 | private class LogDumper extends Thread { 188 | final String logPath; 189 | final String logFileSuffix; 190 | final int logFileLimitation; 191 | final String logCmd; 192 | 193 | final RestartHandler restartHandler; 194 | 195 | private Process logcatProc; 196 | private BufferedReader mReader = null; 197 | private FileOutputStream out = null; 198 | 199 | private boolean mRunning = true; 200 | final private Object mRunningLock = new Object(); 201 | 202 | private long currentFileSize; 203 | 204 | public LogDumper(String folderPath, String suffix, 205 | int fileSizeLimitation, String command, 206 | RestartHandler handler) { 207 | logPath = folderPath; 208 | logFileSuffix = suffix; 209 | logFileLimitation = fileSizeLimitation; 210 | logCmd = command; 211 | restartHandler = handler; 212 | 213 | String date = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss") 214 | .format(new Date(System.currentTimeMillis())); 215 | String fileName = (TextUtils.isEmpty(logFileSuffix)) ? date : (logFileSuffix + "-"+ date); 216 | try { 217 | out = new FileOutputStream(new File(logPath, fileName + ".log")); 218 | } catch (FileNotFoundException e) { 219 | e.printStackTrace(); 220 | } 221 | } 222 | 223 | public void stopDumping() { 224 | synchronized (mRunningLock) { 225 | mRunning = false; 226 | } 227 | } 228 | 229 | @Override 230 | public void run() { 231 | try { 232 | logcatProc = Runtime.getRuntime().exec(logCmd); 233 | mReader = new BufferedReader(new InputStreamReader( 234 | logcatProc.getInputStream()), 1024); 235 | String line = null; 236 | while (mRunning && (line = mReader.readLine()) != null) { 237 | if (!mRunning) { 238 | break; 239 | } 240 | if (line.length() == 0) { 241 | continue; 242 | } 243 | if (out != null && !line.isEmpty()) { 244 | byte[] data = (line + "\n").getBytes(); 245 | out.write(data); 246 | if (logFileLimitation != 0) { 247 | currentFileSize += data.length; 248 | if (currentFileSize > logFileLimitation*1024) { 249 | restartHandler.sendEmptyMessage(EVENT_RESTART_LOG); 250 | break; 251 | } 252 | } 253 | } 254 | } 255 | 256 | } catch (IOException e) { 257 | e.printStackTrace(); 258 | } finally { 259 | if (logcatProc != null) { 260 | logcatProc.destroy(); 261 | logcatProc = null; 262 | } 263 | if (mReader != null) { 264 | try { 265 | mReader.close(); 266 | mReader = null; 267 | } catch (IOException e) { 268 | e.printStackTrace(); 269 | } 270 | } 271 | if (out != null) { 272 | try { 273 | out.close(); 274 | } catch (IOException e) { 275 | e.printStackTrace(); 276 | } 277 | out = null; 278 | } 279 | } 280 | } 281 | } 282 | 283 | public static class Builder { 284 | 285 | /** 286 | * context object 287 | */ 288 | private Context mContext; 289 | 290 | /** 291 | * the folder name that we save log files to, 292 | * just folder name, not the whole path, 293 | * if set this, will save log files to /sdcard/$mLogFolderName folder, 294 | * use /sdcard/$ApplicationName as default. 295 | */ 296 | private String mLogFolderName; 297 | 298 | /** 299 | * the whole folder path that we save log files to, 300 | * this setting`s priority is bigger than folder name. 301 | */ 302 | private String mLogFolderPath; 303 | 304 | /** 305 | * the log file suffix, 306 | * if this is sot, it will be appended to log file name automatically 307 | */ 308 | private String mLogFileNameSuffix = ""; 309 | 310 | /** 311 | * single log file size limitation, 312 | * in k-bytes, ex. set to 16, is 16KB limitation. 313 | */ 314 | private int mLogFileSizeLimitation = 0; 315 | 316 | /** 317 | * log level, see android.util.Log, 2 - 7, 318 | * if not be set, will use verbose as default 319 | */ 320 | private int mLogLevel = LogRecorder.LOG_LEVEL_NO_SET; 321 | 322 | /** 323 | * can set several filter tags 324 | * logcat -s ActivityManager:V SystemUI:V 325 | */ 326 | private List mLogFilterTags = new ArrayList<>(); 327 | 328 | /** 329 | * filter through pid, by setting this with your APP PID, 330 | * the log recorder will just record the APP`s own log, 331 | * use one call: android.os.Process.myPid(). 332 | */ 333 | private int mPID = LogRecorder.INVALID_PID; 334 | 335 | /** 336 | * which log buffer to catch... 337 | *

338 | * Request alternate ring buffer, 'main', 'system', 'radio' 339 | * or 'events'. Multiple -b parameters are allowed and the 340 | * results are interleaved. 341 | *

342 | * The default is -b main -b system. 343 | */ 344 | private int mLogBuffersSelected = LogRecorder.LOG_BUFFER_DEFAULT; 345 | 346 | /** 347 | * log output format, don`t support config yet, use $time format as default. 348 | *

349 | * Log messages contain a number of metadata fields, in addition to the tag and priority. 350 | * You can modify the output format for messages so that they display a specific metadata 351 | * field. To do so, you use the -v option and specify one of the supported output formats 352 | * listed below. 353 | *

354 | * brief — Display priority/tag and PID of the process issuing the message. 355 | * process — Display PID only. 356 | * tag — Display the priority/tag only. 357 | * thread - Display the priority, tag, and the PID(process ID) and TID(thread ID) 358 | * of the thread issuing the message. 359 | * raw — Display the raw log message, with no other metadata fields. 360 | * time — Display the date, invocation time, priority/tag, and PID of 361 | * the process issuing the message. 362 | * threadtime — Display the date, invocation time, priority, tag, and the PID(process ID) 363 | * and TID(thread ID) of the thread issuing the message. 364 | * long — Display all metadata fields and separate messages with blank lines. 365 | */ 366 | private int mLogOutFormat; 367 | 368 | /** 369 | * set log out folder name 370 | * 371 | * @param logFolderName folder name 372 | * @return The same Builder. 373 | */ 374 | public Builder setLogFolderName(String logFolderName) { 375 | this.mLogFolderName = logFolderName; 376 | return this; 377 | } 378 | 379 | /** 380 | * set log out folder path 381 | * 382 | * @param logFolderPath out folder absolute path 383 | * @return the same Builder 384 | */ 385 | public Builder setLogFolderPath(String logFolderPath) { 386 | this.mLogFolderPath = logFolderPath; 387 | return this; 388 | } 389 | 390 | /** 391 | * set log file name suffix 392 | * 393 | * @param logFileNameSuffix auto appened suffix 394 | * @return the same Builder 395 | */ 396 | public Builder setLogFileNameSuffix(String logFileNameSuffix) { 397 | this.mLogFileNameSuffix = logFileNameSuffix; 398 | return this; 399 | } 400 | 401 | /** 402 | * set the file size limitation 403 | * 404 | * @param fileSizeLimitation file size limitation in KB 405 | * @return the same Builder 406 | */ 407 | public Builder setLogFileSizeLimitation(int fileSizeLimitation) { 408 | this.mLogFileSizeLimitation = fileSizeLimitation; 409 | return this; 410 | } 411 | 412 | /** 413 | * set the log level 414 | * 415 | * @param logLevel log level, 2-7 416 | * @return the same Builder 417 | */ 418 | public Builder setLogLevel(int logLevel) { 419 | this.mLogLevel = logLevel; 420 | return this; 421 | } 422 | 423 | /** 424 | * add log filterspec tag name, can add multiple ones, 425 | * they use the same log level set by setLogLevel() 426 | * 427 | * @param tag tag name 428 | * @return the same Builder 429 | */ 430 | public Builder addLogFilterTag(String tag) { 431 | mLogFilterTags.add(tag); 432 | return this; 433 | } 434 | 435 | /** 436 | * which process`s log 437 | * 438 | * @param mPID process id 439 | * @return the same Builder 440 | */ 441 | public Builder setPID(int mPID) { 442 | this.mPID = mPID; 443 | return this; 444 | } 445 | 446 | /** 447 | * -b radio, -b main, -b system, -b events 448 | * -b main -b system as default 449 | * 450 | * @param logBuffersSelected one of 451 | * LOG_BUFFER_MAIN = 1 << 0; 452 | * LOG_BUFFER_SYSTEM = 1 << 1; 453 | * LOG_BUFFER_RADIO = 1 << 2; 454 | * LOG_BUFFER_EVENTS = 1 << 3; 455 | * LOG_BUFFER_KERNEL = 1 << 4; 456 | * @return the same Builder 457 | */ 458 | public Builder setLogBufferSelected(int logBuffersSelected) { 459 | this.mLogBuffersSelected = logBuffersSelected; 460 | return this; 461 | } 462 | 463 | /** 464 | * sets log out format, -v parameter 465 | * 466 | * @param logOutFormat out format, like -v time 467 | * @return the same Builder 468 | */ 469 | public Builder setLogOutFormat(int logOutFormat) { 470 | this.mLogOutFormat = mLogOutFormat; 471 | return this; 472 | } 473 | 474 | public Builder(Context context) { 475 | mContext = context; 476 | } 477 | 478 | /** 479 | * call this only if mLogFolderName and mLogFolderPath not 480 | * be set both. 481 | * 482 | * @return 483 | */ 484 | private void applyAppNameAsOutfolderName() { 485 | try { 486 | String appName = mContext.getPackageName(); 487 | String versionName = mContext.getPackageManager().getPackageInfo( 488 | appName, 0).versionName; 489 | int versionCode = mContext.getPackageManager() 490 | .getPackageInfo(appName, 0).versionCode; 491 | mLogFolderName = appName + "-" + versionName + "-" + versionCode; 492 | mLogFolderPath = applyOutfolderPath(); 493 | } catch (Exception e) { 494 | } 495 | } 496 | 497 | private String applyOutfolderPath() { 498 | String outPath = ""; 499 | if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { 500 | outPath = Environment.getExternalStorageDirectory() 501 | .getAbsolutePath() + File.separator + mLogFolderName; 502 | } 503 | 504 | return outPath; 505 | } 506 | 507 | /** 508 | * Combine all of the options that have been set and return 509 | * a new {@link LogRecorder} object. 510 | */ 511 | public LogRecorder build() { 512 | LogRecorder logRecorder = new LogRecorder(); 513 | 514 | // no folder name & folder path be set 515 | if (TextUtils.isEmpty(mLogFolderName) 516 | && TextUtils.isEmpty(mLogFolderPath)) { 517 | applyAppNameAsOutfolderName(); 518 | } 519 | 520 | // make sure out path be set 521 | if (TextUtils.isEmpty(mLogFolderPath)) { 522 | mLogFolderPath = applyOutfolderPath(); 523 | } 524 | 525 | logRecorder.mFolderPath = mLogFolderPath; 526 | logRecorder.mFileSuffix = mLogFileNameSuffix; 527 | logRecorder.mFileSizeLimitation = mLogFileSizeLimitation; 528 | logRecorder.mLevel = mLogLevel; 529 | if (!mLogFilterTags.isEmpty()) { 530 | for (int i = 0; i < mLogFilterTags.size(); i++) { 531 | logRecorder.mFilterTags.add(mLogFilterTags.get(i)); 532 | } 533 | } 534 | logRecorder.mPID = mPID; 535 | 536 | return logRecorder; 537 | } 538 | } 539 | 540 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # LogRecorder 2 | Record system or application log to sdcard on Android device. 3 | 4 | # Usage 5 | 直接复制 [LogRecorder.java](https://github.com/dxjia/LogRecorder/blob/master/LogRecorder.java) 文件到你的工程中,使用方式如下: 6 |
首先在`AndroidManifest.xml`中增加权限: 7 | ``` 8 | 9 | 10 | ``` 11 | 12 | 然后在代码中合适的地方使用,之后Log就会自动开始记录,直到调用`logRecorder.stop()`,或者进程结束: 13 | ``` 14 | LogRecorder logRecorder 15 | = new LogRecorder.Builder(context) 16 | .setLogFolderName("foldername") 17 | .setLogFolderPath("/sdcard/foldername") 18 | .setLogFileNameSuffix("filesuffix") 19 | .setLogFileSizeLimitation(256) 20 | .setLogLevel(4) 21 | .addLogFilterTag("ActivityManager") 22 | .setPID(android.os.Process.myPid()) 23 | .build(); 24 | 25 | logRecorder.start(); 26 | ``` 27 | 28 | ## setLogFolderName() 29 | > 设定log输出目录名,如果该值与folder path都没有设定的话,会默认使用应用包名在sdcard下新建目录。 30 | 31 | ## setLogFolderPath() 32 | > 设置Log输出目录绝对路径,该值会优先使用,会忽略folder name的设置。 33 | 34 | ## setLogFileNameSuffix() 35 | > log文件名前缀,文件名会使用时间的形式,该值的设定会自动追加在时间之前,如setLogFileNameSuffix("mylog") 则最后的文件名为`mylog-2016-02-04-12-26-53.log` 36 | 37 | ## setLogFileSizeLimitation() 38 | > 单个log文件的大小限制,超过设置的限制时,会自动新起新的文件记录log,**`注意`**: 是以`KB`为单位的。 39 | 40 | ## setLogLevel() 41 | > 设置记录的log级别,默认2
42 | > 2 = verbose
43 | > 3 = debug
44 | > 4 = info
45 | > 5 = warning
46 | > 6 = error
47 | > 7 = silent(不输出任何log) 48 | 49 | ## addLogFilterTag() 50 | > 设置log过滤的tag,可以add多个,如`addLogFilterTag("ActivityManager")`表示只过滤“ActivityManager”的log 51 | 52 | ## setPID() 53 | > 通过该方法可以指定一个特定的进程的log,如通过`setPID(android.os.Process.myPid())` 即可只输出自己的APP的log。 54 | --------------------------------------------------------------------------------