c#并行处理,将每个线程记录到一个单独的文件中

时间:2015-10-27 14:28:07

标签: c# .net multithreading logging enterprise-library-6

我有一个并行的ForEach调用另一个方法进行一些处理,在另一个方法中我使用Enterprise Logging。 目前日志全部转到一个文件,我希望每个线程创建自己的日志文件,至少每个满足特定条件的线程都有自己的日志文件。这可以通过Enterprise日志记录实现。 我想我可以在配置文件中定义多个开关,然后在日志记录中使用这些开关,这样可以正常工作

现行守则

                Parallel.ForEach(
                listOfAccounts,
                new ParallelOptions { MaxDegreeOfParallelism = 10},
                accountId =>
                {
                    AccountProcess(accountId);
                });

这是一个名为:

的方法
    private void AccountProcess(int accountId)
    {
        string msgPrefix = MethodBase.GetCurrentMethod().DeclaringType.Name + "." + MethodBase.GetCurrentMethod().Name;

        _logWriter.WriteLog(msgPrefix, string.Format(" Starting AccountProcess method with accountId: {0} on threadID: {1}", accountId, Thread.CurrentThread.ManagedThreadId),
            "Information", 0, 0, TraceEventType.Information);

        try
        {
            _processor = new AccountProcessor(_logWriter);
            bool result = _processor.AccountProcess(accountId);
            _logWriter.WriteLog(msgPrefix, string.Format(" Account Process result: {0} on threadID: {1}", result.ToString(), Thread.CurrentThread.ManagedThreadId),
                "Information", 0, 0, TraceEventType.Information);
        }
        catch(Exception ex)
        {
            _logWriter.WriteLog(msgPrefix,
                string.Format("Error: {0}", ex.Message), "Error", 1, 1, TraceEventType.Error);
            bool rethrow = ExceptionPolicy.HandleException(ex, "Fatal");
            if (rethrow)
            {
                throw;
            }
        }
        finally
        {
            _processor = null;
        }
        _logWriter.WriteLog(msgPrefix, string.Format(" Completed AccountProcess method with accountId: {0} on threadID: {1}", accountId, Thread.CurrentThread.ManagedThreadId),
            "Information", 0, 0, TraceEventType.Information);
    }

在AccountProcess方法中,我想将每个线程记录到一个新文件中。 我是否需要为每个线程创建一个新的LogWriter实例,而不是使用Enterprise logging V6的单例。 _logWriter是Enterprise Logs版本6中LogWriter的Singleton实例的包装,或者需要使用多个开关。 我有三种类型的线程(每个线程都有一个基于accountID的属性。所以根据特定的类型,我可以使用特定的开关,例如。

  <add switchValue="Type1" name="Information">
    <listeners>
      <add name="Informational Listener"/>
    </listeners>
  </add>

  <add switchValue="Type2" name="Information">
    <listeners>
      <add name="Informational Listener"/>
    </listeners>
  </add>

  <add switchValue="Type3" name="Information">
    <listeners>
      <add name="Informational Listener"/>
    </listeners>
  </add>

这种方法有用吗?

0 个答案:

没有答案
相关问题