Android-logging-log4j实现log输出到sd卡中

686 阅读2分钟

       在开发程序的时候往往会出现一些问题,通常我们在Eclipse中允许程序可以看到程序允许的日志,在日志中可以看到错误信息,但是程勋使用不可能时时都连接eclipse的,那么在脱离eclipse正常使用过程中,如果程序出现问题了就看不到错误信息,所以我们需要把错误信息保存到本地以供查看,这里介绍一个日志输出框架,可以方便的输出哦。
Android-logging-log4j是一个简单的日志输出框架,下面讲解使用方法:
1、下载android的log4j的库(的封装)

去:code.google.com/p/android-l…

下载对应的android-logging-log4j-1.0.3.jar,添加到项目的libs文件夹中。\

2.再去下载所依赖的apache的log4j库

去:logging.apache.org/log4j/1.2/d…

下载1.2系列版本的:log4j-1.2.17.zip

解压得到log4j-1.2.17.jar添加到项目的libs文件夹中。

3、有了上面的两个jar包之后,我们就开始在代码中使用了。
代码如下:

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

import  java. io. File;

import  android. os. Environment;

import  org. apache. log4j. Level;

import  org. apache. log4j. Logger;

 

public  class  BaseActivity  extends  Activity {

     private  Logger  gLogger;

     

     public  void  configLog(){

         final  LogConfigurator  logConfigurator  =  new  LogConfigurator();

          

         logConfigurator. setFileName( Environment. getExternalStorageDirectory()  +  File. separator  +  "crifanli_log4j.log");

         // Set the root log level

         logConfigurator. setRootLevel( Level. DEBUG);

         // Set log level of a specific logger

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

         logConfigurator. configure();

 

         //gLogger = Logger.getLogger(this.getClass());

         gLogger  =  Logger. getLogger( "CrifanLiLog4jTest");

    }

     

    @ Override

     protected  void  onCreate( Bundle  savedInstanceState) {

         configLog();

         gLogger. debug( "test android log to file in sd card using log4j");

 这里使用Logger,在oncreate里面进行初始化,初始化调用configLog()方法即可,这个方法里面配置日志文件的保存位置以及日志文件的文件名;最后输出内容使用   gLogger . debug ( "test android log to file in sd card using log4j" )即可,中间即为输出的信息;
然后在内存卡中找到日志文件打开即为刚才保存的日志信息:\

2014-09-18 16:25:29,120 - [DEBUG::CrifanLiLog4jTest::com.qiyun.dinghuohui.activity.GoodsDetailActivity] - test android log to file in sd card using log4j