java 后台实现记录日志的功能

1.编写实现记录日志的静态方法


To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
*/
package util;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
*记录日志

@author muicc
*/
public class TaskListUtil {
public static void wirteFile(String filePath,String conent){
BufferedWriter out = null;
try {
File file = new File(filePath);
if (!file.exists()) {
try {
File fileParent = file.getParentFile();
if (fileParent != null) {
if (!fileParent.exists()) {
fileParent.mkdirs();
}
}
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath, true), "UTF-8"));
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
out.write(sdf.format(date));
out.write(" " + conent);
out.write("\n");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

2.在需要记录日志的地方调用该方法
//记录日志
Date date = new Date();
SimpleDateFormat smpFormat = new SimpleDateFormat(“yyyyMMdd”);//记录日志的时间
String filename1=“D:\logs”+ smpFormat.format(date) + “/getHttpslogs”;//记录日志的地址
String s = “select * from staff s where s.account=’” + account + “’ and s.password=’” + password + “’”;
TaskListUtil.wirteFile(filename1, “记录登录账户:”+account);//调用方法记录日志
TaskListUtil.wirteFile(filename1, “记录登录密码:”+name);
TaskListUtil.wirteFile(filename1, “记录相关sql语句:”+s);
3.最后可在记录日志的地址中查看该日志

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 1024 设计师:上身试试 返回首页