Skip to content

Commit

Permalink
Update 2014-3-3-Hello-World.md
Browse files Browse the repository at this point in the history
  • Loading branch information
zsu authored Oct 4, 2019
1 parent e967f02 commit 4584b8e
Showing 1 changed file with 78 additions and 6 deletions.
84 changes: 78 additions & 6 deletions _posts/2014-3-3-Hello-World.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,82 @@
---
layout: post
title: You're up and running!
title: NLog config in multiple environments deployment
---

Next you can update your site name, avatar and other options using the _config.yml file in the root of your repository (shown below).

![_config.yml]({{ site.baseurl }}/images/config.png)

The easiest way to make your first post is to edit this one. Go into /_posts/ and update the Hello World markdown file. For more instructions head over to the [Jekyll Now repository](https://github.com/barryclark/jekyll-now) on GitHub.
Nlog doesn't support multiple environments config files. But we can reconfig it during run time based on the current asp.net core environment setting.
- Add settings to asp.net core environment specific congig files(appsettings.Production.json):
```
"Logging": {
"NLog": {
"LogLevels": {
"Default": "Error",
"Sql": "Error"
}
}
}
```
- Read settings and reconfig in Startup.cs
```
public void UpdateLogLevel()
{
try
{
string logLevelSettingPrefix = KeySettingLogPrefix;
LogManager.Configuration = LogManager.Configuration.Reload();
var logLevels = _configuration.GetSection("Logging:NLog:LogLevels").GetChildren();
foreach (var item in logLevels)
{
if (!string.IsNullOrWhiteSpace(item.Value))
ChangeLogLevel(item.Key, item.Value);
}
var settings = Settings;
var logLevelSettings = settings.AsQueryable().Where(x => x.Name.Trim().ToLower().StartsWith(KeySettingLogPrefix)).ToList();
LogManager.ReconfigExistingLoggers();
}
catch (Exception ex)
{
_logger.LogError(ex, string.Empty);
}
}
private void ChangeLogLevel(string ruleName, string logLevel)
{
if (string.IsNullOrWhiteSpace(ruleName))
{
_logger.LogError("Rule name cannot be empty.");
return;
}
if (string.IsNullOrWhiteSpace(logLevel))
{
_logger.LogError("Loglevel cannot be empty.");
return;
}
NLog.LogLevel level = null;
try
{
level = NLog.LogLevel.FromString(logLevel);
}
catch (Exception ex)
{
_logger.LogError(ex, $"Invalid Loglevel {logLevel}.");
return;
}
var rules = LogManager.Configuration.LoggingRules;//.Where(x => x.NameMatches(loggerName));
foreach (var rule in rules)
{
if (rule.RuleName?.ToLower() == ruleName.ToLower())
{
rule.SetLoggingLevels(level, NLog.LogLevel.Fatal);
//// Iterate over all levels up to and including the target, (re)enabling them.
//for (int i = level.Ordinal; i <= 5; i++)
//{
// rule.EnableLoggingForLevel(LogLevel.FromOrdinal(i));
//}
}
}
}
...
public void ConfigureServices(IServiceCollection services)
{
UpdateLogLevel();
}
```

0 comments on commit 4584b8e

Please sign in to comment.