Search code examples
c#.net.net-6.0nlog

How to generate filename from message in NLog


I'm using NLog 5.2.4 My messages looks like this:

[127.0.0.1:50543]: Here comes some text ....
[127.0.0.1:50544]: Here comes some text ....

I want messages to be logged to files with name
test_127.0.0.1_50543.log
test_127.0.0.1_50544.log
and so on.

One of my attempts looked something like this:

<target xsi:type="AsyncWrapper" name="testAsync" queueLimit="50000" timeToSleepBetweenBatches="0" batchSize="500" overflowAction="Grow">
      <target name="testFile"
              layout="${longdate} ${level:uppercase=true} ${logger} ${message} ${exception:format=ToString:innerFormat=ToString:maxInnerExceptionLevel=5}"
              fileName="Log/test_${replace:regex=true:searchFor=^\\[(\\d+\\.\\d+\\.\\d+\\.\\d+\:\\d+)\\].*:replaceWith=\$1:input=${message}}.log"
              xsi:type="File"
              maxArchiveFiles="5"
              archiveAboveSize="10000000"
      />
    </target>

so far I get whole message in filename or nothing.

I have multiple objects and all of them have same ILogger.
Maybe I can add somehow custom attribute/variable/property in object for NLog to use?


Solution

  • Thanks to the @rolf-kristensen I was able to do it with

    fileName="logs/test_${event-properties:item=RemoteEndPoint}.log"
    

    in NLog.config

    And in the code I have

    Logger.LogTrace("[{RemoteEndPoint}]: startValue: {startValue}", RemoteEndPoint, startValue);