Log4j Implementation in Android

六眼飞鱼酱① 提交于 2019-12-21 06:04:55

问题


I am new to android development.I want to write logs to one file in SD Card.How can i do this using Log4j.What all are the steps to Implement Log4j.I read many atricles.But none of them describing how to configure and implement it.Can anyone please explain how to do this in android in simple words.


回答1:


You should look at logback (the next generation of log4j). Use the FileAppender or RollingFileAppender.

Instructions:

  1. Add slf4j-api-1.6.6.jar and logback-android-1.0.6-2.jar to your classpath.

  2. Create the file assets/logback.xml in your project (or use the AndroidManifest.xml...see example), containing the following configuration:

<configuration>
  <appender name="FILE" class="ch.qos.logback.core.FileAppender">
    <file>/sdcard/testFile.log</file>
    <append>true</append>
    <encoder>
      <pattern>%-4relative [%thread] %-5level %logger{35} - %msg%n</pattern>
    </encoder>
  </appender>

  <root level="DEBUG">
    <appender-ref ref="FILE" />
  </root>
</configuration>

Note: Since the specified path is on SD, make sure to use WRITE_EXTERNAL_STORAGE permission. You can instead specify a different path where you already have write permissions.

Your Java code, which contains the SLF4J logging calls, now logs all events at or above the DEBUG level to the /sdcard/testFile.log.

Example Java:

package com.example;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.example.R;
import android.app.Activity;
import android.os.Bundle;

public class HelloAndroidActivity extends Activity {
    static private final Logger LOG =
                       LoggerFactory.getLogger(HelloAndroidActivity.class);

    @Override
    public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);

       //
       // Based on the configuration above, these log statements
       // are written to /sdcard/testFile.log
       //
       LOG.info("Hello Android!");
       LOG.debug("reply: {}", Example.hello());
    }
}

class Example {
    static private final Logger LOG =
                     LoggerFactory.getLogger(Example.class);

    static public String hello() {
        LOG.trace("entered hello()");
        return "Hi there!";
    }
}


来源:https://stackoverflow.com/questions/11826025/log4j-implementation-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!