📄 log.java
字号:
package anni.tools;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
/**
* 日志.
*
* @author Lingo
* @version 1.0
* @since 2006-01-02 23:24
*/
public final class Log {
/**
* 日志文件最大限度.
*/
public static final int LOG_FILE_MAX_SIZE = 1024 * 1024;
/**
* 日志显示的时间格式.
*/
private static SimpleDateFormat sdf = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
/**
* 日志文件的时间格式.
*/
private static SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");
/**
* 日志文件个数.
*/
private static int count = 0;
/**
* 今天.
*/
private static Calendar today = Calendar.getInstance();
/**
* 现在.
*/
private static Calendar now;
/**
* 默认的日期文件.
*/
private static File logFile = new File("log.txt");
/**
* 工具类隐藏构造方法.
*/
private Log() {
}
/**
* info级别的日志.
* @param obj 信息
*/
public static void info(final Object obj) {
now = Calendar.getInstance();
check();
Throwable t = new Throwable();
StackTraceElement[] element = t.getStackTrace();
String msg;
if (obj == null) {
msg = null;
} else {
msg = obj.toString();
}
String message = "[" + sdf.format(now.getTime()) + "]["
+ element[1].getClassName() + "]["
+ element[1].getMethodName() + "] : " + msg;
System.out.println(message);
PrintWriter out = null;
try {
out = new PrintWriter(new FileWriter(logFile, true));
out.println(message);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (out != null) {
out.flush();
out.close();
out = null;
}
}
}
/**
* 检测日志文件是否超过最大限制.
*/
private static void check() {
long len = logFile.length();
if (len > LOG_FILE_MAX_SIZE) {
count++;
File destFile = new File("log_" + sdf2.format(today) + "_"
+ count + ".txt");
logFile.renameTo(destFile);
logFile = new File("log.txt");
}
if (today.DAY_OF_MONTH < now.DAY_OF_MONTH) {
today = now;
count = 0;
}
}
/**
* 测试用的main方法.
* @param args 参数列表
*/
public static void main(final String[] args) {
Log.info("test");
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -