Registering custom NLog target in code

Created a custom target, and wanted to add it in code, instead of adding it in nlog.config file, at least for now.

Documentation says all you need is this

ConfigurationItemFactory.Default.Targets.RegisterDefinition("myTarget", typeof(SignalRTarget));

 which is 1/3 of the story.

After some some googling and thinking I realized I probably need to specify a rule for the new target. This is the working code:

ConfigurationItemFactory.Default.Targets.RegisterDefinition("SignalRTarget", typeof(SignalRTarget)); 

LogManager.Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, new SignalRTarget())); 

LogManager.ReconfigExistingLoggers();

One thought on “Registering custom NLog target in code”

  1. Thanks for this, saved me some hair which I was about to start pulling out. I also tried to configure using xml which also mysteriously didn’t work.

Leave a Reply

Your email address will not be published. Required fields are marked *