14

I am using NLog and I want to log to RichTextBox and File at the same time. And I want to configure the Logger programmatically, not with xml config file.

The following code only logs to the last target (File in this case). Can anybody help?

RichTextBoxTarget t1 = new RichTextBoxTarget();
t1.Layout = "${date} ${message}";
t1.ControlName = "rtb_log";
t1.FormName = "MainForm";
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(t1, LogLevel.Debug);

FileTarget t2 = new FileTarget(); 
t2.Layout = "${date} ${level} ${message}"; 
t2.FileName = "${basedir}/Logs/today.log"; 
t2.KeepFileOpen = false; 
t2.Encoding = "iso-8859-2"; 
NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(t2, LogLevel.Trace); 

Logger logger = LogManager.GetLogger("MyLogger");
Imran S.
  • 935
  • 3
  • 15
  • 32

2 Answers2

9

Okay I got it. I should've read the help file more before posting the question. But anyways, the answer is to use SplitTarget as follows...

RichTextBoxTarget t1 = new RichTextBoxTarget();
t1.Layout = "${date} ${message}";
t1.ControlName = "rtb_log";
t1.FormName = "MainForm";

FileTarget t2 = new FileTarget(); 
t2.Layout = "${date} ${level} ${message}"; 
t2.FileName = "${basedir}/Logs/today.log"; 
t2.KeepFileOpen = false; 
t2.Encoding = "iso-8859-2"; 

SplitTarget target = new SplitTarget(); 
target.Targets.Add(t1); 
target.Targets.Add(t2); 

NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);
Logger logger = LogManager.GetLogger("MyLogger");
Imran S.
  • 935
  • 3
  • 15
  • 32
  • This way still overwrites the rules, limiting you to one rule. Jason's answer seems more correct to me. – GraemeF Apr 21 '15 at 15:41
8

SimpleConfigurator overwrites all existing rules. In your example, you had 2 calls, so the first target got discarded.

Instead, you should manually add a target and logging rule and call Reload():

LogManager.Configuration.AddTarget (t1);
LogManager.Configuration.AddTarget (t2);
LoggingRule r1 = new LoggingRule ("*", LogLevel.Debug, t1);
LoggingRule r2 = new LoggingRule ("*", LogLevel.Trace, t2);
LogManager.Configuration.LoggingRules.Add (r1);
LogManager.Configuration.LoggingRules.Add (r2);
LogManager.Configuration.Reload ();
mafu
  • 31,798
  • 42
  • 154
  • 247
  • 2
    `LogManager.Configuration.Reload()` did not work for me; nothing was logged. What did work was declaring a new variable `var config = new LoggingConfiguration();`, do the above steps on `config`, then setting `LogManager.Configuration = config;`. The `Reload` doesn't work using Nlog 2.0.0.0. – David Ching Aug 28 '16 at 19:10