6

Lets say I have the following in my nlog.config (taken from http://nlog-project.org/documentation/v2.0.1/html/T_NLog_Targets_MemoryTarget.htm):

<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
     <targets>
         <target name="memory" xsi:type="Memory" layout="${message}" />
     </targets>

     <rules>
         <logger name="*" minlevel="Info" writeTo="memory" />
    </rules>
</nlog>

How do I access this target programatically? I am trying to display the logs in a text box.

Andy Brown
  • 18,961
  • 3
  • 52
  • 62
Zeus82
  • 6,065
  • 9
  • 53
  • 77

4 Answers4

10

Exactly the same issue here, this worked for me:

var target =(MemoryTarget)LogManager.Configuration.FindTargetByName("memory");
var log = string.Join("\r\n", target.Logs);
txtLog.Text = log;
Thomas Weller
  • 55,411
  • 20
  • 125
  • 222
4

You can use LoggingConfiguration.FindTargetByName passing in the name of the target, then cast it to MemoryTarget, and use the Log property to get the logs gathered

Xharze
  • 2,703
  • 2
  • 17
  • 30
1

You can create your own target and process log entries as need: https://github.com/NLog/NLog/wiki/How-to-write-a-custom-target

Grault
  • 974
  • 12
  • 31
user3636971
  • 214
  • 1
  • 5
  • 1
    Why would he need to do that when NLog has a `MemoryTarget` already written for just this purpose? –  Nov 24 '15 at 14:45
  • 1
    With MemoryTarget you have to check manually/periodically for new log entries. Furthermore, maybe you have to filter leg entries which are already presented, or change the entire TextBox content, which is not very effective. With a custom target, you can notify a listener which can handle added log entries as required - append to the TextBox in that case! After all, it is just an alternative, but I do not agree with the downvote... – user3636971 Nov 27 '15 at 09:06
  • 1
    You were probably downvoted because you didn't answer the OPs very specific question. "How do I access this target programatically?" The answer isn't how to create a different kind of target. –  Nov 27 '15 at 20:47
1

Check here NLog manual http://nlog-project.org/documentation/v2.0.1/html/T_NLog_Targets_MemoryTarget.htm

 using System;

 using NLog;
 using NLog.Targets;

 class Example
 {
     static void Main(string[] args)
     {
        MemoryTarget target = new MemoryTarget();
        target.Layout = "${message}";
        //  target.Layout = "${longdate} ${level:uppercase=true} ${logger} ${message}";
        NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);

        Logger logger = LogManager.GetLogger("Example");
        logger.Debug("log message");

        foreach (string s in target.Logs)
        {
            Console.Write("logged: {0}", s);
        }
    }
}
NoWar
  • 36,338
  • 80
  • 323
  • 498