栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

使用java实现日志工具类分享

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用java实现日志工具类分享

复制代码 代码如下:
package com.teligen.eos.teleCode;

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


public class WriteLogUtil {

 private static String rootPath = "D:\logs\";

 
 public static void writeMsgToFile(String msg) {
  //删除之前的文件
  delOldFile();

  FileWriter fileWriter = null;
  try {
   fileWriter = new FileWriter(getFileName(),true);
   Date today = new Date();
   String time = String.valueOf(today.getHours()) + ":" + String.valueOf(today.getMinutes()) + " " + String.valueOf(today.getSeconds());
   fileWriter.write("#" + time + "# [" + msg + "]" + "rn");
   fileWriter.flush();
  } catch (IOException e) {
   System.out.println("### 写日志到文件异常 ### >>> " + e.getMessage());
   e.printStackTrace();
  } finally {
   try {
    fileWriter.close();
   } catch (IOException e) {
    System.out.println("### 关闭写日志的流异常 ### >>> " + e.getMessage());
    e.printStackTrace();
   }
  }
 }

 
 private static void delOldFile() {
  Date today = new Date();
  int month = today.getMonth()+1;
  month = month - 2;
  if(month == -1) month = 11;
  if(month == 0) month = 12;
  String delPath = rootPath + String.valueOf(month) + "\";
  File folder = new File(delPath);
  if(folder.exists()) {
   File[] files = folder.listFiles();
   for(int i=0; i    files[i].delete();
   }
  }
 }

 
 private static String getFileName() {
  Date today = new Date();
  String fileName = String.valueOf((today.getYear()+1900)) + String.valueOf((today.getMonth()+1)) + String.valueOf(today.getDate()) + ".log";

  
  //创建目录
  File folder = new File(rootPath + String.valueOf((today.getMonth()+1)) + "\");
  if(!folder.exists()) {
   folder.mkdirs();
  }
  //创建文件
  File file = new File(fileName);
  if(!file.exists()) {
   try {
    file.createNewFile();
   } catch (IOException e) {
    System.out.println("### 新建日志文件异常 ### >>> " + e.getMessage());
    e.printStackTrace();
   }
  }

  fileName = rootPath + String.valueOf((today.getMonth()+1)) + "\" + fileName;

  return fileName;
 }

 
 public static void main(String[] args) {
  //getFileName();
  String testString = "写日志咯:71FABB7890D2CC0D267FBD84F409618C0303BC597B9244C324947BDE4B1C0B4CB08C33FC461F7BADD088535DAE42D8D7D06F4134E442D9D1CE3A0F9B3EDD64337A2D18CE34FCDC137B7CBD84F409618C03038FEAEC79F79C2F58BD84F409618C03038FEAEC79F79C2F58BD84F409618C03038FEAEC79F79C2F581790ACB3C178641D14D8C09905BC52CF1C8249B12F2EDE5AC3C8FAF2FD8A686E";
  writeMsgToFile(testString);
  //delOldFile();
 }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/152336.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号