Android程序加入日志文件

坚强是说给别人听的谎言 提交于 2020-08-08 21:57:33
import android.os.Environment;

import com.emh.simplepdacall.constant.Constants;

import org.apache.log4j.Level;

import java.io.File;

import de.mindpipe.android.logging.log4j.LogConfigurator;

public class Log4JUtil {

    private static final String APP_NAME = "com.compnayName.appName";
    private static final String LOG_DIR = Environment.getExternalStorageDirectory().getPath()
            + File.separator + APP_NAME + File.separator + "Log" + File.separator;
    private static final String LOG_FILE_PATH = LOG_DIR + "log" + ".txt";
    private static final String LOG_FILE_PATTERN = "[%-d{yyyy-MM-dd HH:mm:ss}][Class: %c.%M(%F:%L)] %n[Level: %-5p] - Msg: %m%n";
    private static final Level LOG_LEVEL_DEBUG = Level.ALL;
    private static final Level LOG_LEVEL_RELEASE = Level.INFO;

    public static void configuration() {
        LogConfigurator configurator = new LogConfigurator();
        if (Constants.IS_DEBUG) {
            setLogToDebug(configurator);
        } else {
            setLogToRelease(configurator);
        }
        configurator.setFileName(LOG_FILE_PATH);
        configurator.setLevel("org.apache", Level.ERROR);
        configurator.setFilePattern(LOG_FILE_PATTERN);
        configurator.setMaxFileSize(1024 * 1024 * 5);
        configurator.setImmediateFlush(true);
        configurator.configure();
    }

    public static void createDir(String path) {
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    private static void setLogToDebug(LogConfigurator config) {
        config.setRootLevel(LOG_LEVEL_DEBUG);
    }

    private static void setLogToRelease(LogConfigurator config) {
        config.setRootLevel(LOG_LEVEL_RELEASE);
    }
}

使用

public class App extends Application {

    private static final String TAG = App.class.getSimpleName();

    @Override
    public void onCreate() {
        super.onCreate();
        Log.e(TAG, "application created...");
        Log4JUtil.configuration();
    }
}

public class MainActivity extends AppCompatActivity {
    private Logger logger = Logger.getLogger(MainActivity.class);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.e(TAG, "MainActivity created...");
        setContentView(R.layout.activity_main);
        logger.info("onCreate");
    }
}

 

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