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();
}
Related
I am trying to make a demo app.
That download a image from my s3 server to my phones memory card.
I tried the demo codes and wrote the following. But the app force closes as soon as i run it on my phone.
Any help would be appreciated.
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
File f=null;
try{
File dir= Environment.getExternalStorageDirectory();
f= new File(dir,"test.jpg");
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), "Exception", Toast.LENGTH_SHORT).show();
}
AWSCredentials creden=new BasicAWSCredentials(accessKey,secretKey);
AmazonS3Client s3Client=new AmazonS3Client(creden);
ObjectMetadata obj= s3Client.getObject(new GetObjectRequest("adj-temp","funflick_1.jpg"),f);
}
Try this it will work Happy coding
{
String str_FilePathInDevice = "/sdcard/" + "/"
+ "RestoreFolderName" + "/" + "filname.extention";
File file = new File(str_FilePathInDevice);
String str_Path = file.getPath().replace(file.getName(), "");
File filedir = new File(str_Path);
try {
filedir.mkdirs();
} catch (Exception ex1) {
}
S3Object object = s3Client.getObject(new GetObjectRequest(
"BucketName", "keyName"));
BufferedReader reader = new BufferedReader(new InputStreamReader(
object.getObjectContent()));
Writer writer = new OutputStreamWriter(new FileOutputStream(file));
while (true) {
String line = reader.readLine();
if (line == null)
break;
writer.write(line + "\n");
}
writer.flush();
writer.close();
reader.close();
}
Could someone look at this snippet of code please and let me know what I'm doing wrong? It's a simple function that takes a string as parameter which it uses as a file name, adding ".txt" to the end of it.
The function checks if the file exists, creating it if it doesn't and then writes two lines of text to the file. Everything appears to be working and the file is created successfully on the sd card. However, after everything is done, the file is empty (and has a size of 0 bytes).
I suspect it's something obvious that I'm overlooking.
public void writeFile(String fileName) {
String myPath = new File(Environment.getExternalStorageDirectory(), "SubFolderName");
myPath.mkdirs();
File file = new File(myPath, fileName+".txt");
try {
if (!file.exists()) {
if (!file.createNewFile()) {
Toast.makeText(this, "Error Creating File", Toast.LENGTH_LONG).show();
return;
}
}
OutputStreamWriter writer = new OutputStreamWriter(openFileOutput(file.getName(), Context.MODE_PRIVATE));
writer.append("First line").append('\n');
writer.append("Second line").append('\n');
writer.close();
}
catch (IOException e) {
// Do whatever
}
}
Hi I will show you the full code I use, works perfect.
I don't use
new OutputStreamWriter()
i use
new BufferedWriter()
here is my Snippet
public void writeToFile(Context context, String fileName, String data) {
Writer mwriter;
File root = Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + File.separator + "myFolder");
if (!dir.isDirectory()) {
dir.mkdir();
}
try {
if (!dir.isDirectory()) {
throw new IOException(
"Unable to create directory myFolder. SD card mounted?");
}
File outputFile = new File(dir, fileName);
mwriter = new BufferedWriter(new FileWriter(outputFile));
mwriter.write(data); // DATA WRITE TO FILE
Toast.makeText(context.getApplicationContext(),
"successfully saved to: " + outputFile.getAbsolutePath(), Toast.LENGTH_LONG).show();
mwriter.close();
} catch (IOException e) {
Log.w("write log", e.getMessage(), e);
Toast.makeText(context, e.getMessage() + " Unable to write to external storage.",Toast.LENGTH_LONG).show();
}
}
-- Original Code --
That one took a while to find out. The javadocs
here brought me on the right track.
It says:
Parameters
name The name of the file to open; can not contain path separators.
mode Operating mode. Use 0 or MODE_PRIVATE for the default operation, MODE_APPEND to append to an existing file, MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE to control permissions.
The file is created, if it does not exist, but it is created in the private app space. You create the file somewhere on the sd card using File.createNewFile() but when you do context.openFileOutput() it creates always a private file in the private App space.
EDIT: Here's my code. I've expanded your method by writing and reading the lines and print what I got to logcat.
<pre>
public void writeFile(String fileName) {
try {
OutputStreamWriter writer = new OutputStreamWriter(
getContext().openFileOutput(fileName + ".txt", Context.MODE_PRIVATE));
writer.append("First line").append('\n');
writer.append("Second line").append('\n');
writer.close();
}
catch (IOException e) {
Log.e("STACKOVERFLOW", e.getMessage(), e);
return;
// Do whatever
}
// Now read the file
try {
BufferedReader is = new BufferedReader(
new InputStreamReader(
getContext().openFileInput(fileName + ".txt")));
for(String line = is.readLine(); line != null; line = is.readLine())
Log.d("STACKOVERFLOW", line);
is.close();
} catch (IOException e) {
Log.e("STACKOVERFLOW", e.getMessage(), e);
return;
// Do whatever
}
}
Change the mode from Context.MODE_PRIVATE to Context.MODE_APPEND in openFileOutput()
MODE_APPEND
MODE_PRIVATE
Instead of
OutputStreamWriter writer = new OutputStreamWriter(openFileOutput(file.getName(), Context.MODE_PRIVATE));
Use
OutputStreamWriter writer = new OutputStreamWriter(openFileOutput(file.getName(), Context.MODE_APPEND));
UPDATE :
1.
FileOutputStream osr = new FileOutputStream(file.getName(), true); // this will set append flag to true
OutputStreamWriter writer = new OutputStreamWriter(osr);
BufferedWriter fbw = new BufferedWriter(writer);
fbw.write("First line");
fbw.newLine();
fbw.write("Second line");
fbw.newLine();
fbw.close();
Or 2.
private void writeFileToInternalStorage() {
FileOutputStream osr = new FileOutputStream(file.getName(), true); // this will set append flag to true
String eol = System.getProperty("line.separator");
BufferedWriter fbw = null;
try {
OutputStreamWriter writer = new OutputStreamWriter(osr);
fbw = new BufferedWriter(writer);
fbw.write("First line" + eol);
fbw.write("Second line" + eol);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fbw != null) {
try {
fbw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I'm trying to write log statements to the sdcard. The way i have decided to do it is create a file on the sdcard through the Application Object. This way i can call a static method logToSdcard() from anywhere in the app.
The containing folder "/RR3log/" is created but every statement that i log is in its own file called "rr3LogFile.txt". So i have multiple rr3LogFile files containing one staement in each.
How can i write all statement to one rr3LogFile file? Thanks in advance Matt.
public class NfcScannerApplication extends Application{
#Override
public void onCreate() {
super.onCreate();
File storageDir = new File(Environment
.getExternalStorageDirectory(), "/RR3log/");
storageDir.mkdir();
try {
if(outfile == null){
outfile=File.createTempFile("rr3LogFile", ".txt",storageDir);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void logToSdcard(String tag, String statement){
Log.e(TAG, "inside logtosdcard$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
String state = android.os.Environment.getExternalStorageState();
if(!state.equals(android.os.Environment.MEDIA_MOUNTED)) {
try {
throw new IOException("SD Card is not mounted. It is " + state + ".");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
DateTime now = new DateTime();
DateTimeFormatter fmt = DateTimeFormat.forPattern("d-MMM-Y H:mm");
String dateStr = fmt.print(now);
try{
FileOutputStream fOut = new FileOutputStream(outfile);
OutputStreamWriter myOutWriter =new OutputStreamWriter(fOut);
myOutWriter.append(dateStr + " " + tag + " ");
myOutWriter.append(statement);
myOutWriter.append("\n");
myOutWriter.flush();
myOutWriter.close();
fOut.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
.
Then in an Activity anywhere in the app.
#Override
protected void onResume() {
super.onResume();
Log.e(TAG, "inside entryactivity onResume");
NfcScannerApplication.logToSdcard(TAG, "inside entryactivity onResume" );
In your logToSdcard Method create the FileOutputStream with an additional parameter:
FileOutputStream fOut = new FileOutputStream(outfile, true);
The true paramters says that contents will be appended to the file. See also FileOutputStream
Try that:
public static void printLog(Context context){
String filename = context.getExternalFilesDir(null).getPath() + File.separator + "my_app.log";
String command = "logcat -f "+ filename + " -v time -d *:V";
Log.d(TAG, "command: " + command);
try{
Runtime.getRuntime().exec(command);
}
catch(IOException e){
e.printStackTrace();
}
}
The logs will be saved continuously until the application is exited.
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");
}
}
In following code i want to crate a file in sdcard. but it not giving any valid output. showing only the hello world...Where the "file created" message will be displayed and where the file will be stored?
package com.read;
import java.io.FileOutputStream;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
public class read extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String FILENAME = "hello_file";
String string = "hello world!";
try{
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
}catch(Exception e){}
System.out.println("File created");
}
}
try below code might help you
try {
File root = Environment.getExternalStorageDirectory();
if (root.canWrite()){
File gpxfile = new File(root, "gpxfile.gpx");
FileWriter gpxwriter = new FileWriter(gpxfile);
BufferedWriter out = new BufferedWriter(gpxwriter);
out.write("Hello world");
out.close();
}
}catch (IOException e) {
Log.e(TAG, "Could not write file " + e.getMessage());
}
Note: For this to be working your emulator or device must have SDcard
Edit: For reading the file fromSDCard
try{
File f = new File(Environment.getExternalStorageDirectory()+"/filename.txt");
fileIS = new FileInputStream(f);
BufferedReader buf = new BufferedReader(new InputStreamReader(fileIS));
String readString = new String();
//just reading each line and pass it on the debugger
while((readString = buf.readLine())!= null){
Log.d("line: ", readString);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
Using this method you're trying to create a file in phone's internal memory.
Just use this code:
FileOuputStream fos = new FileOutputStream( "/sdcard/" + FILENAME );
It will create a file in a root folder of your SD card.