我的应用使用的是c# FileLogTraceListener日志类记录日志,采用的是多线程,设置LogFileCreationScheduleOption.Daily用来每天生成新的日志文件。记录日志很正常,当我修改系统时间时(即会产生新的日志文件),就会抛出错误,如图所示。
我觉得是个bug,我查看源码能发现当调用CloseCurrentStream()函数时,m_Stream会被设置成null,造成了错误。FileLogTraceListener类在msdn上说的是 线程安全的,看来并非如此。大家觉得是什么原因?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Microsoft.VisualBasic.Logging;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("start");
Tracelog.StartTrace();
for (int i = 0; i < 10; i++)
{
Thread backthread = new Thread(new ThreadStart(Worker));
backthread.Start();
}
}
public static void Worker()
{
while (true)
{
//Console.WriteLine("start");
Tracelog.Trace(Tracelog.INFO, "test");
Thread.Sleep(10);
}
}
}
public class Tracelog
{
public static int INFO = 0;
public static int ERROR = 1;
public static FileLogTraceListener myListener;
//private static readonly object Lock = new object();
public static void StartTrace()
{
try
{
//lock (Lock)
{
myListener = new FileLogTraceListener("myListener");
myListener.LogFileCreationSchedule = LogFileCreationScheduleOption.Daily;
myListener.CustomLocation = "log";
myListener.BaseFileName = "log";
myListener.MaxFileSize = 10 * 1024 * 1024;
myListener.WriteLine("Trace start");
myListener.Flush();
}
}
catch (Exception e)
{
Console.WriteLine("StartTrace error" + e.ToString());
}
}
public static void Trace(int type, string message)
{
try
{
//lock (Lock)
{
myListener.WriteLine(message);
myListener.Flush();
}
}
catch (Exception e)
{
Console.WriteLine("Trace error message:" + e.ToString());
}
}
}
}