Collect all Log.d from class and save it into SDCard - android

Hey is it possible in Android to collect all Log.d from one class and keep on appending it and save it into SDCard ?
For example :
Class Android {
private final static String TAG = "hello";
public void abcd(){
Log.d(TAG, "it went into abcd method");
}
public void efgh(){
Log.d(TAG, "it went into efgh method");
}
/*Here collect all above LOGS and write to file in SDCard*/
}

You can get all logs with the logcat command. You can try something like:
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();
}
}
You can get more information about logcat here: http://developer.android.com/tools/help/logcat.html

You can override the Log class and do that yourself. But is it really required for your purposes?

no, Log.* methods write to the console, however you can use Logger http://developer.android.com/reference/java/util/logging/Logger.html and a FileHandler

If you want to add logs with tag name and
logcat -s <Tagname>
Is not working for you then you can do this trick
//... Brtle 's code..(accepted one )
file.createNewFile();
FileWriter writer = new FileWriter(file);
while((line = in.readLine()) != null){
if(line.contains("TAG_NAME")){ // Trick :-)
writer.write(line + "\n");
}
}

Related

Android FileOutputStream location save file

I have an app that saves into a file (internal storage) data input by the user and at startup it loads this file and shows the contents. I would like to know: where can I find my file (data.txt)?
In addition, if I input "Hello" and then "World" when I load the file, I see "HelloWorld" in the same line but I want "Hello" and "World" printed on two different lines.
For saving file:
public void writeToFile(String data) {
try {
FileOutputStream fou = openFileOutput("data.txt", MODE_APPEND);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fou);
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
For loading file:
public String readFromFile() {
String ret = "";
try {
InputStream inputStream = openFileInput("data.txt");
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return ret;
}
Thanks.
[UPDATE]
I've inserted "\n" after every input:
user = (EditText) v.findViewById(R.id.username);
writeToFile(user.getText().toString() + "\n");
But when I print my file, they are always on the same line.
Where can I find my file (data.txt)?
You can find the path of the directory, which is created by openFileOutput, by using YourActivity.this.getFilesDir().getAbsolutePath().
But I want "Hello" and "World" printed in two different lines.
Use line.separator after writing a word in a file, for example:
String separator = System.getProperty("line.separator");
outputStreamWriter.write(data);
outputStreamWriter.append(separator);
...
Or you can also use replaceAll to break String into multiple lines:
String separator = System.getProperty("line.separator");
data=data.replaceAll(" ",separator);
I guess you can find it here: data/data/[your package name]/... and regarding writing in two separate lines just add "\n" whenever you need to go to another line.

extend Android.util.Log to write to file

I would like to extend the android.util.Log class to also write to a log file in internal storage of the device, preferrably also for specific TAGS.
I currently have an implementation:
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);
}
}
As you can see this custom logger logs both to a log file on the internal storage (using the android-logging-log4j library) and through the android.util.Log class.
However i would like the standard log entries from the android.util.Log class in my log file, and if possible only certain (custom) TAGS.
Anybody has an example or any good tips on how to reach this?
Thanks in advance
You can read log cat programmatically and store into text file or you send it wherever you want.
Below is the detailed article I have written for same:
Read & Store Log-cat Programmatically in Android
And for reading the logcat here is sample code:
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();
}
}
}
So there is much shorter variant
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();
}

Filter Logs in Android programmatically

This is method to fetch and dump logs in SDCard for Android. This is working fine, but I am wondering if we can put filter to trace logs related to specific tags.
I tried logcat -s *TagIWant; but it didn't work. Any other suggestion?
public static void Log(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();
}
}
try {
Process process = Runtime.getRuntime().exec("logcat -d");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
Pattern pattern = Pattern.compile("XXX", 0);
while ((line = bufferedReader.readLine()) != null) {
if (patternu != null
&& !pattern.matcher(line).find()) {
continue;
}
log.append(line);
log.append('\n');
}
} catch (IOException e) {
}
Replace "Your_Tag" with your tag, that will give you the logs with tag as specified in with priority "Debug" and Above.
String command = "logcat Your_Tag:D *:S";
Process process = Runtime.getRuntime().exec(command);
Check more on http://developer.android.com/tools/debugging/debugging-log.html
You can easily filter the line that you want to write like the code below:
while ((line = bufferedReader.readLine()) != null) {
if(line.contains("The String you want to exist in your log")){
writer.write(line + "\n");
}
else{continue;}
}

Adding file contents to an ArrayList; Android

What I am trying to accomplish is to read a file line by line and store each line into an ArrayList. This should be such a simple task but I keep running into numerous problems. At first, it was repeating the lines when it was saved back into a file. Another error which seems to occur quite often is that it skips the try but doesn't catch the exception? I have tried several techniques but no luck. If you have any advice or could provide help in anyway it would be greatly appreciated. Thank you
Current code:
try{
// command line parameter
FileInputStream fstream = new FileInputStream(file);
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
fileList.add(strLine);
}
//Close the input stream
in.close();
} catch (Exception e){//Catch exception if any
Toast.makeText(this, "Could Not Open File", Toast.LENGTH_SHORT).show();
}
fileList.add(theContent);
//now to save back to the file
try {
FileWriter writer = new FileWriter(file);
for(String str: fileList) {
writer.write(str);
writer.write("\r\n");
}
writer.close();
} catch (java.io.IOException error) {
//do something if an IOException occurs.
Toast.makeText(this, "Cannot Save Back To A File", Toast.LENGTH_LONG).show();
}
There is a very simple alternative to what you are doing with Scanner class:
Scanner s = new Scanner(new File("filepath"));
ArrayList<String> list = new ArrayList<String>();
while (s.hasNext()){
list.add(s.next());
}
s.close();
Why do you have fileList.add(theContent) after the try/catch? I don't see what the point of that is. Remove that line and see if it helps.
Example, I just tested this code on my local machine (not android but should be the same)
import java.io.*;
import java.util.ArrayList;
class FileRead
{
public static void main(String args[])
{
ArrayList<String> fileList = new ArrayList<String>();
final String file = "textfile.txt";
final String outFile = "textFile1.txt";
try{
FileInputStream fstream = new FileInputStream(file);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
fileList.add(strLine);
}
//Close the input stream
in.close();
} catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
try {
FileWriter writer = new FileWriter(outFile);
for(String str: fileList) {
writer.write(str);
writer.write("\r\n");
}
writer.close();
} catch (java.io.IOException error) {
System.err.println("Error: " + error.getMessage());
}
}
}
After I ran this the 2 files had no differences. So my guess is that line may have something to do with it.

Writing/Reading Files to/from Android phone's internal memory

I have an utility class named 'MyClass'. The class has two methods to read/write some data into phone's internal memory. I am new to android, Please follow below code.
public class MyClass {
public void ConfWrite() {
try {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(new
File(getFilesDir()+File.separator+"MyFile.txt")));
bufferedWriter.write("lalit poptani");
bufferedWriter.close();
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
while executing ConfWrite method, it fails
please provide a better solution to solve this
thanks in advance
You can Read/ Write your File in data/data/package_name/files Folder by,
To Write
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(new
File(getFilesDir()+File.separator+"MyFile.txt")));
bufferedWriter.write("lalit poptani");
bufferedWriter.close();
To Read
BufferedReader bufferedReader = new BufferedReader(new FileReader(new
File(getFilesDir()+File.separator+"MyFile.txt")));
String read;
StringBuilder builder = new StringBuilder("");
while((read = bufferedReader.readLine()) != null){
builder.append(read);
}
Log.d("Output", builder.toString());
bufferedReader.close();
public static void WriteFile(String strWrite) {
String strFileName = "Agilanbu.txt"; // file name
File myFile = new File("sdcard/Agilanbu"); // file path
if (!myFile.exists()) { // directory is exist or not
myFile.mkdirs(); // if not create new
Log.e("DataStoreSD 0 ", myFile.toString());
} else {
myFile = new File("sdcard/Agilanbu");
Log.e("DataStoreSD 1 ", myFile.toString());
}
try {
File Notefile = new File(myFile, strFileName);
FileWriter writer = new FileWriter(Notefile); // set file path & name to write
writer.append("\n" + strWrite + "\n"); // write string
writer.flush();
writer.close();
Log.e("DataStoreSD 2 ", myFile.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
public static String readfile(File myFile, String strFileName) {
String line = null;
try {
FileInputStream fileInputStream = new FileInputStream(new File(myFile + "/" + strFileName)); // set file path & name to read
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream); // create input steam reader
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) { // read line by line
stringBuilder.append(line + System.getProperty("line.separator")); // append the readed text line by line
}
fileInputStream.close();
line = stringBuilder.toString(); // finially the whole date into an single string
bufferedReader.close();
Log.e("DataStoreSD 3.1 ", line);
} catch (FileNotFoundException ex) {
Log.e("DataStoreSD 3.2 ", ex.getMessage());
} catch (IOException ex) {
Log.e("DataStoreSD 3.3 ", ex.getMessage());
}
return line;
}
use this code to write --- WriteFile(json); // json is a string type
use this code to read --- File myFile = new File("sdcard/Agilanbu");
String strObj = readfile(myFile, "Agilanbu.txt");
// you can put it in seperate class and just call it where ever you need.(for that only its in static)
// happie coding :)

Categories

Resources