Android Open Source Log library Logger use tutorial

Source: Internet
Author: User
Tags tag name

Reprint Please specify source: http://blog.csdn.net/like_program/article/details/52986553

What is 1.Logger?

In our daily development, there must be a need to deal with log, recall how we use log: first define a static constant Tag,tag value is usually the class name of the current class, and then where the need to print Log, called Log.d(TAG, "要打印的内容") . Every time a new write a class, you have to write a TAG, which also forget, the most bitter force is that the project on the line, but also manually to each Log comment off ...

Of course, some students may want to say, this is nothing, I encapsulated a Log not on the line. But for the novice, the package has a certain degree of difficulty, if there is a ready-made open-source library can be used directly to the good.

Daniel of Github, of course, also noticed the situation, so the open source log library Logger was born.

Logger's Github homepage: https://github.com/orhanobut/logger

Logger provides the following features:

    • Thread's information
    • Class of information
    • Methods of information
    • humanized output of JSON text
    • humanized output of line breaks
    • Simple output
    • Jump from log to source

Logger and native log the biggest difference is: Logger print out the log at a glance, citing the image on the official Github, look at the difference between the native log and the Logger print log:

Log printed by native log:

Logger Printed logs:

As you can see, the Logger print log ignores all of the extra logs, shows only the logs that are useful to us, and also keeps the log boxes up so we can see more comfortable. I have to say, Logger do is too human.

Logger use method is not difficult, Logger Open Source Library's Github home page wrote a very detailed use method, English also passable classmate can go directly to Logger Homepage View use method, have English phobia of classmate, can through this blog to learn.

Use of 2.Logger

Open Android Studio and create a new Loggertest project.

1. Import dependencies

In dependencies in Loggertest/app/build.gradle, import dependencies with the following code:

{    compile ‘com.orhanobut:logger:1.15‘}

Then Android Studio should pop up Sync Now , which is where Arrow 1 points to,

If it pops up Sync Now , click on it and if it doesn't pop up, click on the arrow 2 to point to the option.

Once the Grade is built, we can use the logger.

2. Simple to use

Logger use the same method as the native Log, let's try to print a simple text first.

Modify the OnCreate () method in Mainactivity.java with the following code:

@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    Logger.d("执行了 onCreate");}

Hey, why didn't you write TAG? In fact, Logger has its own default tag, the default tag is PRETTYLOGGER , we run the program, look at the output log:

We can see that the logs have been successfully output, and more beautiful than the original log output we used before, the log information at a glance. The arrows point to the Logger default tag, so if you want Logcat to show only your own printed logs, you can add the default tag in the log filter.

or add it directly in the filter box:

3. Print more types of data

Logger also supports printing data in formats such as Json,xml.

1.JSON type Data
Private String json_content = "{\"Weatherinfo\":{\"City\":\"Beijing\",\"Cityid\":\"101010100\"," +            "\"Temp\":\"18\",\"Wd\":\"Southeast Wind\",\"Ws\":\"Level 1\",\"Sd\":\"17%\ ", \" wse\ ": \" 1\ "," +"\"Time\":\"17:05\",\"Isradar\":\"1\",\"Radar\":\"Jc_radar_az9010_jb\"," +            "\"Njd\":\"No live\",\"Qy\":\"1011\",\"Rain\":\"0\"}}"; @Overrideprotected void OnCreate (Bundle savedinstancestate){Super.oncreate (savedinstancestate);    Setcontentview (R.layout.activity_main); Logger.json (json_content);}

2.XML type Data
Private String xml_content = "<china dn=\"Nay\"><city quname=\"Heilongjiang\"Pyname=\"Heilongjiang\""+" cityname=\"Harbin\"state1=\"1\"State2=\"1\"Statedetailed=\"Cloudy\"/><city quname=\"Jilin\""+" pyname=\"Jilin\""+" cityname=\"Changchun\"state1=\"0\"State2=\"0\"Statedetailed=\"Clear\"/><city quname=\"Liaoning\""+" pyname=\"Liaoning\""+" cityname=\"Shenyang\"state1=\"1\"State2=\"0\"Statedetailed=\"Cloudy With a sunny turn\"/><city "+" quname=\"Hainan\"Pyname=\"Hainan\""+" cityname=\"Haikou\"state1=\"22\"State2=\"21st\"Statedetailed=\"Medium to heavy rain turns small to cloudy\"/></china> "; @Overrideprotected void OnCreate (Bundle savedinstancestate){Super.oncreate (savedinstancestate);    Setcontentview (R.layout.activity_main); Logger.xml (xml_content);}

3.List type Data
@Overrideprotected voidOnCreate (Bundle savedinstancestate) {Super.OnCreate (savedinstancestate); Setcontentview (R.Layout.Activity_main);//List type data    List<String> List = NewArrayList<>();List.Add"Hello");List.Add"World"); Logger.DList);}

4.MAP type Data
@Overrideprotected voidOnCreate (Bundle savedinstancestate) {Super.OnCreate (savedinstancestate); Setcontentview (R.Layout.Activity_main);//MAP type data    Map<String,String> Map = NewHashMap<>();Map.Put"Key_hello","Hello");Map.Put"Key_world","World"); Logger.DMap);}

5.Set type Data
@Overrideprotected voidOnCreate (Bundle savedinstancestate) {Super.OnCreate (savedinstancestate); Setcontentview (R.Layout.Activity_main);//Set type data    Set<String> Set = NewHashSet<>();Set.AddNew String("Hello"));Set.AddNew String("World")); Logger.DSet);}

4. String formatting
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    Logger.d("hello %s %d""world"5);}

5. Custom TAG

If you are not satisfied with the default tag, you can also define a tag yourself, only need to call once Logger.init () on the line. Because you only need to call once, you can complete the initialization of Logger in application.

New MyApplication inherits the application code as follows:

publicclass MyApplication extends Application {    privatestatic"LoggerTest";    @Override    publicvoidonCreate() {        super.onCreate();        Logger.init(TAG);    }}

To modify the properties of application in Androidmanifest.xml, add android:name=".MyApplication" the Androidmanifest.xml code as follows:

<applicationandroid:name=". MyApplication "android:allowbackup=" true "android:icon=" @mipmap/ic_launcher "  Android:label= "@string/app_name"android:supportsrtl="true"  Android:theme="@style/apptheme">                            <activity android:name=". Mainactivity ">        <intent-filter>            <action android:name="Android.intent.action.MAIN"/>            <category android:name="Android.intent.category.LAUNCHER"/>        </intent-filter>    </activity></Application>

So when the App starts, it initializes our custom MyApplication. Then we print the log in Mainactivity's OnCreate () to see if the custom TAG is in effect.

@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    Logger.d("hello world");}

As you can see, our custom TAG is already in effect. Then some students may have doubts, if I do not want to use this tag, if temporarily want to change a tag with it, of course there is a way, call Logger.t("临时TAG名").d() , you can use the temporary tag print log.

@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    Logger.t("MyTag").d("hello world");}

As you can see, the temporary tag name is appended to the custom tag.

6. Set no print log

Previously said, the log is only developed when the need to use, wait until the project on-line can not be used. Logger Of course also considering this, by setting Logger.init(TAG).logLevel(LogLevel.NONE) can be set to not print the log. The default parameter of the LogLevel () method is LogLevel.FULL to print all logs. To modify the MyApplication OnCreate () method:

@OverridepublicvoidonCreate() {    super.onCreate();    Logger.init(TAG).logLevel(LogLevel.NONE);}

Run it and you can see that Logger does not have a print log.

7. Print Exception

Logger print Exception, can see very clearly Exception information, here we write an array out of bounds exception:

@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    intnewint[3];    try {        a[43;    catch (Exception e) {        "message");    }}

8. More Personalized Settings

Logger also has some personalization settings, such as

Logger.init(TAG)        .methodCount(3// 方法栈打印的个数,默认是 2        .// // 隐藏线程信息,默认显示        .methodOffset(2// 设置调用堆栈的函数偏移值,默认是 0        .logAdapter(new// 自定义一个打印适配器

Interested students can go to Logger's Github home page to see more usage of Logger.

SOURCE download

Android Open Source Log library Logger use tutorial

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.