Android log Print class Logutils, able to navigate to the class name, method name, and number of rows where the error occurred and save the log file

Source: Internet
Author: User
Tags dateformat locale log log return tag

Android log Print class Logutils, able to navigate to the class name, method name, and number of rows where the error occurred and save the log file

In development, we often use print log to debug our application. In Java we often use Method System.out.println () to print logs in the console for our debugging. There is a dedicated class log in Android to enable the printing of logs under the Android system, which makes it easier for us to locate problems in the program.

However, the log class provided by Android is not very convenient for actual project use. When the program has an error, what we want most is that the log class can help us navigate to which method of the class, even if there is an error in that line. This will provide us with a lot of debugging convenience.

At the same time, we should also think that for the sake of security of the application, before the app is officially launched, we should turn off the function of the print log to prevent others from using log to hack your application. Production mode under the print log, the formal mode of the function of the print logs off, to achieve the flexibility of log closed and open, also need to be on the original log class to do some encapsulation.

There is also a time when our program problem crashes, we want to be able to collect the cause of the exception for analysis, so you can save the log log to a file, placed in the SD card program created by the directory. can also be in the case of user networking, in the background of the program to send out the Exception Log log file upload to the server, convenient for the programmer to analyze and solve the bug.

Today, I would like to share with you a very useful log class logutils, which is extracted from the xutils, slightly modified, and commented.

  Example:
We call some of the methods in the Logutils in Mainactivity, and look at the number of rows.

 

Then look at the console print log is not as mainactivity call, the log has the name of the class and the OnCreate method name, and the current number of rows;

See log log is not very convenient to locate the problem in the program, the exception can be quickly located. Then the following log type is set to False anywhere in the program, and the log is not printed, which is quite convenient to use.
 

   Allow print log type, default is True, set to False to not printPublicstatic boolean allowd = true; Span class= "Hljs-keyword" >public static boolean AllowE = true; public static boolean AllowI = Span class= "Hljs-keyword" >true; public static boolean AllowV = Span class= "Hljs-keyword" >true; public static boolean AllowW = Span class= "Hljs-keyword" >true; public static boolean ALLOWWTF = Span class= "Hljs-keyword" >true;             

The code is posted below:

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. tag automatically generated, format: * CustomTagPrefix:className.methodName (Line:linenumber), * customtagprefix is empty when only output: Classname.methodname ( Line:linenumber). * Http://blog.csdn.net/finddreams */public class Logutils {public static String Customtagprefix = "finddreams";//Custom The tag prefix, which can be the author name private static final Boolean issavelog = true; Whether to save the log to the SD card public static final String ROOT = Environment.getexternalstoragedirectory (). GetPath () +/F Inddreams/";    The root directory in the SD card is private static final String Path_log_info = root + "info/"; Private Logutils () {}//Allow print log type, default is True, set to False to not print public static Boolean allowd = true;   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 C Allerclazzname = Caller.getclassname ();        Gets 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);        void 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 (). Getstacktra    CE () [4]; public static void point (string path, string tag, string msg) {if (Issdava ()) {Date date = new Da            Te ();            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, tr                UE));            Out.write (time + "+ tag +" + msg + "\ r \ n");            } catch (Exception e) {e.printstacktrace ();                    } finally {try {if (out! = null) {out.close ();                }} catch (IOException e) {e.printstacktrace (); }}}}/** * Create files recursively based on file path * * @param file */public static void Createdippat        H (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 Reusabl        Eformatter {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<reusableformatter> Thread_local_formatter = new Threadlocal<reusablefo Rmatter> () {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; }    }}

Http://files.cnblogs.com/files/tc310/LogUtils.rar

Android log Print class Logutils, able to navigate to the class name, method name, and number of rows where the error occurred and save the log file

Related Article

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.