So I have a rather simple problem, but seems like I am missing something. I have a WPF application ( .NET Core 5.0 ).
I am trying to use 2 files for logging, but whenever I retrieve one logger and write a message, I get the same log in both files.
Here is my code.
private void SetupLogger()
{
// Step 1. Create configuration object
var config = new LoggingConfiguration();
// Step 2. Create targets
var firstTarget = new FileTarget()
{
Name = "FirstLogger",
FileName = Path.Combine(basePath, "log1.txt"),
Layout = "${longdate} ${level} ${message} ${exception}"
};
var secondTarget = new FileTarget()
{
Name = "SecondLogger",
FileName = Path.Combine(basePath, "log2.txt"),
Layout = "${longdate} ${level} ${message}"
};
config.AddTarget("FirstLogger", firstTarget );
config.AddTarget("SecondLogger", secondTarget );
var ruleInfo1 = new LoggingRule("*", NLog.LogLevel.Trace, firstTarget );
var ruleInfo2= new LoggingRule("*", NLog.LogLevel.Trace, secondTarget );
// Step 3. Define rules
config.LoggingRules.Add(ruleInfo1);
config.LoggingRules.Add(ruleInfo2);
// Step 4. Activate the configuration
LogManager.Configuration = config;
// Example usage
var logger = LogManager.GetLogger("FirstLogger");
logger.Info("App starting...");
}
In an other file I have a second log
public void Start()
{
//initialize app
var logger = LogManager.GetLogger("FirstLogger");
logger.Info("App finished initializing...");
}
Now what I see both logs in both files.
LE: I've tried this and it still logs to both files.
var ruleInfo1 = new LoggingRule("FirstLogger", LogLevel.Trace, firstTarget )
{
Final = true
};
var ruleInfo2 = new LoggingRule("*", LogLevel.Trace, secondTarget );
config.LoggingRules.Add(ruleInfo1);
config.LoggingRules.Add(ruleInfo2);
CodePudding user response:
That's correct.
The only difference between the two loggers is an exception.
You're not throwing any exceptions, and thus none will be logged.
CodePudding user response:
Logging-rules with wildcard *
for the Logger-name will match all loggers:
// Step 3. Define rules
var ruleInfo1 = new LoggingRule("*", NLog.LogLevel.Trace, firstTarget );
config.LoggingRules.Add(ruleInfo1);
var ruleInfo2 = new LoggingRule("*", NLog.LogLevel.Trace, secondTarget );
config.LoggingRules.Add(ruleInfo2);
Maybe change into this:
// Step 3. Define rules
var ruleErrors = new LoggingRule("*", NLog.LogLevel.Warn, firstTarget );
config.LoggingRules.Add(ruleErrors);
var ruleUsers = new LoggingRule("UserLog", NLog.LogLevel.Trace, firstTarget );
config.LoggingRules.Add(ruleUsers);
var ruleAll = new LoggingRule("*", NLog.LogLevel.Trace, secondTarget );
config.LoggingRules.Add(ruleAll);
Now the 3 rules will ensure:
- ruleErrors - Will redirect warnings/errors into firstTarget (Filter on LogLevel)
- ruleUsers - Will redirect events written to
LogManager.GetLogger("UserLog")
into firstTarget (Filter on Logger-name) - ruleAll - Will redirect all events to secondTarget (Without any filter)
See also: https://github.com/NLog/NLog/wiki/Configuration-file#rules