Android|Integrate slf4j + logback as logging framework

Android|Integrate slf4j + logback as logging framework

Recently, when I was working on a log transformation for an Android APP, I wanted to meet the following requirements:

  • It is very convenient to use variable parameters to output logs;
  • Logs can be output to the console and files according to the level;
  • It can split log files according to date and file size, save logs for a specified number of days in a rolling manner, and automatically clean up old logs.

Based on this requirement, I searched for "Android log framework", and most netizens recommended logger, timber, xLog, etc., which looked good. However, based on my years of experience and habits in backend development, I learned more and found that the familiar log4j and logback have also been adapted on Android, so I finally decided to use slf4j + logback to achieve a consistent experience in front-end and back-end development.

Students who have done Java backend development are generally familiar with the combination of slf4j + logback, but students who have done Android development may not have heard of them. Therefore, this article will start from scratch and record how to integrate slf4j + logback as a logging framework in Android APP and use Lombok annotations to generate log objects.

Integrate slf4j + logback

logback-android Project address: https://github.com/tony19/logback-android

1. Add dependencies in the build.gradle file of the project/module:

 dependencies { implementation 'org.slf4j:slf4j-api:2.0.7' implementation 'com.github.tony19:logback-android:3.0.0' }

If it is a single-module project, you can add it directly in the app/build.gradle file. If it is a multi-module project, you can add it in the build.gradle file of a common module. Remember to change the implementation of slf4j-api to api so that it can be referenced by other modules.

2. Create a log configuration file app/src/main/assets/logback.xml:

 <configuration debug="false" xmlns="https://tony19.github.io/logback-android/xml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://tony19.github.io/logback-android/xml https://cdn.jsdelivr.net/gh/tony19/logback-android/logback.xsd" > <property name="LOG_DIR" value="${EXT_DIR:-${DATA_DIR}}/test/log"/> <appender name="logcat" class="ch.qos.logback.classic.android.LogcatAppender"> <tagEncoder> <pattern>%logger{12}</pattern> </tagEncoder> <encoder> <pattern>[%-20thread] %msg</pattern> </encoder> </appender> <appender name="local_file" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>${LOG_DIR}/test.log</file> <encoder> <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern> </encoder> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <fileNamePattern>${LOG_DIR}/test.%d.log</fileNamePattern> <maxHistory>15</maxHistory> </rollingPolicy> </appender> <root level="DEBUG"> <appender-ref ref="logcat" /> </root> <root level="INFO"> <appender-ref ref="local_file" /> </root> </configuration>

The above configuration means that logs of DEBUG and above levels are output to the console, and logs of INFO and above levels are output to files. Files are segmented by date, and logs of up to 15 days are retained.

You can configure as needed, for example, you can limit the size of a single file, customize the format of log output, etc.

In the project's Wiki, it is mentioned that one thing that Android developers are more concerned about is that the log has a save path. You can specify an absolute path or use a variable, for example:

  • ${DATA_DIR} represents Context.getFilesDir();
  • ${EXT_DIR} represents Context.getExternalFilesDir(null);
  • ${EXT_DIR:-${DATA_DIR}} means use EXT_DIR if EXT_DIR is available, otherwise use DATA_DIR;
  • ${PACKAGE_NAME} represents the package name;
  • ${VERSION_NAME} represents the version name;
  • ${VERSION_CODE} represents the version number.

3. You can start using slf4j's API to print logs:

 import org.slf4j.Logger; import org.slf4j.LoggerFactory; // 声明logger Logger log = LoggerFactory.getLogger(MainActivity.class); // 打印日志log.info("hello world"); log.info("number {}, boolean {}, string {}, object {}", 1, true, "string", new Object());

Run the app and you can see that the logs are output to logcat and files in the corresponding locations.

When you have questions about the configuration and need to debug, you can change debug="false" in the above configuration file to debug="true", so that logback will output detailed information to help us locate the problem.

Generate log objects using Lombok annotations

In step 3 of the previous section, in each class that needs to use the logger, you need to manually declare the logger, such as Logger log = LoggerFactory.getLogger(MainActivity.class);, which is not very convenient.

Here we can use Lombok annotations to simplify this step and automatically generate logger objects.

Lombok officially provides integration instructions for the Android platform: https://projectlombok.org/setup/android.

Based on the Android Studio environment, there are actually only two steps to do.

1. Install the Lombok plugin:

Settings -> Plugins -> Search for Lombok -> Install

Note: For Android Studio versions 2020.3.1 - 2022.3.1, the JetBrains official plugin market cannot search for compatible versions of the Lombok plugin. You can refer to https://gitee.com/sgpublic/lombok-plugin-repository for a solution.

2. Add the following content to the build.gradle file of the module you need to use:

 dependencies { compileOnly 'org.projectlombok:lombok:1.18.30' annotationProcessor 'org.projectlombok:lombok:1.18.30' }

Then, you can use the @Slf4j annotation to automatically generate a logger object. Now the usage is simplified to this:

 @Slf4j public class Test { public void test() { log.info("hello world"); } }

summary

Well, the above is the record of integrating slf4j + logback in Android. So far, I have "unified" the usage of Java backend and Android client to print logs, and made a small step forward in avoiding the "schizophrenia" caused by multi-project maintenance.

The code samples listed in this article have been uploaded to GitHub, address: https://github.com/mzlogin/AndroidPractices/tree/master/android-studio/LogbackDemo

<<:  Apple iOS / iPadOS 17.1 official version released: support AirDrop Internet transmission, compatible with USB-C Apple Pencil, etc.

>>:  How much do you know about Android AOP?

Recommend

@North Pole Rabbit: Cute thing, you really don’t mind the cold…

Rabbits in the world are classified into eight ge...

If you see these creatures on the beach, don't touch them!

During the hot summer, many people like to go to ...

Zero-based easy entry to the way of love 2.0

1. Wrong concept of love: thinking that only mone...

Ionic 1.0.0 released, HTML5 mobile application framework

Ionic 1.0.0 released, codenamed "uranium-uni...

Three secrets of brand promotion on Xiaohongshu

With over 100 million monthly active users and 10...

Is Tik Tok restricting influencers from promoting products?

In the past few months, Douyin has been imposing ...

Android 12L increases Chrome usage 18 times on large-screen devices

A few months ago, Android 12L was released as a B...

4K becomes the standard for TVs, but there are differences in standard names

4K TV is a TV with a physical screen resolution o...

Adding more oil to stir-fried carrots will help nutrients be better absorbed?

Carrots are a nutritious vegetable. The carotenoi...

How did “GunGun” turn himself into a “living fossil”?

Do you know the answers to these questions about ...