package net.dncsoft.test;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class MyLog {
private static final String logFileName_ = "C:\\tianyu.log";
private static long lastTimestamp = 0L;
private static long firstTimestamp = 0L;
public static synchronized void start() {
lastTimestamp = new Date().getTime();
firstTimestamp = lastTimestamp;
try {
FileWriter writer = new FileWriter(logFileName_, true);
PrintWriter out = new PrintWriter(writer);
out.println("-----------------------------------------------------");
out.close();
writer.close();
} catch (Exception localException) {
localException.printStackTrace();
}
}
public static synchronized void log(String p_msg) {
try {
long nowTimestamp = new Date().getTime();
FileWriter writer = new FileWriter(logFileName_, true);
PrintWriter out = new PrintWriter(writer);
Calendar cal = Calendar.getInstance();
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd-hh:mm:ss-SSS");
DecimalFormat decimalFormat = new DecimalFormat("####");
out.print(dateFormat.format(cal.getTime()) + "\t");
out.print(decimalFormat.format(nowTimestamp - lastTimestamp) + "\t");
out.print(decimalFormat.format(nowTimestamp - firstTimestamp) + "\t");
out.println(p_msg);
out.close();
writer.close();
lastTimestamp = nowTimestamp;
} catch (Exception localException) {
localException.printStackTrace();
}
}
}
C#版
private readonly object syncLock = new object();
void MyLog(string msg, [System.Runtime.CompilerServices.CallerFilePath] string filePath = "", [System.Runtime.CompilerServices.CallerLineNumber] int lineNumber = 0)
{
lock (syncLock)
{
System.IO.FileStream LogFile = new System.IO.FileStream(@"C:\temp\tian.log.txt ", System.IO.FileMode.Append);
System.IO.StreamWriter LogStream = new System.IO.StreamWriter(LogFile);
LogStream.WriteLine(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss-") + lineNumber + ":" + msg);
LogStream.Close();
LogFile.Close();
}
}
本文介绍了一个简单的日志记录工具实现,分别用Java和C#两种语言进行编码。该工具能够记录时间戳及自定义消息,并将这些信息写入到指定的日志文件中,便于后续的应用程序维护和调试。
2万+

被折叠的 条评论
为什么被折叠?



