C#的System.Diagnostics.Trace.WriteLine 写入文件

Trace类和Debug类的区别在于Trace类会同时在Debug、Release模式下起作用,而Debug只作用在Debug模式下起作用。
在.NET平台,有很多优秀的日志类库,例如Log4Net。如果程序很小,也可以自己通过C#的Trace类来实现一个基本的日志记录功能。

private static void InitLog()
{
	try
	{
		string logpath = Path.Combine(Application.StartupPath, "log");
		if (!Directory.Exists(logpath))
			Directory.CreateDirectory(logpath);
		string logFileName = Path.Combine(logpath, Path.GetFileNameWithoutExtension(Application.ExecutablePath) + ".log");
		DeleteLogFile(logFileName, 1024 * 1024 * 3);//大于3M则清除
		TextWriterTraceListener traceLister = new TimeTextWriterTraceListener(logFileName);
		traceLister.TraceOutputOptions |= TraceOptions.DateTime;
		Trace.AutoFlush = true;
		Trace.Listeners.Add(traceLister);//注册Trace监听
	}
	catch (Exception)
	{
	}
}
		
private static void DeleteLogFile(string fileName, long fileSize)
{
	if (!File.Exists(fileName))
		return;
	try
	{
		var fileInfo = new System.IO.FileInfo(fileName);
		long fileInfoSize = fileInfo.Length;
		if (fileInfoSize > fileSize)
		{
			File.Delete(fileName);
		}
	}
	catch
	{
	}
}

internal class TimeTextWriterTraceListener : TextWriterTraceListener
{
	public TimeTextWriterTraceListener(string fileName)
		: base(fileName)
	{
	}

	public override void WriteLine(string message)
	{
		if (string.IsNullOrEmpty(message))
			return;

		try
		{
			if ((this.TraceOutputOptions & TraceOptions.DateTime) == TraceOptions.DateTime && message.IndexOf("========") == -1)
			{
				base.Write(DateTime.Now.ToString());
				base.Write(" ");
			}
			base.WriteLine(message);
		}
		catch (Exception)
		{
		}
	}
}

//使用
Trace.WriteLine($"=== run ===");

你可能感兴趣的:(c#,Trace)