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

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.

Related

Writing data to a public text file in Android

I need to write some data into a text file to be read from standard text editor applications. In my app (running on Android 7.0) compiled with targetSdkVersion 27 I'm doing this trough this method, that works (or at least it seems to work since I got no exeptions):
private void storeLocation(Location location) {
try {
FileOutputStream outputStreamWriter;
outputStreamWriter = this.openFileOutput(logPath.getPath(), Context.MODE_APPEND);
outputStreamWriter.write(("LAT: " + location.getLatitude() + "\n").getBytes());
outputStreamWriter.write(("LON: " + location.getLongitude() + "\n").getBytes());
outputStreamWriter.close();
}
catch (Throwable e) {
Log.e("Exception", "File write failed: " + e.getMessage());
}
}
Variable logPath is defined in this way in application onCreate() event handler:
File logPath = new File("VIPER_" + getCurrentDateTime() + "_" + UUID.randomUUID().toString() + ".log");
I tought to find this file inside application private data folder but it's not here (maybe it's deleted after application closing?).
If I try to specify a different folder (like public downloads folder etc.) I got all sort of exceptions like file not found, read only filesystem, presence of / character in path etc.
There's a (simple) way to allow an application without having to deal with a FileProvider implementation?
The solution I found and that's working for some reason is the following:
logPath = new File( this.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS), "VIPER_" + getCurrentDateTime() + "_" + UUID.randomUUID().toString() + ".txt");
private void storeLocation(Location location) {
try {
final FileOutputStream outputStreamWriter = new FileOutputStream( logPath, true);
final SimpleDateFormat time_format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS", Locale.getDefault());
final String line = time_format.format(
new Date()) + String.format(Locale.getDefault(),
" %f %f %f %f\n",
location.getLatitude(),
location.getLongitude(),
location.getAltitude(),
location.getBearing());
outputStreamWriter.write(line.getBytes());
outputStreamWriter.flush();
outputStreamWriter.close();
}
catch (Throwable e) {
Log.e("Exception", "File write failed: " + e.getMessage());
}
}
I really haven't got why this code works while the previous wasn't ... maybe one of the reason is openFileOutput() call I was using in the first sample or maybe is the Environment.DIRECTORY_DOCUMENTS I'm using now. What's certain that even if now the file is availabe its availability is not immediate but may require a variable timespan (from some seconds to some minutes).
May this code be of any help to someonelse.

When accessing a text file on my android device through my PC, part of it doesn't come through

In my android app, I am putting values to a text file and I have confirmed that it works. I can open the text file on my android device and see ALL of the data in there as it should be. However, when I plug the device into my PC via USB, some of the data in the text file gets cut off.
Here's the data I see on my android device when I open the text file:
false,false,false,NULL,NULL,false,false,NULL,NULL,60,67,false,true,1,false,4,1,
Here's the data I see when I access the text file on my computer:
false,false,false,NULL,NULL,false,false,NULL,NULL,60,67,false,true,1,f
As you can see, the last few pieces of data get cut off. I've tried with different data and it still gets cut off there.
I'm not sure if this will help as the following code seemingly does get all the data to the text file (if looking on my android device), but here's the code for writing to the text file. I'm getting two lists of data from SharedPreferences files I've previously created and writing them to a file when a button is pressed.
SharedPreferences auto = getSharedPreferences("Auto", MODE_PRIVATE);
SharedPreferences teleop = getSharedPreferences("Teleop", MODE_PRIVATE);
autoValues = auto.getAll();
teleopValues = teleop.getAll();
public void writeToFile(View view){
try {
FileOutputStream stream = new FileOutputStream(myFile);
for (Map.Entry<String, ?> entry : autoValues.entrySet()){
stream.write(entry.getValue().toString().getBytes());
stream.write(",".getBytes());
}
for (Map.Entry<String, ?> entry : teleopValues.entrySet()){
stream.write(entry.getValue().toString().getBytes());
stream.write(",".getBytes());
}
stream.close();
System.out.println("SUCCESS: MAY HAVE WRITTEN TO FILE IN EXPORT");
} catch (Exception e){
e.printStackTrace();
System.out.println("ERROR: DID NOT WRITE TO FILE");
}
}
Use following function to efficiently write to your file. You must have permission to access external storage.
public static void logToFile(String message) {
String formattedData = String.format("%s", (new SimpleDateFormat("dd-MM HH:mm:ss", Locale.getDefault())
.format(new Date())) + "\t\t\t" + message + "\n");
FileOutputStream stream = null;
String path = Environment.getExternalStorageDirectory() + File.separator + Environment.DIRECTORY_DOWNLOADS;
try {
File file = new File(path + "/Logger.txt");
if (!file.exists()) {
file.createNewFile();
}
stream = new FileOutputStream(file, true);
stream.write(formattedData.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}

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.

Programmatically redirecting android logs to a file

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");

context.openFileInput() returning null when trying to access a stored file

Currently, I have the following code for saving a Web Archive and then getting it as a FileInputStream. However, the channel within webContent remains null and a FileNotFoundException is thrown:
// Save the Web Archive once loading is finished
String path = context.getFilesDir().getAbsolutePath()
+ File.separator + WEB_PREFIX + postId;
webView.saveWebArchive(path);
FileInputStream webContent = null;
try {
webContent = context.openFileInput(WEB_PREFIX + postId);
} catch (FileNotFoundException e) {
Log.d("onPageFinished()", "FileNotFoundException");
e.printStackTrace();
}
If I try to perform context.openFileInput(path) instead, I get
09-05 23:39:42.448: E/AndroidRuntime(8399): java.lang.IllegalArgumentException: File /data/data/com.example/files/web-2189241737372651547 contains a path separator
Does anyone know of a solution? The file certainly exists, since I saved it in the previous line.
openFileInput() doesn't accept paths, only a file name if you want to access a path.
Use this instead:
File file = new File(this.getFilesDir().getAbsolutePath() + (WEB_PREFIX + postId));
EDIT:
You need to make sure you are saving and retrieving the file from the same place. Give this a go:
Note: I'm not sure you need File.separator but try with and without it and see which one works.
String path = context.getFilesDir().getAbsolutePath()
+ File.separator + WEB_PREFIX + postId;
webView.saveWebArchive(path);
FileInputStream webContent = null;
try {
webContent = new File(path);
} catch (FileNotFoundException e) {
Log.d("onPageFinished()", "FileNotFoundException");
e.printStackTrace();
}

Categories

Resources