**为方便测试,需要经常处理log是否打印的问题,有时为了方便统计,将错误日志生成到sd卡方便查看**
package com.manny.utils;
import android.content.Context;
import android.os.Environment;
import android.util.Log;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;
/**
* Created by manny on 2017/12/28.
*/
public class LogUtils
{
public static final String TAG_DEFAULT = “MANNY”;
private static boolean isOutPut = false;
/**
*是否在sd卡记录错误日志
*/
private static boolean isDebug = false;
/**
* 在程序初始化时调用,可以在Application的onCreate或者service的onCreate中
* 若sd卡内存在log.dat 则true
*/
public static void isOutputLog( Context context )
{
if( SdCardUtils.isSdCardExist() )
{
File file = new File( Environment.getExternalStorageDirectory() + "/Log.dat" );
if( file.exists() )
{
isOutPut = true;
}
else
{
isOutPut = false;
}
}
}
public static void d( String msg )
{
d( TAG_DEFAULT, msg );
}
public static void i( String msg )
{
i( TAG_DEFAULT, msg );
}
public static void e( String msg )
{
e( TAG_DEFAULT, msg );
}
public static void w( String msg )
{
w( TAG_DEFAULT, msg );
}
public static void v( String msg )
{
v( TAG_DEFAULT, msg );
}
public static void d(
Class cls,
String msg )
{
d( TAG_DEFAULT, msg );
}
public static void v(
Class cls,
String msg )
{
v( TAG_DEFAULT, msg );
}
public static void e(
Class cls,
String msg )
{
e( TAG_DEFAULT, msg );
}
public static void i(
Class cls,
String msg )
{
i( TAG_DEFAULT, msg );
}
public static void w(
Class cls,
String msg )
{
w( TAG_DEFAULT, msg );
}
public static void v(
String tag,
String msg )
{
if( isOutPut )
{
Log.v( tag, msg );
}
}
public static void d(
String tag,
String msg )
{
if( isOutPut )
{
Log.d( tag, msg );
}
}
public static void i(
String tag,
String msg )
{
if( isOutPut )
{
Log.i( tag, msg );
}
}
public static void e(
String tag,
String msg )
{
if( isOutPut )
{
Log.e( tag, msg );
}
}
public static void w(
String tag,
String msg )
{
if( isOutPut )
{
Log.w( tag, msg );
}
}
/**
* 记录错误日志并生成文件在sd卡内error.txt
*/
public static synchronized void e( Throwable ex )
{
PrintStream ps = null;
try
{
d( "", "begin e" );
d( "", Log.getStackTraceString( ex ) );
d( "", "end e" );
if( isDebug )
{
if( SdCardUtils.isSdCardExist() )
{
ps = new PrintStream( new FileOutputStream( Environment.getExternalStorageDirectory() + "/error.txt", true ) );
ex.printStackTrace( ps );
ps.flush();
}
}
}
catch( Exception e )
{
e( e );
}
finally
{
try
{
if( null != ps )
{
ps.close();
}
}
catch( Exception e )
{
e( e );
}
}
}
}