Android应用中添加Log4j的示例

1、新建Android项目

Project: AndroidLog4j

Package:cn.darkranger.log

Activity:MainActivity

2、在libs中添加log4j-1.2.17.jar包

3、添加android-logging-log4j-1.0.3.jar

我看了一下,这里面只有两个类,我就用反编译工具反编译成了java文件,写入代码中了

LogCatAppender.java(主要作用是将log在控制台的输出转化为Android中的LogCat输出)

package cn.darkranger.log.log4j;

import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.Layout;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.spi.LoggingEvent;

import android.util.Log;

/**
 * 源自 android-logging-log4j-1.0.3.jar
 *
 * @author Administrator
 */
public class LogCatAppender extends AppenderSkeleton {
    protected Layout tagLayout;

    public LogCatAppender(Layout messageLayout, Layout tagLayout) {
        this.tagLayout = tagLayout;
        setLayout(messageLayout);
    }

    public LogCatAppender(Layout messageLayout) {
        this(messageLayout, new PatternLayout("%c"));
    }

    public LogCatAppender() {
        this(new PatternLayout("%m%n"));
    }

    protected void append(LoggingEvent le) {
        switch (le.getLevel().toInt()) {
        case 5000:
            if (le.getThrowableInformation() != null) {
                Log.v(getTagLayout().format(le), getLayout().format(le), le.getThrowableInformation().getThrowable());
            } else {
                Log.v(getTagLayout().format(le), getLayout().format(le));
            }
            break;
        case 10000:
            if (le.getThrowableInformation() != null) {
                Log.d(getTagLayout().format(le), getLayout().format(le), le.getThrowableInformation().getThrowable());
            } else {
                Log.d(getTagLayout().format(le), getLayout().format(le));
            }
            break;
        case 20000:
            if (le.getThrowableInformation() != null) {
                Log.i(getTagLayout().format(le), getLayout().format(le), le.getThrowableInformation().getThrowable());
            } else {
                Log.i(getTagLayout().format(le), getLayout().format(le));
            }
            break;
        case 30000:
            if (le.getThrowableInformation() != null) {
                Log.w(getTagLayout().format(le), getLayout().format(le), le.getThrowableInformation().getThrowable());
            } else {
                Log.w(getTagLayout().format(le), getLayout().format(le));
            }
            break;
        case 40000:
            if (le.getThrowableInformation() != null) {
                Log.e(getTagLayout().format(le), getLayout().format(le), le.getThrowableInformation().getThrowable());
            } else {
                Log.e(getTagLayout().format(le), getLayout().format(le));
            }
            break;
        case 50000:
            if (le.getThrowableInformation() != null) {
                Log.wtf(getTagLayout().format(le), getLayout().format(le), le.getThrowableInformation().getThrowable());
            } else
                Log.wtf(getTagLayout().format(le), getLayout().format(le));
            break;
        }
    }

    public void close() {
    }

    public boolean requiresLayout() {
        return true;
    }

    public Layout getTagLayout() {
        return this.tagLayout;
    }

    public void setTagLayout(Layout tagLayout) {
        this.tagLayout = tagLayout;
    }
}

LogConfig.java(主要作用是配置一些基本的信息)

package cn.darkranger.log.log4j;

import java.io.IOException;

import org.apache.log4j.Layout;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.RollingFileAppender;
import org.apache.log4j.helpers.LogLog;

/**
 * 源自 android-logging-log4j-1.0.3.jar
 *
 * @author Administrator
 */
public class LogConfig {
    private Level rootLevel = Level.DEBUG;
    private String filePattern = "%d - [%p::%c::%C] - %m%n";
    private String logCatPattern = "%m%n";
    private String fileName = "android-log4j.log";
    private int maxBackupSize = 5;
    private long maxFileSize = 1024 * 1024 * 5L;
    private boolean immediateFlush = true;
    private boolean useLogCatAppender = true;
    private boolean useFileAppender = true;
    private boolean resetConfiguration = true;
    private boolean internalDebugging = false;

    public LogConfig() {
    }

    public LogConfig(String fileName) {
        setFileName(fileName);
    }

    public LogConfig(String fileName, Level rootLevel) {
        this(fileName);
        setRootLevel(rootLevel);
    }

    public LogConfig(String fileName, Level rootLevel, String filePattern) {
        this(fileName);
        setRootLevel(rootLevel);
        setFilePattern(filePattern);
    }

    public LogConfig(String fileName, int maxBackupSize, long maxFileSize, String filePattern, Level rootLevel) {
        this(fileName, rootLevel, filePattern);
        setMaxBackupSize(maxBackupSize);
        setMaxFileSize(maxFileSize);
    }

    public void configure() {
        Logger root = Logger.getRootLogger();

        if (isResetConfiguration()) {
            LogManager.getLoggerRepository().resetConfiguration();
        }

        LogLog.setInternalDebugging(isInternalDebugging());

        if (isUseFileAppender()) {
            configureFileAppender();
        }

        if (isUseLogCatAppender()) {
            configureLogCatAppender();
        }

        root.setLevel(getRootLevel());
    }

    public void setLevel(String loggerName, Level level) {
        Logger.getLogger(loggerName).setLevel(level);
    }

    private void configureFileAppender() {
        Logger root = Logger.getRootLogger();

        Layout fileLayout = new PatternLayout(getFilePattern());
        RollingFileAppender rollingFileAppender;
        try {
            rollingFileAppender = new RollingFileAppender(fileLayout, getFileName());
        } catch (IOException e) {
            throw new RuntimeException("Exception configuring log system", e);
        }

        rollingFileAppender.setMaxBackupIndex(getMaxBackupSize());
        rollingFileAppender.setMaximumFileSize(getMaxFileSize());
        rollingFileAppender.setImmediateFlush(isImmediateFlush());

        root.addAppender(rollingFileAppender);
    }

    private void configureLogCatAppender() {
        Logger root = Logger.getRootLogger();
        Layout logCatLayout = new PatternLayout(getLogCatPattern());
        LogCatAppender logCatAppender = new LogCatAppender(logCatLayout);

        root.addAppender(logCatAppender);
    }

    public Level getRootLevel() {
        return this.rootLevel;
    }

    public void setRootLevel(Level level) {
        this.rootLevel = level;
    }

    public String getFilePattern() {
        return this.filePattern;
    }

    public void setFilePattern(String filePattern) {
        this.filePattern = filePattern;
    }

    public String getLogCatPattern() {
        return this.logCatPattern;
    }

    public void setLogCatPattern(String logCatPattern) {
        this.logCatPattern = logCatPattern;
    }

    public String getFileName() {
        return this.fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public int getMaxBackupSize() {
        return this.maxBackupSize;
    }

    public void setMaxBackupSize(int maxBackupSize) {
        this.maxBackupSize = maxBackupSize;
    }

    public long getMaxFileSize() {
        return this.maxFileSize;
    }

    public void setMaxFileSize(long maxFileSize) {
        this.maxFileSize = maxFileSize;
    }

    public boolean isImmediateFlush() {
        return this.immediateFlush;
    }

    public void setImmediateFlush(boolean immediateFlush) {
        this.immediateFlush = immediateFlush;
    }

    public boolean isUseFileAppender() {
        return this.useFileAppender;
    }

    public void setUseFileAppender(boolean useFileAppender) {
        this.useFileAppender = useFileAppender;
    }

    public boolean isUseLogCatAppender() {
        return this.useLogCatAppender;
    }

    public void setUseLogCatAppender(boolean useLogCatAppender) {
        this.useLogCatAppender = useLogCatAppender;
    }

    public void setResetConfiguration(boolean resetConfiguration) {
        this.resetConfiguration = resetConfiguration;
    }

    public boolean isResetConfiguration() {
        return this.resetConfiguration;
    }

    public void setInternalDebugging(boolean internalDebugging) {
        this.internalDebugging = internalDebugging;
    }

    public boolean isInternalDebugging() {
        return this.internalDebugging;
    }
}

4、编写LogUtil.java工具类(主要作用是重新配置Log4j的一些参数,设置成为合适自己项目的log,在这里我们通过调用LogUtil.configLog()就可以了,简洁)

LogUtil.java

package cn.darkranger.log.log4j;

import java.io.File;
import java.util.Locale;

import org.apache.log4j.Level;

import android.os.Environment;

/**
 * LogUtil 工具类
 *
 * @author Administrator
 *
 */
@SuppressWarnings("all")
public class LogUtil {

    /** 这里的AppName决定log的文件位置和名称 **/
    private static final String APP_NAME = "MyApp";

    /** 设置log文件全路径,这里是 MyApp/Log/myapp.log **/
    private static final String LOG_FILE_PATH = Environment.getExternalStorageDirectory() + File.separator + APP_NAME
            + File.separator + "Log" + File.separator + APP_NAME.toLowerCase(Locale.CHINA) + ".log";

    /**
     *  ### log文件的格式
     *
     *     ### 输出格式解释:
     *    ### [%-d{yyyy-MM-dd HH:mm:ss}][Class: %c.%M(%F:%L)] %n[Level: %-5p] - Msg: %m%n
     *
     *    ### %d{yyyy-MM-dd HH:mm:ss}: 时间,大括号内是时间格式
     *    ### %c: 全类名
     *    ### %M: 调用的方法名称
     *    ### %F:%L  类名:行号(在控制台可以追踪代码)
     *    ###    %n: 换行
     *    ### %p: 日志级别,这里%-5p是指定的5个字符的日志名称,为的是格式整齐
     *    ### %m: 日志信息

     *    ### 输出的信息大概如下:
     *    ### [时间{时间格式}][信息所在的class.method(className:lineNumber)] 换行
     *    ###    [Level: 5个字符的等级名称] - Msg: 输出信息 换行
     */
    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";

    /** 生产环境下的log等级 **/
    private static final Level LOG_LEVEL_PRODUCE = Level.ALL;

    /** 发布以后的log等级 **/
    private static final Level LOG_LEVEL_RELEASE = Level.INFO;

    /**
     * 配置log4j参数
     */
    public static void configLog(){

        LogConfig logConfig = new LogConfig();

        /** 设置Log等级,生产环境下调用setLogToProduce(),发布后调用setLogToRelease() **/
        setLogToProduce(logConfig);

        logConfig.setFileName(LOG_FILE_PATH);

        logConfig.setLevel("org.apache", Level.ERROR);

        logConfig.setFilePattern(LOG_FILE_PATTERN);

        logConfig.setMaxFileSize(1024 * 1024 * 5);

        logConfig.setImmediateFlush(true);

        logConfig.configure();

    }

    /**
     * 将log设置为生产环境
     *
     * @param logConfig
     */
    private static void setLogToProduce(LogConfig logConfig) {
        logConfig.setRootLevel(LOG_LEVEL_PRODUCE);
    }

    /**
     * 将log设置为发布以后的环境
     *
     * @param logConfig
     */
    private static void setLogToRelease(LogConfig logConfig) {
        logConfig.setRootLevel(LOG_LEVEL_RELEASE);
    }
}

5、编写MyApplication.java(继承Application,然后在onCreate()中调用LogUtil.configLog()方法来配置Log4j,这样程序一开始就相当于初始化了Log4j的配置)

package cn.darkranger.log.application;

import org.apache.log4j.Logger;

import android.app.Application;
import cn.darkranger.log.log4j.LogUtil;

public class MyApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        //配置log4j基本参数
        LogUtil.configLog();

        //获取Application Log
        Logger log = Logger.getLogger(MyApplication.class);

        //输出MyApplication的信息
        log.info("Log4j Is Ready and My Application Was Created Successfully! ");
    }

}

6、修改AndroidManifest.xml(主要有两个地方,一是添加读取存储的权限,二是指定Application为我们刚刚写的MyApplication)

有下划线的地方就是我们添加的xml代码

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="cn.darkranger.log"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="22" />

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:name="cn.darkranger.log.application.MyApplication"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="cn.darkranger.log.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

 7、使用Log4j

  (1)创建Logger实例

    private static Logger log = Logger.getLogger(YourClassName.class);

  (2)在代码中用log记录信息

    log.info("onCreate()");
    log.fatal("this is fatal!");
    log.error("this is error!");
    log.warn("this is warn!");
    log.info("this is info!");
    log.debug("this is debug!");
    log.trace("this is trace!");

  (3)MainActivity.java中的示例(红色的部分就是log的记录)

package cn.darkranger.log;

import org.apache.log4j.Logger;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;

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

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        log.info("onCreate()");
        log.fatal("this is fatal!");
        log.error("this is error!");
        log.warn("this is warn!");
        log.info("this is info!");
        log.debug("this is debug!");
        log.trace("this is trace!");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        log.info("onCreateOptionsMenu()");
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

 8、结果展示:


  控制台输出:

  

  平板中的Log位置:计算机\Galaxy Tab A\Tablet\MyApp\Log\myapp.log(相对于计算机)

           设备存储\MyApp\Log\myapp.log(相对于平板)

[2016-06-16 17:14:54][Class: cn.darkranger.log.application.MyApplication.onCreate(MyApplication.java:21)]
[Level: INFO ] - Msg: Log4j Is Ready and My Application Was Created Successfully!
[2016-06-16 17:14:54][Class: cn.darkranger.log.MainActivity.onCreate(MainActivity.java:17)]
[Level: INFO ] - Msg: onCreate()
[2016-06-16 17:14:54][Class: cn.darkranger.log.MainActivity.onCreate(MainActivity.java:18)]
[Level: FATAL] - Msg: this is fatal!
[2016-06-16 17:14:54][Class: cn.darkranger.log.MainActivity.onCreate(MainActivity.java:19)]
[Level: ERROR] - Msg: this is error!
[2016-06-16 17:14:54][Class: cn.darkranger.log.MainActivity.onCreate(MainActivity.java:20)]
[Level: WARN ] - Msg: this is warn!
[2016-06-16 17:14:54][Class: cn.darkranger.log.MainActivity.onCreate(MainActivity.java:21)]
[Level: INFO ] - Msg: this is info!
[2016-06-16 17:14:54][Class: cn.darkranger.log.MainActivity.onCreate(MainActivity.java:22)]
[Level: DEBUG] - Msg: this is debug!
[2016-06-16 17:14:54][Class: cn.darkranger.log.MainActivity.onCreate(MainActivity.java:23)]
[Level: TRACE] - Msg: this is trace!
[2016-06-16 17:14:54][Class: cn.darkranger.log.MainActivity.onCreateOptionsMenu(MainActivity.java:30)]
[Level: INFO ] - Msg: onCreateOptionsMenu()
时间: 2024-10-05 16:35:37

Android应用中添加Log4j的示例的相关文章

Android系统中添加一个产品----图文详解

本文本着开源的精神介绍如何向一个Android系统中添加一个产品的整个过程,按照以下过程笔者有理由相信每个将要从事本行业的人都可以完成,其实添加一个产品并不难,难的是对其相关硬件的修改,好了废话不多说. 首先我们要创建一个属于自己产品的目录,这里以WY_device为例,以WY作为产品的名字. 首先从已经存在的产品中拷贝一个以产品的名字为名的.mk文件,修改为自己的.mk文件,在这里为WY.mk 对其进行如下的修改: 然后添加AndroidProducts.mk  这是添加产品的配置文件名路径,

在Android Studio中添加assets目录

在Android Studio中添加assets目录,目录的位置在 XXX\src\main\assets XXX代表你的项目的路径,assets放在src\main目录下. 这个位置可以通过XXX.iml  XXX代表自己的项目名,其中有设置assets的目录,设置如下 <option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" /> 结果如图所示: 参考:http://blo

在Android应用中添加React Native支持

用android studio创建一个基本的android hello world程序 在项目根目录中通过npm向导生成package.json文件,在cmd中输入命令:npm init 在package.json文件中添加启动脚本"start": "node node_modules/react-native/local-cli/cli.js start" 添加react-native npm依赖,在命令行输入npm install react react-nat

向Android系统中添加模块及产品流程

 添加Android模块  一.基础知识: (1)在Android系统中,编译都是以模块(而不是文件)作为单位的,每个模块都有一个唯一的名称: (2)为了将模块编译到Android系统中,每个模块都需要一个专门的Make文件,也即是"Android.mk"文件: 二.实现hello.c 模块的编写  1. 如在 hardware/test目录下,编写hello.c 2. 在hardw/test目录下,编写Android.mk Android.mk编写的步骤: (1)设置当前模块的编译路

如何在Android Gradle中添加原生so文件依赖

@author ASCE1885的 Github 简书 微博 CSDN 原文链接 背景 几个月前,基于Google的LevelDB,我为Android平台写了一个名为SnappyDB的键值数据库(NoSQL). 由于它使用到了原生C++代码,因此最终生成的文件除了Jars包还有so文件. 通过Maven仓库发布我们的函数库没有什么问题(只要你通过繁琐的发布流程),maven-android-plugin可以帮助我们包含共享库.Maven依赖规则使得我们可以指定想要获取的ABI(不同的CPU架构)

关于如何正确地在android项目中添加第三方jar包

1.下载第三方jar包 2.在android项目下创建一个libs目录(名称并不固定,你完全可以取其他名称) 3.在eclipse中右键点击libs目录,依次选择Import -> General -> File System,选中jar包所在目录, 然后选中这个目录下的jar包 注:到这一步为止你就成功地把jar包添加到项目中(但是还没有被android的虚拟机识别,因此如果这时你使用jar包中的类,编译都无法通过) 4.右键点击项目名,依次选择Build Path -> Config

如何在Android Studio中添加RecyclerView-v7支持包

1.打开SDK Manager,在Extras树下找到Android Support Library,下载好支持包.RecyclerView在v7-21版本就出来了.我这里不用更新了,说明是最新的,怎么可能不行呢? 2.按照目录结构,在app的build.gradle的dependencies最后添加了一句: compile 'com.android.support:recyclerview-v7:24.2.1' 3.Build——Clean Project.等待Clean完毕后,在Extern

项目中添加Log4J支持

首先,在项目中的classes 中新建立一个log4j.properties文件即可: 在实际编程时,要使Log4j真正在系统中运行事先还要对配置文件进行定义.定义步骤就是对Logger.Appender及Layout的分别使用.Log4j支持两种配置文件格式,一种是XML格式的文件,一种是java properties(key=value)[Java特性文件(键=值)].(这里只说明properties文件) 1.配置根Logger 其语法为: log4j.rootLogger = [ lev

android UI中添加一张图片如何将这张图片中某一部分设为透明的

可以利用canvas画布类,这个类的具体方法可以参看官方api.http://developer.android.com/reference/android/graphics/Canvas.html 思路如下:对你图片做一些处理,例如让上部分完全显示,让下部分半透明.1.先将你的原图转化为位图Bitmap:2.先创建canvas画布,大小就是你原图片大小:3.创建画笔paint类,设置画笔属性透明度,颜色等:4.使用canvas类的drawBitmap(int[] colors, int off