Skip to content

Instantly share code, notes, and snippets.

@crearo
Created December 18, 2017 10:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crearo/c3b7e012dfcd9505fcccc0a6b5c2438a to your computer and use it in GitHub Desktop.
Save crearo/c3b7e012dfcd9505fcccc0a6b5c2438a to your computer and use it in GitHub Desktop.
Provides Android's Log.d() like logging for logging to files
package com.rish.imagestab.utils;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
/**
* Created by rish on 14/6/17.
* Helps log text to a file.
* Maintains list of created files, and keeps their InputStreams open until
* logAllFiles() is called.
*
* Syntactically this is similar to Android's Log.d(TAG, "text-to-log") method
* where you mention the TAG to log to, and the contents you'd like to log.
*
* In this, you call the FileLogger.log(file, "text-to-log").
*
* I usually maintain the file argument in another static class called BasePath.
*
* NOTE : This is not optimized, maybe not the right way to do this either.
* Do point out any mistakes!
*/
public class FileLogger {
private static FileLogger fileLogger;
private HashMap<String, FileLog> fileHashmap;
private FileLogger() {
fileHashmap = new HashMap<>();
}
public static FileLogger get() {
if (fileLogger == null) {
fileLogger = new FileLogger();
}
return fileLogger;
}
public void log(File file, String s) {
try {
if (fileHashmap.containsKey(file.getAbsolutePath())) {
fileHashmap.get(file.getAbsolutePath()).bufferedWriter.append(s + "\n");
} else {
if (!file.exists()) {
file.createNewFile();
}
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file, true));
FileLog fileLog = new FileLog(file, bufferedWriter);
fileHashmap.put(file.getAbsolutePath(), fileLog);
log(file, s);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void logAllFiles() {
for (String key : fileHashmap.keySet()) {
write(fileHashmap.get(key));
}
}
private void write(FileLog fileLog) {
try {
fileLog.bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private class FileLog {
private File file;
private BufferedWriter bufferedWriter;
public FileLog(File file, BufferedWriter bufferedWriter) {
this.file = file;
this.bufferedWriter = bufferedWriter;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment