我想将不同任务中的所有日志记录到不同的日志文件中,如下面的代码片段所述。但是使用以下代码,它会将日志写入到在不同任务中创建的所有日志文件中,但是为任务编写的日志将合并到由不同任务编写的日志中。
private static string logFile;
private static void CreateEmptyFile(string filename)
{
if (!File.Exists(filename))
{
File.Create(filename).Dispose();
}
}
private static void Log(string logMessage, string path)
{
string timeStamp = String.Format("{0} {1} - ", DateTime.Now.ToLongDateString(), DateTime.Now.ToLongTimeString());
File.AppendAllText(path, timeStamp + logMessage + Environment.NewLine);
}
private static void TaskMethod1(arg1)
{
// It calls a bunch of functions and they all log to logfile and all these operation including bunch of functions called(they also log using Log method)
logFile = DateTime.Now.ToFileTime() + ".txt";
CreateEmptyFile(logFile);
Log("TaskMethod1", logFile);
}
private static async Task TaskMethod()
{
while(runningService)
{
// Thi will create more than one task in parallel to run and each task can take upto 30 minutes to finish. Based on some condition the upper limit for parallel tasks can go upto 10.
Task.Run(() => TaskMethod1(arg1);
}
}
internal static void Start()
{
runningService = true;
Task1 = Task.Run(() => TaskMethod());
}
我希望将不同任务的所有日志文件分开,并且一个任务的内容不要与另一任务的内容合并。我怀疑这是因为全局变量logFile
在创建新任务时会更改其值,但是我不确定,这是因为将日志写入其他任务的日志的原因吗?如果那是问题,我该如何解决?我是否应该将logFile
作为参数传递给每个函数,而不是全局声明它。
您可以在启动任务之前指定日志文件名,并将其作为参数传递给辅助函数:
private static async Task TaskMethod()
{
while (runningService)
{
// I am assuming this is not your original code which would create
// a huge amount of parallel tasks without any checks..
// if there is no sleep or no wait for synchronization,
// many tasks will be created in the same millisecond and will have
// the same log file name, which would be the least of your problems!
string logFile = DateTime.Now.ToFileTime() + ".txt";
Task.Run(() => TaskMethod1(arg1, logFile));
}
}
现在您的TaskMethod1应该看起来像:
// Does not compile. I only add the new string type parameter to the end.
// Your code is not complete, so the answer has to assume that you
// understand that only one string logFile parameter is appended to the
// end of your parameter list
private static void TaskMethod1(arg1, string logFile)
{
CreateEmptyFile(logFile);
Log("TaskMethod1", logFile);
}