First of all, please don’t spray me. If anything is wrong, I hope you can comment on it below, and then I will correct it.

— — — — — — — — — — — — — — — — — — — — — — — I’m not feeling well is not split your — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — –

“Every time you log in production, a puppy dies.” — Jake Wharton

In the Android project, when debugging the program, I usually log to check the relevant information, but I used the system’s own log to print.

Come down to two problems: < information display >, < information storage >, on these two problems we specifically see how to solve

— — — — — — — — — — — — — — — — — — — — — — — the main body split jun — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — –

1. Information display

V (tag,”XXXX”); When more and more projects. When you look at the log, you don’t know which file or even which code generated the log information, and then you have to go back and find the code to write the log. And it’s going to take a lot of log information out of your eyes. At this time, we can only look for a needle in a haystack, or the keyword tag to search. The answer is no, of course. (This B makes me tired)

Therefore, based on this situation, I searched online and found many recommendations for Logger, so I used Logger.

See what Logger has to offer:

1.Thread information

2.Class information

3.Method information

4.Pretty-print for json content

5.Pretty-print for new line “\n”

6.Clean output

7.Jump to source

Logger source address: github.com/orhanobut/l… In the first place in the build. Introduce the Logger gradle: compile ‘com. Orhanobut: Logger: 1.15’ and then directly in the code you can use the Logger. First look at the effect:

public class Act_Logger extends Activity{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Logger.init(" tagName "); String name = "billy"; Logger.d(" Hello, so-and-so "); Logger.d(" hello, %s",name); getString(name); ArrayList list = new ArrayList(); list.add(new UserBean("user1",1)); list.add(new UserBean("user2",2)); list.add(new UserBean("user3",3)); list.add(new UserBean("user4",4)); Logger.d(list); } public void getString(String name){logger. e(" hello, %s",name); }}Copy the code



PNG Screen Snapshot 2016-11-24 11.40.22 am.png

We can see the name of the thread in the Log information, which class, which method, it’s displayed, and the Log information is beautiful. And you can click to jump to the corresponding code. Support Array, Map, Set and List at the same time.




description.png

What? You don’t think that’s any good? So if you want to view a JSON message, the original layout of the JSON in the log is not wrong (keng) (die), now look at the json message display in the Logger.




logger-log.png

Suddenly I feel superior. Show it to your colleagues.

There’s a little feature here. Why

Logger.d(" Hello, so-and-so "); Logger.d(" hello, %s",name);Copy the code

All can be supported.

That’s because they all get called eventually

private String createMessage(String message, Object... args) {      
    return args == null || args.length == 0 ? message : String.format(message, args);
}Copy the code

And then I print the string using the system Log.

Mainly I thought the createMessage snippet would be handy as a method for util tools. I used it for my own project.

2. Information storage

Log if we use a mobile phone connected to the computer debugging, this time is convenient, you can view information while operating, but one thousand is installed on his mobile phone to a customer, or an android device, you have a demand to know his Log information, then will you connected to the computer operation and review the Log information?

Here on the net I looked again below, still old routine, discovery everybody recommends Timber. Then I used Timber. This is actually a package library of logs, so without further ado. Take off your clothes and go straight to it.

Old routine, first attached Timber source address: github.com/JakeWharton…

In the build. Introducing Timber grade: compile ‘com. Jakewharton. Timber: Timber: 4.3.1’

In the custom class that inherits Application, set Timber tree, actually Timber is similar to managing a forest, the specific use of which tree is decided by your own side. Timber, for example, is a DebugTree class.

@Override public void onCreate() { super.onCreate(); If (buildconfig.debug) {Timber. Plant (new Timber.DebugTree()); } else { Timber.plant(new FileLoggingTree()); }}Copy the code

Then it’s ready to use

Timber.tag("code_gg");        
Timber.d("test Timber %d",10);Copy the code

> < p style = “text-indent: 22px; line-height: 22px; Like writing to a file. Here I first write a silly white sweet FileLoggingTree class, just for reference. We’ll use another third party later, which is even more powerful.

String CacheDiaPath = context.getcacheDir ().tostring ();

private static class FileLoggingTree extends Timber.Tree { @Override protected void log(int priority, String tag, String message, Throwable t) { if (TextUtils.isEmpty(CacheDiaPath)) { return; } File file = new File(CacheDiaPath + "/log.txt"); Log.v("dyp", "file.path:" + file.getAbsolutePath() + ",message:" + message); FileWriter writer = null; BufferedWriter bufferedWriter = null; try { writer = new FileWriter(file); bufferedWriter = new BufferedWriter(writer); bufferedWriter.write(message); bufferedWriter.flush(); } catch (IOException e) {log.v ("dyp", "failed to save file "); e.printStackTrace(); } finally { if (bufferedWriter ! = null) { try { bufferedWriter.close(); } catch (IOException e) { e.printStackTrace(); } } } } }Copy the code

The log method contains four parameters: int priority, String tag, String message, Throwable t. I simply took the message parameter and saved it to the log. TXT file in the path I specified. Of course Timber can encapsulate itself.

There are trees that record crashes, for example

/** * A tree which logs important information for crash reporting. */ private static class CrashReportingTree extends Timber.Tree { @Override protected void log(int priority, String tag, String message, Throwable t) { if (priority == Log.VERBOSE || priority == Log.DEBUG) { return; } FakeCrashLibrary.log(priority, tag, message); if (t ! = null) { if (priority == Log.ERROR) { FakeCrashLibrary.logError(t); } else if (priority == Log.WARN) { FakeCrashLibrary.logWarning(t); }}}}Copy the code

Of course I thought it was pretty low. Then I looked at some third parties that could write logs to files. Logback-android found. -files-sqlite databases -logcat -sockets -syslog-email

So we can use Timber with logback-Android to simulate store to file.

Logback-android source code: github.com/tony19/logb…

Step 1: Introduce Logback-Android

Gradle

// only needed for SNAPSHOT builds repositories { maven { url 'https://oss.sonatype.org/content/repositories/snapshots' Dependencies}} {the compile 'org. Slf4j: slf4j - API: 1.7.21' compile 'com. Making. Tony19: logback - android - core: 1.1.1-6' compile 'com. Making. Tony19: logback - android - classic: 1.1.1-6'}Copy the code

Step 2: Create a logback. XML file in the following location. By default, the path and file name are fixed




Paste_Image.png

Step 3: Configure the Logback file




    
    

    
    

    
    
        
            %-5relative [%thread][%file:%M:%line] - %msg%n
        
    

    
    
        
        true
        
        true
        
        ${LOG_DIR}/base.log
        
        
            
            %date [%thread] %-5level %logger{36} [%file:%line] - %msg%n
        
    

    
    
        ${LOG_DIR}/base.roll.${today}.log
        true
        
            %date %-5relative [%thread] %-5level %logger{36} [%file:%M:%line] - %msg%n
            
        

        
            ${LOG_DIR}/base.roll.%d{yyyy-MM-dd}.log
            
            7
        

        
        
            10MB
        
    

    
    
        
    

    
    
        
    

    
    
    
    
    
    

    

    
    
    
    
    

    
    
    
    
    
    
Copy the code

Log information saved in a file:




Paste_Image.png

Now you can write a tree for Timber using logback-Android:

public class FileLoggingTree extends Timber.DebugTree { static Logger mLogger = LoggerFactory.getLogger(FileLoggingTree.class); @Override protected void log(int priority, String tag, String message, Throwable t) { if (priority == Log.VERBOSE) { return; } String logMessage = tag + ": " + message; switch (priority) { case Log.DEBUG: mLogger.debug(logMessage); break; case Log.INFO: mLogger.info(logMessage); break; case Log.WARN: mLogger.warn(logMessage); break; case Log.ERROR: mLogger.error(logMessage); break; }}}Copy the code

Timber. Plant (new FileLoggingTree()); That’s it.