Hippias Minor
Hippias Minor

Reputation: 1967

Log to different files with NLog and configure it with NLog Config XML

For some business purposes I have to create different log files and write them to different files. [1 to 1000 dynamically change] .It may be crazy but that is what the business wants.

I am able to manage it using NLog programatically : I create different Target for different log files programatically and create named loggers for each of them.

The problem is that now I am not able to configure NLog externally : Suppose that I will change log files layout. [ Now I should do it from code ] I should have to create my own config file which I do not want.

I try to write to use NConfig file variable definition, but NLog does not allow to reach variable definitions from code.

Is it possible [ any trick] to create loggers with different files with NLog Config file, without writing all logs-targets to NLog File? [ I am not able to add all loggers to Nlog config since I do not know how many I will create, but I have a pattern to create them ]

My Log File Creation Pattern :

I have different channels in my app : For each request I create a new channel with its own channel:

Upvotes: 1

Views: 1536

Answers (1)

Ilya
Ilya

Reputation: 23125

You can use single file target and incorporate a layout renderer into its fileName parameter. This target will choose one of the several files based on the value that layout renderer have provided.

<target xsi:type="File"
          layout="${message}"
          fileName="${baseDir}\Log\channel${channelId}.log"
          createDirs="true" />

where ${channelId} is the layout renderer which provides different value for each channel. This value should be obtained somehow from the context of the request.

You can look for the existing layout renderers to see if any of them fits your needs or write your own specific renderer.

Upvotes: 2

Related Questions