سؤال

I would like my application to repeatedly write a large amount of data to separate "log" files during the application lifetime. (Call each instance of such a file a "data file".) The data is written to this file in a single write operation (as it's a string). In the main application log file, the application would write the path name of the data file that it creates, so that I can identify that data file that was created at that point in its execution.

I could create the data file using the .NET file API, but I thought it would be useful to use NLog, as I could enable the writing of the file via configuration. However, I cannot see how to define a Target whose name is unique for each write operation. As an alternative, I could programmatically create a Target and add it to the LogManager's Configuration object each time I write a data file, and then delete the Target afterwards.

This seems plausible, but before implementing it I'd like to know if others had a similar requirement and how they implemented it.

هل كانت مفيدة؟

المحلول

You can configure NLog so that the name of the output file (in the case of using a file target) is "dynamic". You can use LayoutRenderers in the file name configuration. So, you could configure the target something like this:

  <targets>
    <target name="file" xsi:type="File" layout="${verbose}" fileName="${basedir}/${gdc:DataFile}.log" />
  </targets>

In your code you would do something like this:

NLog.GlobalDiagnosticsContext.Set("DataFile", "SomeName");

When NLog writes, it will resolve the file name. If the file exists, then the log will be written to that file. If the file does not exist, then NLog will create a new file. So, in your case, if you set a new value into the GlobalDiagnosticsContext dictionary before each write, you will get a new file. You can experiment with other LayoutRenders and see if you can get the behavior that you want for free. For example, if you used the CounterLayoutRenderer you could probably get a different file for every single write (I haven't tried it, so I can't say for sure).

You could configure it something like this:

  <targets>
    <target name="file" xsi:type="File" layout="${verbose}"fileName="${basedir}/${counter}.log" />
  </targets>

UPDATE - You can also use the CounterLayoutRenderer as the basis for a filename, rather than accept it as the entire filename.

  <targets>
    <target name="file" xsi:type="File" layout="${verbose}"fileName="${basedir}/MyDataStuff_${counter}.log" />
  </targets>

This will yield filenames like: MyDataStuff_0.log MyDataStuff_1.log MyDataStuff_2.log etc...

Using LayoutRenderers to build the output filename is pretty flexible, so you should be able to find a solution that meets your needs.

Maybe this will give you some ideas

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top