在 windows 服务中记录多个任务

Logging in case of multiple tasks in windows service

我想将不同任务中的所有日志记录到不同的日志文件中,如下面的代码片段所述。但是使用下面的代码,它会将日志写入在不同任务中创建的所有日志文件,但是为任务写入的日志会合并到不同任务写入的日志中。

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