安卓,输出log信息到文件


public static boolean OutLogFile = true;	// 输出log信息到文件

/** 输出log信息到文件中 */
public static String FileLog(String info)
{
	if (OutLogFile)
	{
		String crashPath = "/sdcard/ltsdk/Log/";
		
		DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		String date = formatter.format(new Date());
		
		DateFormat formatter2 = new SimpleDateFormat("HH:mm:ss");
		String time = formatter2.format(new Date()) + "  ";
		
		String fileName = "log-" + date + ".txt";
		info = "\r\n" + time + info;
		
		try
		{
			if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
			{
				// String path = "/sdcard/com.hm.pay.demo/crash/";
				File dir = new File(crashPath);
				if (!dir.exists())
				{
					dir.mkdirs();
				}
				FileOutputStream fos = new FileOutputStream(crashPath + fileName, true);
				fos.write(info.getBytes());
				fos.close();
			}
		}
		catch (Exception e)
		{
			Log.e(TAG, "an error occured while writing file log...", e);
		}
		return crashPath + fileName;
	}
	else return "";
}

 

安卓开发中,记录log信息文件可以通过以下步骤实现: 1. 创建一个用于存储log文件。可以使用`File`类来创建一个新的文件对象,指定存储路径和文件名。 ```java File logFile = new File(Environment.getExternalStorageDirectory(), "log.txt"); ``` 2. 在代码中,通过`Log`类来输出log信息。可以使用`Log.d()`、`Log.i()`、`Log.e()`等方法来输出不同级别的log信息。 ```java Log.d("TAG", "This is a debug log message"); Log.i("TAG", "This is an info log message"); Log.e("TAG", "This is an error log message"); ``` 3. 创建一个`PrintWriter`对象,用于将log信息文件。 ```java PrintWriter printWriter = new PrintWriter(new FileWriter(logFile, true)); ``` 4. 在应用程序中设置一个`UncaughtExceptionHandler`,以捕获未处理的异常,将异常信息log文件。 ```java Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread thread, Throwable throwable) { throwable.printStackTrace(printWriter); printWriter.flush(); // 退出应用程序或进行其他处理 } }); ``` 5. 在应用程序中的适当位置,使用`printWriter`将log信息文件。 ```java printWriter.println("This is a log message"); printWriter.flush(); ``` 记得在合适的时候关闭`printWriter`和`FileWriter`对象。 以上是将log信息记录文件的一种常见方法,你也可以根据自己的需求进行修改和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值