Android Klog Source Code Analysis
-
- Android Klog Source Code Analysis
-
- Code structure
- Detailed analysis
- Baselog
- FileLog
- Jsonlog
- Xmllog
- Core file Klogjava Analysis
- Problems encountered
Always use this library. But no detailed study. Let's look into it today. Address of the library:
Klog, thank the author here first. Great!
Code structure
The structure of the entire code is very easy. For example, the following:
library klog BaseLog.java FileLog.java JsonLog.java XmlLog.java KLog.java KLogUtil.java
A total of six files:
- Baselog.java, support for major log printing
- Filelog.java. Supports saving log as a file
- Jsonlog.java, supports printing JSON objects and JSON arrays
- Xmllog.java, supports printing of log in XML form
Detailed Analysis Baselog
Two methods:
Public class baselog { Private Static Final intMax_length =4000; Public Static void Printdefault(intType, string tag, string msg) {intindex =0;intLength = Msg.length ();intCountofsub = Length/max_length;if(Countofsub >0) {//over specified length, acne print. This avoids the default log length limit for the system. for(inti =0; i < countofsub; i++) {String sub = msg.substring (index, index + max_length); Printsub (type, tag, sub); Index + = max_length; } printsub (type, tag, msg.substring (index, length));//Print remainder part}Else{printsub (type, tag, msg); } }Private Static void printsub(intType, string tag, string sub) {Switch(type) { CaseKLOG.V:LOG.V (tag, sub); Break; CaseKLOG.D:LOG.D (tag, sub); Break; CaseKLOG.I:LOG.I (tag, sub); Break; CaseKLOG.W:LOG.W (tag, sub); Break; CaseKLOG.E:LOG.E (tag, sub); Break; CaseKLOG.A:LOG.WTF (tag, sub); Break; } }}
This breaks the Android system's log word limit, which in fact exceeds the word limit. Using the method of sub-printing to print, the other code does not do analysis, relatively simple.
FileLog
Three methods
Public class filelog { Private Static FinalString File_prefix ="Klog_";Private Static FinalString File_format =". Log";/** * @param Tag log tag * @param targetdirectory log File Save dir * @p Aram fileName Log name * @param headstring log file header * @param msg Log file Log content body * / Public Static void Printfile(String tag, File targetdirectory, @Nullable string fileName, String headstring, String msg) {filename = (filename = =NULL) ? GetFileName (): FileName;if(Save (TargetDirectory, FileName, msg)) {LOG.D (tag, headstring +"Save Log success!" Location is >>> "+ Targetdirectory.getabsolutepath () +"/"+ FileName); }Else{LOG.E (tag, headstring +"Save log fails!"); } }/** * @param dic log File Save dir * @param fileName og file name * @param Msg log file Log content body * @return True if save success */ Private Static Boolean Save(File dic, @NonNull string fileName, String msg) {File File =NewFile (DIC, fileName);Try{OutputStream OutputStream =NewFileOutputStream (file); OutputStreamWriter OutputStreamWriter =NewOutputStreamWriter (OutputStream,"UTF-8"); Outputstreamwriter.write (msg); Outputstreamwriter.flush (); Outputstream.close ();return true; }Catch(FileNotFoundException e) {E.printstacktrace ();return false; }Catch(Unsupportedencodingexception e) {E.printstacktrace ();return false; }Catch(IOException e) {E.printstacktrace ();return false; }Catch(Exception e) {E.printstacktrace ();return false; } }/** * When the file name is not set, randomly generate a file name * * @return default file name */ Private StaticStringGetFileName() {Random random =NewRandom ();returnFile_prefix + long.tostring (system.currenttimemillis () + Random.nextint (10000). SUBSTRING (4) + File_format; }}
Jsonlog
Jsonlog is simpler, there is only one way (this baby once thought that JSON printing would be very troublesome)
Public class jsonlog { Public Static void Printjson(string tag, string msg, String headstring) {String message;Try{if(Msg.startswith ("{")) {//Working with JSON objectsJsonobject Jsonobject =NewJsonobject (msg); Message = jsonobject.tostring (klog.json_indent); }Else if(Msg.startswith ("[")) {//Working with JSON arraysJsonarray Jsonarray =NewJsonarray (msg); Message = jsonarray.tostring (klog.json_indent); }Else{message = MSG; } }Catch(Jsonexception e) {message = MSG; } klogutil.printline (Tag,true);//Call formatting methodMessage = headstring + klog.line_separator + message; String[] lines = Message.split (klog.line_separator); for(String line:lines) {LOG.D (tag,"║"+ line); } klogutil.printline (Tag,false);//Call formatting method}}
Xmllog
Two methods:
Public class xmllog { /** * Print XML * * @param Tag log tag * @param XML XML content * @param headstring File header * / Public Static void Printxml(string tag, string xml, String headstring) {if(XML! =NULL{XML = Xmllog.formatxml (XML); XML = headstring +"\ n"+ xml; }Else{XML = headstring + klog.null_tips; } klogutil.printline (Tag,true); String[] lines = Xml.split (klog.line_separator); for(String line:lines) {if(! Klogutil.isempty (line)) {LOG.D (tag,"║"+ line); }} klogutil.printline (tag,false); }/** * @param inputxml XML content * @return formatted XML String */ Private StaticStringFormatxml(String inputxml) {Try{Source Xmlinput =NewStreamsource (NewStringReader (Inputxml)); Streamresult XMLOutput =NewStreamresult (NewStringWriter ()); Transformer Transformer = Transformerfactory.newinstance (). Newtransformer (); Transformer.setoutputproperty (Outputkeys.indent,"Yes"); Transformer.setoutputproperty ("{http://xml.apache.org/xslt}indent-amount","2"); Transformer.transform (Xmlinput, xmloutput);returnXmloutput.getwriter (). toString (). Replacefirst (">",">\n"); }Catch(Exception e) {E.printstacktrace ();returnInputxml; } }}
Careful you will find. Whether it's in JSON or XML form. Calls are system-native methods to process data, so it is also convenient to familiarize yourself with the methods provided by Java (or Android). Ha ha.
The klogutil used above, such as the following:
Public class klogutil { Public Static Boolean IsEmpty(String line) {returnTextutils.isempty (line) | | Line.equals ("\ n") || Line.equals ("\ T") || Textutils.isempty (Line.trim ()); } Public Static void PrintLine(String tag,BooleanIstop) {if(Istop) {LOG.D (tag,"╔═══════════════════════════════════════════════════════════════════════════════════════"); }Else{LOG.D (tag,"╚═══════════════════════════════════════════════════════════════════════════════════════"); } }}
Core file Klog.java Analysis
The method mainly provides different overloads similar to the System log method, which I want to talk about is the class name, method name, line number and so on that gets the log in detail. It is related to this method of wrappercontent.
Private StaticString[]wrappercontent(intStacktraceindex, String tagstr, Object ... objects) {stacktraceelement[] StackTrace = Thread.CurrentThread (). Getsta Cktrace (); Stacktraceelement targetelement = Stacktrace[stacktraceindex]; String className = Targetelement.getclassname ();//Get class namestring[] ClassNameInfo = Classname.split ("\\.");//First form if(Classnameinfo.length >0) {ClassName = Classnameinfo[classnameinfo.length-1] + SUFFIX; }if(Classname.contains ("$")) {//Another formClassName = Classname.split ("\\$")[0] + SUFFIX; } String MethodName = Targetelement.getmethodname ();//Get method name intlinenumber = Targetelement.getlinenumber ();//Get your line number if(LineNumber <0) {linenumber =0; } String tag = (Tagstr = =NULL? CLASSNAME:TAGSTR);if(Misglobaltagempty && Textutils.isempty (tag)) {tag = Tag_default; }Else if(!misglobaltagempty) {tag = Mglobaltag; }//Get message bodyString msg = (Objects = =NULL) ? Null_tips:getobjectsstring (objects); String headstring ="[ ("+ ClassName +":"+ linenumber +")#"+ MethodName +" ] ";return NewString[]{tag, MSG, headstring}; }/** * Get message body * * @param Objects Message Object array * @return message body String * / Private StaticStringgetobjectsstring(Object ... objects) {if(Objects.length >1) {StringBuilder StringBuilder =NewStringBuilder (); Stringbuilder.append ("\ n"); for(inti =0; i < objects.length; i++) {Object object = Objects[i];if(Object = =NULL) {stringbuilder.append (PARAM). Append ("["). append (i). Append ("]"). Append (" = "). Append (NULL). Append ("\ n"); }Else{stringbuilder.append (PARAM). Append ("["). append (i). Append ("]"). Append (" = "). Append (Object.ToString ()). Append ("\ n"); } }returnStringbuilder.tostring (); }Else{Object object = objects[0];returnObject = =NULL?
NULL : object.toString(); } }
Analysis done, is not very easy, suppose you looked at the code of this library. You would think my analysis was superfluous.
Problems encountered
When you use Klog to print JSON-form information. Assuming that the network request is asynchronous, it causes the Klog.json print format to appear garbled. That is, a result has not been completely printed out. One on the inside will start printing, this should be the problem of concurrency, and then I will be on the basis of klog to optimize the problem.
Android Klog Source Code Analysis