Android Performance

Android Tools - Log2File

Word count: 427Reading time: 2 min
2014/05/02
loading

Log2File is a utility class for Android applications to record logs to a file (such as the SD card).

Usage Scenarios:

  1. Unable to connect to a computer for debugging (e.g., USB port is occupied by USB OTG).
  2. Logs are difficult to capture in real-time.
  3. Bugs appear randomly and are not easily reproducible.
  4. Other scenarios where persistent logging is needed.

0. Introduction

This article was originally published on my CSDN blog: http://blog.csdn.net/grackergao/article/details/18322749. I have now migrated it here. The source code is available on Github: https://github.com/Gracker/Android-Utils/blob/master/Log2File.java.

1. Log2File Source Code

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;

import android.content.Context;
import android.os.Environment;

public class Log2File
{
    private static boolean  logInit;
    private static BufferedWriter writer;

    private Log2File()
    {
    
    }
    
    /**
     * Initialize Log and create log file
     * @param ctx Context
     * @param fileName Name of the log file
     * @return boolean Success or failure
     */
    public static boolean init(Context ctx, String fileName)
    {
        if(!logInit)
        {           
            String state = Environment.getExternalStorageState();
            if (Environment.MEDIA_MOUNTED.equals(state))
            {
                File sdDir = Environment.getExternalStorageDirectory();
                File logDir = new File(sdDir.getAbsolutePath() + "/log2file/" + 
                        ctx.getPackageName() + "/");
    
                try {
                    if(!logDir.exists())
                    {
                        logDir.mkdirs();
                    }
    
                    File logFile = new File(logDir, fileName);
                    logFile.createNewFile();
    
                    writer = new BufferedWriter(new FileWriter(logFile, true));
                    logInit = true;
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
    
            }
    
        }
    
        return logInit;
    }
    
    /**
     * Write a log message
     * @param msg The message to log
     */
    public static void w(String msg)
    {
        if(logInit)
        {
            try {
                Date date = new Date();
                writer.write("[" + date.toLocaleString() + "] " + msg);
                writer.newLine();
                writer.flush();
            } catch (IOException e) {
                // TODO Auto-generated catch block
            }
        }
    }
    
    /**
     * Close the log writer
     */
    public static void close()
    {
        if(logInit)
        {
            try {
                writer.close();
                writer = null;
    
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    
            logInit = false;
        }
    }
}

2. Usage

Using this utility class is quite simple.

  1. First, call init to initialize:
    Log2File.init(context, fileName);
  2. Call w() to output logs:
    Log2File.w(String msg);
  3. After usage, remember to close the Log:
    Log2File.close();

About Me && Blog

Below is my personal intro and related links. I look forward to exchanging ideas with fellow professionals. “When three walk together, one can always be my teacher!”

  1. Blogger Intro: It includes my WeChat and WeChat group links.
  2. Blog Content Navigation: A guide for my blog content.
  3. Curated Excellent Blog Articles - Android Performance Optimization Must-Knows: Welcome self-recommendations and recommendations (just message me on WeChat).
  4. Android Performance Optimization Knowledge Planet: Welcome to join, thanks for your support~

One walks faster alone, but a group walks further together.

Scan WeChat QR Code

CATALOG
  1. 1. 0. Introduction
  2. 2. 1. Log2File Source Code
  3. 3. 2. Usage
  • About Me && Blog