Java 简易Logger工具类,服务器日志文件

2019-11-25  本文已影响0人  刘坤林

为保存服务器的操作记录以及一些必要的信息记录,建立此工具类。

大分组 2019-11,以下按日生成txt日志。

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.OutputStreamWriter;

import java.text.SimpleDateFormat;

import java.util.Date;

public class Logger {

private static Logger l;

private static final String base_path="D:\\logs\\car_rent";

private static final SimpleDateFormat sdf_year_month = new SimpleDateFormat("yyyy-MM");

private static final SimpleDateFormat sdf_day = new SimpleDateFormat("dd");

public static Logger instance() {

if(l==null) {

synchronized (Logger.class) {

if(l==null) {

l=new Logger();

}

}

}

return l;

}

private Logger() {

File filebase=new File(base_path);

if(!filebase.exists()) {

filebase.mkdir();

}

}

private String today;

private String month_path;

private String current_path;

public void out(String message) {

try {

Date date=new Date();

today=sdf_day.format(date);

month_path = base_path + "\\" + sdf_year_month.format(date);

File file=new File(month_path);

if(!file.exists()) {

file.mkdir();

}

current_path = month_path + "\\" + today+".txt";

file=new File(current_path);

FileOutputStream fos=null;

if(!file.exists()) {

file.createNewFile();

fos = new FileOutputStream(file);

}else {

fos = new FileOutputStream(file, true);

}

OutputStreamWriter osw = new OutputStreamWriter(fos, "utf-8");

osw.write("["+MySystem.getLogTime()+"] ");

osw.write(message);

osw.write("\r\n");  //换行

try {

if (osw != null) {

osw.close();

}

        } catch (IOException e) {

        System.err.println(e.getMessage());

        }

try {

if (fos != null) {

fos.close();

}

}catch (IOException e) {

System.err.println(e.getMessage());

        }

System.out.println("[日志保存成功]["+message+"]");

}catch(Exception e) {

System.err.println("无法输出日志["+message+"]["+e.getMessage()+"]");

}

}

}

上一篇下一篇

猜你喜欢

热点阅读