Android下的一个打log的java类

这是一个用于将Android应用的日志记录到文件系统的实用工具类。它使用单例模式,支持初始化指定的log路径,并能根据日期生成不同的日志文件。提供了不同级别的日志写入方法,如VERBOSE, DEBUG, INFO, WARN和ERROR。此外,还包含了文件流的打开、关闭以及写入操作。
摘要由CSDN通过智能技术生成
package com.example.yourapp.util;

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

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * 将Log日志写入文件中
 * <p>
 * 使用单例模式是因为要初始化文件存放位置
 * <p>
 * Created by daniel on 2021/6/14.
 */
public class LogToFile {

    private static String TAG = "YourApp";

    private static FileOutputStream fos = null;//FileOutputStream会自动调用底层的close()方法,不用关闭
    private static BufferedWriter bw = null;

    private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss", Locale.US);//日期格式

    /**
     * 初始化,须在使用之前设置,最好在Application创建时调用
     *
     * @param logPath log日志存放路径, null to use /sdcard/
     */
    public static void init(String logPath) {
        // 每init一次,关闭以前的log文件
        close();

        //
        if (logPath == null)
            logPath = "/sdcard";
        //如果父路径不存在
        File file = new File(logPath);
        if (!file.exists()) {
            file.mkdirs();//创建父路径
        }

        Date date = new Date();//因为log日志是使用日期命名的,使用静态成员变量主要是为了在整个程序运行期间只存在一个.log文件中
        String fileName = logPath + File.separator + dateFormat.format(date) + ".log";//log日志名,使用时间命名,保证不重复
        try {
            fos = new FileOutputStream(fileName);
            bw = new BufferedWriter(new OutputStreamWriter(fos));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        /*
        catch (IOException e) {
            e.printStackTrace();
        }
        */
    }

    /**
     * 获得文件存储路径
     *
     * @return
     */
    public static String getFilePath(Context context) {
        //不用Environment.getExternalStorageDirectory(),SD根目录:/mnt/sdcard/(6.0后写入需要用户授权)
        if (Environment.MEDIA_MOUNTED.equals(Environment.MEDIA_MOUNTED) || !Environment.isExternalStorageRemovable()) {//如果外部储存可用
            return context.getExternalFilesDir(null).getPath();//获得外部存储路径,默认路径为/storage/emulated/0/Android/data/<package name>/files/2016-03-14_16-15-09.log
            //return context.getExternalCacheDir().getAbsolutePath();
        } else {
            return context.getFilesDir().getPath();//直接存到/data/data/<package name>/files里,非root手机是看不到的
            //return context.getCacheDir().getAbsolutePath();
        }
    }

    private static final int VERBOSE = 'v';

    private static final int DEBUG = 'd';

    private static final int INFO = 'i';

    private static final int WARN = 'w';

    private static final int ERROR = 'e';

    public static void v(String tag, String msg) {
        writeToFile(VERBOSE, tag, msg);
    }

    public static void d(String tag, String msg) {
        writeToFile(DEBUG, tag, msg);
    }

    public static void i(String tag, String msg) {
        writeToFile(INFO, tag, msg);
    }

    public static void w(String tag, String msg) {
        writeToFile(WARN, tag, msg);
    }

    public static void e(String tag, String msg) {
        writeToFile(ERROR, tag, msg);
    }

    /**
     * 将log信息写入文件中
     *
     * @param type
     * @param tag
     * @param msg
     */
    public static void writeToFile(int type, String tag, String msg) {
        if (null == fos || null == bw) {
            Log.e(TAG, "未初始化LogToFile");
            return;
        }

        Date date = new Date();
        String log = dateFormat.format(date) + " " + type + " " + tag + " " + msg + "\n";//log日志内容,可以自行定制
        try {
            bw.write(log);
            bw.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将字节数组写入文件中
     *
     * @param dataBuffer
     */
    public static void writeToFile(byte[] dataBuffer, int offset, int length) {
        if (null == fos || null == bw) {
            Log.e(TAG, "未初始化LogToFile");
            return;
        }

        try {
            fos.write(dataBuffer, offset, length);
            fos.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void close() {
        try {
            if (fos != null) {
                fos.close();
                fos = null;
            }
            if (bw != null) {
                bw.close();//关闭缓冲流
                bw = null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

这个log类可以吐log到存储。写完了,但功能还需要进一步增强。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值