Android log printing LogUtils can locate the class name, method name, and number of lines with errors, and save log files.

Source: Internet
Author: User
Tags return tag

Android log printing LogUtils can locate the class name, method name, and number of lines with errors, and save log files.

 
  
During development, we often use the log printing method to debug our applications. In Java, we often use the System. out. println () method to print logs on the console for debugging. Android has a dedicated Log class to print logs in the Android system, which makes it easier for us to locate problems in the program.
  
However, the Log class officially provided by Android is not very convenient for actual projects. When an error occurs in the program, what we hope most is that the Log class can help us locate the method of the class, or even the row has an error. This will bring great convenience to our debugging.
  
At the same time, we should also think that for the sake of application security, before the app is officially launched, we should disable the Log printing function to prevent others from cracking your application through Log. In the production mode, Log printing is disabled in the formal mode. To enable and disable Log printing flexibly, some encapsulation needs to be performed on the native Log class.
  
In another case, when a program crashes, we hope to collect the cause of the exception for analysis. Therefore, we can save the Log to a file, in the directory created by the SD card program. You can also upload abnormal Log files to the server in the background of the program when the user is connected to the Internet, so that programmers can analyze and solve bugs.
  
Today, I will share with you a very useful LogUtils Log class in the project. This class is extracted from xUtils and slightly modified with annotations.
  
  Example:
We call some LogUtils methods in MainActivity. Check the number of rows.
  
 

Next, let's see if the Log printed on the console is the same as that called by MainActivity. The Log contains the name of this class and the oncreate method name, and the current number of rows has been reached;
 
Placement/bP1tLss6PSssTcv + placement + C1sbXEt72x46GjPGJyIC8 + DQqhoTwvcD4NCjxwcmUgY2xhc3M9 "brush: java;">// Allowed log printing type. The default value is true. If it is set to false, public static boolean allowD = true is not printed; public static boolean allowE = true; public static boolean allowI = true; public static boolean allowV = true; public static boolean allowW = true; public static boolean allowWtf = true;

The code is pasted below:

Package com. finddreams. log; import java. io. bufferedWriter; import java. io. file; import java. io. fileOutputStream; import java. io. IOException; import java. io. outputStreamWriter; import java. text. simpleDateFormat; import java. util. date; import java. util. formatter; import java. util. locale; import android. OS. environment; import android. text. textUtils; import android. util. log;/*** Log tool, similar to android. util. log. Tags are automatically generated. Format: * customTagPrefix: className. methodName (Line: lineNumber). * If customTagPrefix is null, only the following output is: className. methodName (Line: lineNumber ). * Http://blog.csdn.net/finddreams */public class LogUtils {public static String customTagPrefix = finddreams; // the prefix of the custom Tag, which can be the author's name private static final boolean isSaveLog = false; // whether to save the log to the SD card public static final String ROOT = Environment. getExternalStorageDirectory (). getPath () +/finddreams/; // the ROOT directory of the SD card, private static final String PATH_LOG_INFO = ROOT + info/; private LogUtils () {}// Allow Log Printing The default value is true. If it is set to false, public static boolean allowD = true is not printed; public static boolean allowE = true; public static boolean allowI = true; public static boolean allowV = true; public static boolean allowW = true; public static boolean allowWtf = true; private static String generateTag (StackTraceElement caller) {String tag = % s. % s (Line: % d); // placeholder String callerClazzName = caller. getClassName (); // get To the class name callerClazzName = callerClazzName. substring (callerClazzName. lastIndexOf (.) + 1); tag = String. format (tag, callerClazzName, caller. getMethodName (), caller. getLineNumber (); // replace tag = TextUtils. isEmpty (customTagPrefix )? Tag: customTagPrefix +: + tag; return tag;}/*** custom logger */public static CustomLogger customLogger; public interface CustomLogger {void d (String tag, string content); void d (String tag, String content, Throwable tr); void e (String tag, String content); void e (String tag, String content, Throwable tr ); void I (String tag, String content); void I (String tag, String content, Throwable tr); vo Id v (String tag, String content); void v (String tag, String content, Throwable tr); void w (String tag, String content); void w (String tag, string content, Throwable tr); void w (String tag, Throwable tr); void wtf (String tag, String content); void wtf (String tag, String content, Throwable tr ); void wtf (String tag, Throwable tr);} public static void d (String content) {if (! AllowD) return; StackTraceElement caller = getCallerStackTraceElement (); String tag = generateTag (caller); if (customLogger! = Null) {customLogger. d (tag, content);} else {Log. d (tag, content) ;}} public static void d (String content, Throwable tr) {if (! AllowD) return; StackTraceElement caller = getCallerStackTraceElement (); String tag = generateTag (caller); if (customLogger! = Null) {customLogger. d (tag, content, tr);} else {Log. d (tag, content, tr) ;}} public static void e (String content) {if (! AllowE) return; StackTraceElement caller = getCallerStackTraceElement (); String tag = generateTag (caller); if (customLogger! = Null) {customLogger. e (tag, content);} else {Log. e (tag, content) ;}if (isSaveLog) {point (PATH_LOG_INFO, tag, content) ;}} public static void e (String content, Throwable tr) {if (! AllowE) return; StackTraceElement caller = getCallerStackTraceElement (); String tag = generateTag (caller); if (customLogger! = Null) {customLogger. e (tag, content, tr);} else {Log. e (tag, content, tr);} if (isSaveLog) {point (PATH_LOG_INFO, tag, tr. getMessage () ;}} public static void I (String content) {if (! AllowI) return; StackTraceElement caller = getCallerStackTraceElement (); String tag = generateTag (caller); if (customLogger! = Null) {customLogger. I (tag, content);} else {Log. I (tag, content) ;}} public static void I (String content, Throwable tr) {if (! AllowI) return; StackTraceElement caller = getCallerStackTraceElement (); String tag = generateTag (caller); if (customLogger! = Null) {customLogger. I (tag, content, tr);} else {Log. I (tag, content, tr) ;}} public static void v (String content) {if (! AllowV) return; StackTraceElement caller = getCallerStackTraceElement (); String tag = generateTag (caller); if (customLogger! = Null) {customLogger. v (tag, content);} else {Log. v (tag, content) ;}} public static void v (String content, Throwable tr) {if (! AllowV) return; StackTraceElement caller = getCallerStackTraceElement (); String tag = generateTag (caller); if (customLogger! = Null) {customLogger. v (tag, content, tr);} else {Log. v (tag, content, tr) ;}} public static void w (String content) {if (! AllowW) return; StackTraceElement caller = getCallerStackTraceElement (); String tag = generateTag (caller); if (customLogger! = Null) {customLogger. w (tag, content);} else {Log. w (tag, content) ;}} public static void w (String content, Throwable tr) {if (! AllowW) return; StackTraceElement caller = getCallerStackTraceElement (); String tag = generateTag (caller); if (customLogger! = Null) {customLogger. w (tag, content, tr);} else {Log. w (tag, content, tr) ;}} public static void w (Throwable tr) {if (! AllowW) return; StackTraceElement caller = getCallerStackTraceElement (); String tag = generateTag (caller); if (customLogger! = Null) {customLogger. w (tag, tr) ;}else {Log. w (tag, tr) ;}} public static void wtf (String content) {if (! AllowWtf) return; StackTraceElement caller = getCallerStackTraceElement (); String tag = generateTag (caller); if (customLogger! = Null) {customLogger. wtf (tag, content);} else {Log. wtf (tag, content) ;}} public static void wtf (String content, Throwable tr) {if (! AllowWtf) return; StackTraceElement caller = getCallerStackTraceElement (); String tag = generateTag (caller); if (customLogger! = Null) {customLogger. wtf (tag, content, tr);} else {Log. wtf (tag, content, tr) ;}} public static void wtf (Throwable tr) {if (! AllowWtf) return; StackTraceElement caller = getCallerStackTraceElement (); String tag = generateTag (caller); if (customLogger! = Null) {customLogger. wtf (tag, tr);} else {Log. wtf (tag, tr) ;}} private static StackTraceElement getCallerStackTraceElement () {return Thread. currentThread (). getStackTrace () [4];} public static void point (String path, String tag, String msg) {if (isSDAva () {Date date = new Date (); simpleDateFormat dateFormat = new SimpleDateFormat (, Locale. SIMPLIFIED_CHINESE); dateFormat. applyPattern (yyyy ); Path = path + dateFormat. format (date) +/; dateFormat. applyPattern (MM); path + = dateFormat. format (date) +/; dateFormat. applyPattern (dd); path + = dateFormat. format (date) +. log; dateFormat. applyPattern ([yyyy-MM-dd HH: mm: ss]); String time = dateFormat. format (date); File file = new File (path); if (! File. exists () createDipPath (path); BufferedWriter out = null; try {out = new BufferedWriter (new OutputStreamWriter (new FileOutputStream (file, true); out. write (time ++ tag ++ msg +);} catch (Exception e) {e. printStackTrace ();} finally {try {if (out! = Null) {out. close () ;}} catch (IOException e) {e. printStackTrace () ;}}}/ *** recursively create a file based on the file path ** @ param file */public static void createDipPath (String file) {String parentFile = file. substring (0, file. lastIndexOf (/); File file1 = new File (file); File parent = new File (parentFile); if (! File1.exists () {parent. mkdirs (); try {file1.createNewFile ();} catch (IOException e) {e. printStackTrace () ;}}/ *** A little trick to reuse a formatter in the same thread */private static class ReusableFormatter {private Formatter formatter; private StringBuilder builder; public ReusableFormatter () {builder = new StringBuilder (); formatter = new Formatter (builder);} public String format (String msg, Object... args) {formatter. format (msg, args); String s = builder. toString (); builder. setLength (0); return s ;}} private static final ThreadLocal
  
   
Thread_local_formatter = new ThreadLocal
   
    
() {Protected ReusableFormatter initialValue () {return new ReusableFormatter () ;}}; public static String format (String msg, Object... args) {ReusableFormatter formatter = thread_local_formatter.get (); return formatter. format (msg, args);} public static boolean isSDAva () {if (Environment. getExternalStorageState (). equals (Environment. MEDIA_MOUNTED) | Environment. getExternalStorageDirectory (). exists () {return true;} else {return false ;}}}
   
  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.