在工作中,我被要求找到一种创建自定义日志记录级别系统的方法,该系统将输出到.log文件。我发现了一种非常有效的方法,所以我想我会分享。请参阅我的回答
答案 0 :(得分:0)
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.UUID;
class FunctionLogging
{
private String path;
private boolean appendToFile = false;
public FunctionLogging(String file_path, boolean append_value)
{
path = file_path;
appendToFile = append_value;
}
public void writeToFile(int logType, String textLine) throws IOException
{
FileInputStream propFile = new FileInputStream("config.ini");
Properties config = new Properties(System.getProperties());
config.load(propFile);
String tempLev = config.getProperty("loggingLevel");
int logLevel = Integer.parseInt(tempLev);
if(logType<=logLevel)
{
//This section is devoted to creating a timestamp of the instance the output string is created.
Date date = new Date();
SimpleDateFormat format = new SimpleDateFormat();
format = new SimpleDateFormat("dd-MM-yyyy|HH:mm:ss:SSSSSS|");
String timeStamp = format.format(date);
SimpleDateFormat app = new SimpleDateFormat();
app = new SimpleDateFormat("dd-MM-yyyy");
String dateApp = app.format(date);
String temp = UUID.randomUUID().toString();
String unique = temp.substring(28);
String[] messages = new String[4];
messages[0]="DEBUG";
messages[1]="INFO";
messages[2]="Warning";
messages[3]="FATAL";
FileWriter logWriter = new FileWriter(path+dateApp+".log", appendToFile);
PrintWriter loggerLines = new PrintWriter(logWriter);
loggerLines.println(timeStamp+unique+"|"+messages[logType]+"|"+textLine);
loggerLines.close();
}
}
}
我目前只设置了4个可能的级别,可以根据设计师的偏好轻松扩展/缩小。
要使用它,请在将要记录的每个类的类级别中键入以下行(同样,这很容易更改)
FunctionLogging <variable of your choice = new FunctionLogget(path, true)
//true will append to the end of a file, false will overwrite it
//you will then write a line to it based on the variable you specified
<variable of your choice>.writeToFile(<custom integer>, "string action to logg");
这是打印信息的一个例子。
12-03-2015|17:09:33:000056|955aacb7|DEBUG|Application Started
12-03-2015|17:09:35:000144|b967ca48|INFO|Entered helper method
12-03-2015|17:09:37:000147|bc048c7b|WARNING|Be aware, error encountered but will continue
12-03-2015|17:09:39:000149|8eb7279c|FATAL|He's dead Dave, they're all dead Dave!