我想扩展android.util.Log
类,以便也将其写入设备内部存储中的日志文件中,最好还写入特定的TAGS
。
我目前有一个实现:
public class CustomLogger{
private final static Logger fileLog = Logger.getLogger(MainActivity.class);
private Context context;
public CustomLogger(Context c){
this.context = c;
final LogConfigurator logConfigurator = new LogConfigurator();
logConfigurator.setFileName(context.getFilesDir() + File.separator + "myApp.log");
logConfigurator.setRootLevel(Level.DEBUG);
logConfigurator.setLevel("org.apache", Level.ERROR);
logConfigurator.configure();
}
public void i(String TAG, String message){
// Printing the message to LogCat console
Log.i(TAG, message);
// Write the log message to the file
fileLog.info(TAG+": "+message);
}
public void d(String TAG, String message){
Log.d(TAG, message);
fileLog.debug(TAG+": "+message);
}
}
您可以看到此自定义记录器将日志记录到内部存储器上的日志文件中(使用android-logging-log4j
库)并通过android.util.Log
类。但是,我希望从我的日志文件中的android.util.Log
类中获取标准日志条目,并且如果可能的话,仅某些(自定义)TAGS
。
任何人都有一个示例或关于如何实现此目标的任何好的技巧?
提前感谢
您可以通过编程方式读取日志猫并将其存储到文本文件中,也可以将其发送到任意位置。
下面是我有相同内容的详细文章
Read & Store Log-cat Programmatically in Android
并且为了阅读logcat,这里是示例代码
public class LogTest extends Activity {
private StringBuilder log;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
Process process = Runtime.getRuntime().exec("logcat -d");
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
log=new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
log.append(line);
}
TextView tv = (TextView)findViewById(R.id.textView1);
tv.setText(log.toString());
} catch (IOException e) {
}
//convert log to string
final String logString = new String(log.toString());
//create text file in SDCard
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/myLogcat");
dir.mkdirs();
File file = new File(dir, "logcat.txt");
try {
//to write logcat in text file
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
// Write the string to the file
osw.write(logString);
osw.flush();
osw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
所以有更短的变体
try {
final File path = new File(
Environment.getExternalStorageDirectory(), "DBO_logs5");
if (!path.exists()) {
path.mkdir();
}
Runtime.getRuntime().exec(
"logcat -d -f " + path + File.separator
+ "dbo_logcat"
+ ".txt");
} catch (IOException e) {
e.printStackTrace();
}