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(); } }