我正在尝试设置日志处理程序以将Android日志输出到文件到外部存储。下面的代码创建了日志文件,但是没有输出发送到文件,因此处理程序的配置方式显然是错误的。或者,也许这种安排根本不可能发挥作用?
该函数在主活动的onCreate()中调用。
private void logToFile(String path) {
try {
// Get package name
String packageName = MainActivity.class.getPackage().getName();
String logfileName = path + "/" + packageName + ".log";
Logger logger = Logger.getLogger(packageName);
logger.setLevel(Level.FINE);
FileHandler fileTxt = new FileHandler(logfileName);
SimpleFormatter formatterTxt = new SimpleFormatter();
fileTxt.setFormatter(formatterTxt);
logger.addHandler(fileTxt);
Toast.makeText(this, "Logging to " + logfileName, Toast.LENGTH_LONG).show();
} catch (IOException e) {
Log.d(TAG, e.getMessage());
}
Log.i(TAG, "logging to filesystem enabled");
}
答案 0 :(得分:1)
要写入上面声明的记录器(以及附加的写入文件的处理程序),应使用以下内容代替Log.i(TAG,“message”)
private static final Logger logger = Logger.getLogger(TAG);
public void someFunction() {
logger.info("message")
}
这些日志消息也将出现在logCat / debugger中,并附带提供的TAG。 附: Java日志记录让我头疼......
答案 1 :(得分:0)
我对使用Logger而不是标准Logcat Log.d(),Log.e()等感到沮丧,所以我开始使用这个Frankenstein的怪物解决方案,从Logcat读取到LogRecord并使用FileHandler保存。
这意味着您可以轻松限制日志文件大小,并保留详细的Android日志。
但是这不会给你连续输出到文件。如果您不介意按一个按钮或在会话中调用它,那么它应该无关紧要,因为无论如何Logcat都会不断更新。
(我强烈建议从非UI线程调用。)
FileHandler fh=null;
String name;
if ( 0 == Environment.getExternalStorageState().compareTo(Environment.MEDIA_MOUNTED))
name = Environment.getExternalStorageDirectory().getAbsolutePath();
else
name = Environment.getDataDirectory().getAbsolutePath();
name += "/yourapp/yourapp";
try {
fh = new FileHandler(name, 1024*1024, 7, true); //Limit to 7 x 1MB files.
fh.setFormatter(new SimpleFormatter());
//Try to read Logcat.
try {
//Dumps the entire logcat to std output.
Process processD = Runtime.getRuntime().exec("logcat -v long -d");
BufferedReader bufferedReaderD = new BufferedReader(new InputStreamReader(processD.getInputStream()));
String lineD;
while ((lineD = bufferedReaderD.readLine()) != null){
//Send to the file handler.
fh.publish(new LogRecord(Level.ALL, lineD));
}
//Clear the logcat storage. Don't feel like rewriting old records.
Process processC = Runtime.getRuntime().exec("logcat -c");
} catch (IOException e) {
Log.e(TAG, "Could not get Logcat logs.");
e.printStackTrace();
}
} catch (Exception e) {
Log.e("MyLog", "FileHandler exception", e);
} finally {
if (fh != null)
fh.close();
}