(java入门) MyLog

本文介绍了一个简单的日志记录工具实现,分别用Java和C#两种语言进行编码。该工具能够记录时间戳及自定义消息,并将这些信息写入到指定的日志文件中,便于后续的应用程序维护和调试。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值