当前位置: 首页 > article >正文

Android开发:日志功能备忘

临时记一下吧,以后就直接复制粘贴这里面的好了。

实现一个日志记录程序的运行状态,并且带上时间信息,可以写一个类灵活调用。

MyLog.java

package com.example.networkaccessrestrictions;

import static android.content.ContentValues.TAG;

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

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class MyLog {
    private static final String LOG_FILE_NAME = "service_log.txt";//写入日志的文件名

    private Context context;

    // 构造函数,接收 Context
    public MyLog(Context context) {
        this.context = context;
    }

    public void writeLog(String message) {
        File logFile = new File(context.getFilesDir(), LOG_FILE_NAME); // 使用内部存储
        // 获取当前日期
        LocalDateTime currentDateTime = LocalDateTime.now();//注意这里用到的是currentDateTime,不是currentDate也不是currentDateTime

        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        // 格式化当前日期
        String formattedDateTime = currentDateTime.format(formatter);

        // 输出格式化后的日期
        //System.out.println("当前日期: " + formattedDateTime);

        try (FileWriter fileWriter = new FileWriter(logFile, true); // 以追加模式打开文件
             PrintWriter printWriter = new PrintWriter(fileWriter)) {

            printWriter.println(formattedDateTime + ":" + message); // 写入时间戳和消息
        } catch (IOException e) {
            Log.e(TAG, "Error writing to log file", e);
        }
    }
    
}

在其他代码里把活动写入日志时只需要

MyLog mylog=new MyLog(this);
mylog.writeLog("阿巴阿巴阿巴阿巴阿巴");

即可。

那么要上哪找这个日志文件呢?

直接去/data/data/your.package.name/files/ 目录下找日志就完事了。


http://www.kler.cn/news/339425.html

相关文章:

  • 回到原点再出发
  • 详解 Pandas 的 melt 函数
  • 【万字长文】Word2Vec计算详解(二)
  • 白盒和灰盒和黑盒测试
  • MFC多媒体定时器实例(源码下载)
  • 单片机教案 1.2 ATmega2560单片机和Arduino IDE编程基础
  • 易基因: cfMeDIP-seq揭示cfDNA甲基化高效区分原发性和转移性前列腺|Nat Commun
  • rust tokio在linux下面无法创建超过1000个线程问题解决
  • 【每日一题 | 24.10.8】确定字符串是否是另一个的排列
  • Python 卸载所有的包
  • C 数组
  • 宠物咖啡馆在线体验:SpringBoot技术的应用
  • PostgreSQL学习之有关身份鉴别的一些小想法
  • VMWare安装和基本使用NixOS Linux 24.05版本
  • 云岚到家,使用Elasticsearch实现服务的搜索功能,使用Canal+MQ完成服务信息与ES索引同步。MQ
  • 无人机避障——4DMmvRadar三维点云坐标转换到无人机坐标系(三)
  • 宠物咖啡馆在线互动:SpringBoot框架的创新实现
  • 【重学 MySQL】六十二、非空约束的使用
  • Linux-磁盘优化的几个思路
  • OJ在线评测系统 微服务 用分布式消息队列 RabbitMQ 解耦判题服务和题目服务 手搓交换机和队列 实现项目异步化