Android: a library to write log on file?

9.5k views Asked by At

I have to write log on file and send it to the server every each app restart, or when the number of log file is enough. After internet research: I have found Timber and java.util.logging.Logger. I think to create a custom Timber tree and to use Logger to save the log on file. Are there a library already do this maybe in better way ? :D Maybe tinylog ?

This is my poc:

private const val SIZE_LIMIT = 10000
private const val NB_FILE_LIMIT = 3

object TimberLogImplementation : TimberLog{

    override fun init(context: Context) {
        val path: String = File(context.getExternalFilesDir("MyLog"),"log").absolutePath
        val TAG = "FileLoggerTree"
        val fileHandler: FileHandler
        val logger: Logger = MyLogger(TAG)
        logger.level = Level.ALL
        if (logger.handlers.isEmpty()) {
            fileHandler = FileHandler(path, SIZE_LIMIT, NB_FILE_LIMIT, false)
            fileHandler.formatter = SimpleFormatter()
            logger.addHandler(fileHandler)
        } else {
            fileHandler = logger.handlers[0] as FileHandler
        }
        val fileLoggerTree =  FileLoggerTree(logger)
        Timber.plant(fileLoggerTree)
    }

}


class FileLoggerTree(
    private val logger: Logger
) : Timber.Tree() {

    override fun log(priority: Int, tag: String?, message: String, t: Throwable?) {
        logger.log(fromPriorityToLevel(priority), message)
    }

    private fun fromPriorityToLevel(priority: Int): Level {
        return when (priority) {
            Log.VERBOSE -> Level.FINER
            Log.DEBUG -> Level.FINE
            Log.INFO -> Level.INFO
            Log.WARN -> Level.WARNING
            Log.ERROR -> Level.SEVERE
            Log.ASSERT -> Level.SEVERE
            else -> Level.FINEST
        }
    }
}

class MyLogger(name: String): Logger(name, null)

But I don't know if is oversized

2

There are 2 answers

1
Rashiq On

Try this custom class,

public class ErrorLogWriter {
    private static String FolderName = "folderName";
    private static String logFileName = "filename.txt";

    public static void appendLog(String formName, int lineNumber, String error) {
        try {
            File logFolder = new File("Directory path", FolderName);
            if (!logFolder.exists()) {
                logFolder.mkdirs();
            }
            File logFile = new File(logFolder, logFileName);
            if (!logFile.exists()) {
                logFile.createNewFile();
            }
            //BufferedWriter for performance, true to set append to file flag
            BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
            Calendar calendar = Calendar.getInstance();
            buf.append(new SimpleDateFormat(Constants.DATE_FORMAT_TO_SAVE, Locale.getDefault()).format( calendar.getTime()));
            buf.append(" - ");
            buf.append(formName);
            buf.append(" - ");
            buf.append(String.valueOf(lineNumber));
            buf.append(" - ");
            buf.append(error);
            buf.newLine();
            buf.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
0
Khongor Bayarsaikhan On

Here is a Timber extension lib that has a FileLoggerTree:

https://github.com/bastienpaulfr/Treessence