Programmatically redirecting android logs to a file - android

I tried to find this but couldn't find and results. Apologies if this is a duplicate.
I would like to have android logs written to a file. But i do not wish them to be written to the file in the end, rather as the log statement is executed, it should be written into this file.

But i do not wish them to be written to the file in the end, rather as the log statement is executed, it should be written into this file.
Then write one or more methods that log to a file, possibly in addition to logging to LogCat.
Logging to files has been done in Java development for ~15 years, and there is plenty of code available to demonstrate it.

You can try this code!
public static void printLog(Context context){
String filename = context.getExternalFilesDir(null).getPath() + File.separator + "my_app.log";
String command = "logcat -d *:V";
Log.d(TAG, "command: " + command);
try{
Process process = Runtime.getRuntime().exec(command);
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
try{
File file = new File(filename);
file.createNewFile();
FileWriter writer = new FileWriter(file);
while((line = in.readLine()) != null){
writer.write(line + "\n");
}
writer.flush();
writer.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
catch(IOException e)
{
e.printStackTrace();
}
}
Ref: How to keep on appending logs while writing into File in SDCard?

i use this:
Logger logger=Logger.getLogger("myLoggerName");
logger.setLevel(Level.ALL);
File logFileDirectory=new File(getExternalFilesDir(null),"myLogDirectory");
addFileHandler(logger,logFileDirectory,"myLogFile");

Related

How to read logcat continuously and write into the internal storage file?

Reading logcat continuously and write into the internal storage for this i tried the below code.
public class LogCatTask extends AsyncTask<Void, String, Void> {
public AtomicBoolean run = new AtomicBoolean(true);
#Override
protected Void doInBackground(Void... params) {
try {
//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");
Runtime.getRuntime().exec("logcat -c");
Process process = Runtime.getRuntime().exec("logcat -f "+file);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
StringBuilder log = new StringBuilder();
String line = "";
Log.e("log cat task...","while...run.get()."+run.get());
while (run.get()) {
line = bufferedReader.readLine();
//Log.e("log cat task...","while...out.");
if (line != null) {
Log.e("log cat task...","while....");
log.append(line);
//publishProgress(log.toString());
//to write logcat in text file
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
// Write the string to the file
osw.write(log.toString());
osw.flush();
osw.close();
}
line = null;
Thread.sleep(10);
//Log.e("log cat task...","while...out.");
}
//Log.e("log cat task...","ouet....while....");
}
catch(Exception ex){
}
return null;
}
}
once the above code runs,it read the logcat and write into storage but upto some part of the log only it reads.it is not reading the continuos.How to read the logcat continuous?
Here's a working code snippet
try {
Process process = Runtime.getRuntime().exec("logcat");
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
StringBuilder log=new StringBuilder();
String line = "";
while ((line = bufferedReader.readLine()) != null) {
// do what you want with the line you just read
// you're in an infinite loop continuously reading the log,
// you might want to add some mechanism to break out of it
}
}
catch (IOException e) {
fail("failed to get log");
}
Your code is overly complicated and prone to race conditions. For example, is the logcat -c guaranteed to complete before the logcat -f command. The -f command redirects output to a file, and your logic is also trying to write to that same file; that's very problematic. I've noticed that some of the logcat options such as "-T" doesn't work programmatically. Maybe the "-f" option also has problems. If you only want to read the log file up to the current time use "logcat -d".

How to write log to sd card in Android? [duplicate]

This question already has answers here:
How do I write the exception from printStackTrace() into a text file in Java?
(5 answers)
Closed 8 years ago.
My program is crashing in device. I want to exactly catch the log of my program while running in my device .i.e I want to write the log to my sd card, up to the point of crashing. How can I achieve this?
Try this
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this)); // add this to your activity page
public class ExceptionHandler implements
java.lang.Thread.UncaughtExceptionHandler {
private final Context myContext;
private final String LINE_SEPARATOR = "\n";
UncaughtExceptionHandler defaultUEH;
public ExceptionHandler(Context con) {
myContext = con;
defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
}
#SuppressWarnings("deprecation")
public void uncaughtException(Thread thread, Throwable exception) {
StringWriter stackTrace = new StringWriter();
exception.printStackTrace(new PrintWriter(stackTrace));
StringBuilder errorReport = new StringBuilder();
errorReport.append("************ CAUSE OF ERROR ************\n\n");
errorReport.append(stackTrace.toString());
errorReport.append("\n************ DEVICE INFORMATION ***********\n");
errorReport.append("Brand: ");
errorReport.append(Build.BRAND);
errorReport.append(LINE_SEPARATOR);
errorReport.append("Device: ");
errorReport.append(Build.DEVICE);
errorReport.append(LINE_SEPARATOR);
errorReport.append("Model: ");
errorReport.append(Build.MODEL);
errorReport.append(LINE_SEPARATOR);
File root = android.os.Environment.getExternalStorageDirectory();
String currentDateTimeString = DateFormat.getDateTimeInstance().format(
new Date());
File dir = new File(root.getAbsolutePath() + "/dir_name/log");
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, "log.txt");
try {
BufferedWriter buf = new BufferedWriter(new FileWriter(file, true));
buf.append(currentDateTimeString + ":" + errorReport.toString());
buf.newLine();
buf.close();
} catch (IOException e) {
e.printStackTrace();
}
defaultUEH.uncaughtException(thread, exception);
System.exit(0);
}
}
Once I got this from somewhere in SO. Try this:
public static void printLog(Context context){
String filename = context.getExternalFilesDir(null).getPath() + File.separator + "my_app.log";
String command = "logcat -f "+ filename + " -v time *:V";
Log.d(TAG, "command: " + command);
try{
Runtime.getRuntime().exec(command);
}
catch(IOException e){
e.printStackTrace();
}
}
This prints log continuously until the app exit.
Try this :
public void appendLog(String text) {
File logFile = new File("sdcard/log.file");
if (!logFile.exists()) {
try {
logFile.createNewFile();
}
catch (IOException e) {
Log.e(TAG, e.getMessage(), e);
}
}
try {
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(text);
buf.newLine();
buf.close();
} catch (IOException e) {
Log.e(TAG, e.getMessage(), e);
}
}
If you want to catch only the exception with the stacktrace, which in most cases is enough to get what was wrong, then ACRA is a winning solution.
If you do want to write something to your SD card then take in consideration that you can't assume that any device has external storage that you can write to. Unless you validate this.
To bring another option of writing to external storage you can use this simple library:
android-simple-storage
This is how you use it:
Prepare somewhere in your app:
Storage storage = SimpleStorage.getExternalStorage();
// create your own directory
storage.createDirectory("MyDir");
// create the file you want to write to inside your new directory
storage.createFile("MyDir", "MyFile.txt", "");
Append any string (or byte[]) whenever you want to this file:
storage.appendFile("MyDir", "MyFile.txt", "your log line");
You can create/read/update/delete with this tiny library files on internal and external storages very easy. And, take into consideration that writing to the same file will increase the space it takes. You can use getSize() from the same library to validate.

Reading logs with filters programmatically

I am trying to read the user entered logs using log.i() programmatically as follows,
try {
Log.i("logs", "inside log.java");
String filter = "logcat ";
filter += "-d ";
filter += "logs:I";
// String[] command = new String[] { "logcat", "-s" , "logs:"+filter
// };
Process process = Runtime.getRuntime().exec(filter);
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
log = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
log.append(line);
log.append("\n");
}
clear = (Button) findViewById(R.id.clear);
clear.setOnClickListener(onCleared);
tv = (TextView) findViewById(R.id.logview);
tv.setText(log.toString());
} catch (IOException ex) {
Log.e("Logging", ex.toString());
}
// 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();
}
but it simply shows a black screen . but when i try to run the command in adb shell it works . my adb code is,
adb logcat -s logs:I
I was facing a similar problem while trying to log files to text programmatically. I think what's happening here is that the log reading process is blocking the UI (main) thread, resulting in the black screen.
Try putting the entire log reading process into an ASyncTask. That made it work for me!
Did you add this to your manifest file?
<uses-permission android:name="android.permission.READ_LOGS" />

How to log only from my process onto a single log file

I have 3 different process running and wanted to collect logs from them on to a single log file, using logcat.
Is it possible this logfile to have logs only from my 3 processes ? How to do the same programitcally.
any help regarding the same highly appreciated.
-regards,
Manju
you can try this way call this method and put put your message what you write in log file and is stored in your sd card. Any where your application tested it will create a log and you can see the details
public static void MyLog(String msg_location, String log_message) {
String messgae_location = msg_location;
String message_details = log_message;
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath()
+ "/mydata/LOG");
if (!dir.exists()) {
dir.mkdirs();
}
BufferedWriter bufferedWritter = null;
try {
bufferedWritter = new BufferedWriter(new FileWriter(dir
+ File.separator + "my_Log.txt", true));
String logString = null;
logString = currentDateTime1() + ": " + messgae_location + ": "
+ message_details + "\n";
bufferedWritter.write(logString);
bufferedWritter.newLine();
bufferedWritter.flush();
} catch (FileNotFoundException e) {
// e.printStackTrace();
} catch (IOException e) {
// e.printStackTrace();
}
}
You can filter the logcat output by tags.
You can use regular expressions when filtering. E.g. if you have 3 tags tag1m tag2, tag3 then if your filter is tag1|tag2 you will see logcaat output tagged by tag1 and tag2 (but not tag3).
To log your messages in a file better use Log4j for android. It's also simple.

Can i read a file from SmsManager

I copy+paste a *.txt file into the folder /frameworks/opt/telephony/src/java/android/telephony. Now I want to read it from SmsManager, but when I run the "emulator + adb logcat" it show me that it cant find the file.
Both files SmsManager.java and textfile.txt are in the same folder.
My code inside SmsManager is:
try {
FileInputStream fstream = new FileInputStream("textfile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line;
// read every line of the file into the line-variable, on line at the time
while (( line = br.readLine()) != null) {
Log.i(TAG, line+"##########################");
}
in.close();
} catch (java.io.FileNotFoundException e) {
Log.i(TAG, "File didnt found");
} catch (java.io.IOException e) {
Log.i(TAG, "File didnt found");
}
What is wrong, or where must I save the file to find it?
You will have to modify device.mk like below to copy from your source code to Android file system
PRODUCT_COPY_FILES := frameworks/abc.txt:system/abc.txt
In your code you will have to access /system/abc.txt

Categories

Resources