Skip to content

Commit

Permalink
Merge pull request #91 from nacos-group/dev
Browse files Browse the repository at this point in the history
improve logging of Nacos.Microsoft.Extensions.Configuration
  • Loading branch information
catcherwong authored Apr 18, 2021
2 parents 8c1ebb2 + 3f5d16f commit 5229ef7
Show file tree
Hide file tree
Showing 7 changed files with 69 additions and 36 deletions.
6 changes: 3 additions & 3 deletions samples/MsConfigApp/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public static void Main(string[] args)
try
{
Log.ForContext<Program>().Information("Application starting...");
CreateHostBuilder(args).Build().Run();
CreateHostBuilder(args, Log.Logger).Build().Run();
}
catch (System.Exception ex)
{
Expand All @@ -45,7 +45,7 @@ public static void Main(string[] args)
}
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
public static IHostBuilder CreateHostBuilder(string[] args, Serilog.ILogger logger) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((context, builder) =>
{
Expand All @@ -60,7 +60,7 @@ public static IHostBuilder CreateHostBuilder(string[] args) =>
// read configuration from config files
// default is json
// builder.AddNacosConfiguration(c.GetSection("NacosConfig"));
builder.AddNacosV2Configuration(c.GetSection("NacosConfig"));
builder.AddNacosV2Configuration(c.GetSection("NacosConfig"), logAction: x => x.AddSerilog(logger));

// specify ini or yaml
// builder.AddNacosConfiguration(c.GetSection("NacosConfig"), Nacos.IniParser.IniConfigurationStringParser.Instance);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
namespace Microsoft.Extensions.Configuration
{
using Microsoft.Extensions.Logging;
using Nacos.Config;
using Nacos.Microsoft.Extensions.Configuration;
using System;
Expand Down Expand Up @@ -40,11 +41,13 @@ public static IConfigurationBuilder AddNacosConfiguration(
/// <param name="builder">IConfigurationBuilder</param>
/// <param name="configuration">Configuration binding nacos configuration source</param>
/// <param name="parser">The parser.</param>
/// <param name="logAction">The logging action.</param>
/// <returns>IConfigurationBuilder</returns>
public static IConfigurationBuilder AddNacosConfiguration(
this IConfigurationBuilder builder,
IConfiguration configuration,
INacosConfigurationParser parser = null)
INacosConfigurationParser parser = null,
Action<ILoggingBuilder> logAction = null)
{
if (builder == null)
{
Expand All @@ -59,6 +62,7 @@ public static IConfigurationBuilder AddNacosConfiguration(
var source = new NacosConfigurationSource();
configuration.Bind(source);
source.NacosConfigurationParser = parser ?? DefaultJsonConfigurationStringParser.Instance;
source.LoggingBuilder = logAction;

return builder.Add(source);
}
Expand Down Expand Up @@ -97,11 +101,13 @@ public static IConfigurationBuilder AddNacosV2Configuration(
/// <param name="builder">IConfigurationBuilder</param>
/// <param name="configuration">Configuration binding nacos configuration source</param>
/// <param name="parser">The parser.</param>
/// <param name="logAction">The logging action.</param>
/// <returns>IConfigurationBuilder</returns>
public static IConfigurationBuilder AddNacosV2Configuration(
this IConfigurationBuilder builder,
IConfiguration configuration,
INacosConfigurationParser parser = null)
INacosConfigurationParser parser = null,
Action<ILoggingBuilder> logAction = null)
{
if (builder == null)
{
Expand All @@ -116,6 +122,7 @@ public static IConfigurationBuilder AddNacosV2Configuration(
var source = new NacosV2ConfigurationSource();
configuration.Bind(source);
source.NacosConfigurationParser = parser ?? DefaultJsonConfigurationStringParser.Instance;
source.LoggingBuilder = logAction;

return builder.Add(source);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
namespace Nacos.Microsoft.Extensions.Configuration
{
using global::Microsoft.Extensions.Configuration;
using global::Microsoft.Extensions.Logging.Abstractions;
using global::Microsoft.Extensions.Logging;
using Nacos.Config;
using System;
using System.Collections.Concurrent;
Expand All @@ -19,13 +19,18 @@ internal class NacosConfigurationProvider : ConfigurationProvider

private readonly ConcurrentDictionary<string, string> _configDict;

private readonly ILogger _logger;

public NacosConfigurationProvider(NacosConfigurationSource configurationSource)
{
_configurationSource = configurationSource;
_parser = configurationSource.NacosConfigurationParser;
_configDict = new ConcurrentDictionary<string, string>(StringComparer.OrdinalIgnoreCase);

_client = new NacosMsConfigClient(NullLoggerFactory.Instance, new NacosOptions
var nacosLoggerFactory = Nacos.Microsoft.Extensions.Configuration.NacosLog.NacosLoggerFactory.GetInstance(configurationSource.LoggingBuilder);
_logger = nacosLoggerFactory.CreateLogger<NacosConfigurationProvider>();

_client = new NacosMsConfigClient(nacosLoggerFactory, new NacosOptions
{
ServerAddresses = configurationSource.ServerAddresses,
Namespace = configurationSource.Tenant,
Expand Down Expand Up @@ -100,7 +105,7 @@ private void CallBackReload(string key, string val, bool optional)
}
catch (Exception ex)
{
System.Diagnostics.Trace.WriteLine($"call back reload config error, {ex.Message}");
_logger?.LogWarning(ex, $"call back reload config error");
if (!optional)
{
throw;
Expand Down Expand Up @@ -138,7 +143,7 @@ public override void Load()
}
catch (Exception ex)
{
System.Diagnostics.Trace.WriteLine($"MS Config Query config error, {listener.DataId} ,{ex.Message}");
_logger?.LogWarning(ex, "MS Config Query config error, dataid={0}, group={1}, tenant={2}", listener.DataId, listener.Group, listener.Tenant);
if (!listener.Optional)
{
throw;
Expand Down Expand Up @@ -168,7 +173,7 @@ public override void Load()
}
catch (Exception ex)
{
System.Diagnostics.Trace.WriteLine($"MS Config Query config error, {_configurationSource.DataId} ,{ex.Message}");
_logger?.LogWarning(ex, "MS Config Query config error, dataid={0}, group={1}, tenant={2}", _configurationSource.DataId, _configurationSource.Group, _configurationSource.Tenant);
if (!_configurationSource.Optional)
{
throw;
Expand All @@ -179,7 +184,7 @@ public override void Load()
}
catch (Exception ex)
{
System.Diagnostics.Trace.WriteLine($"Load config error, {ex.Message}");
_logger?.LogError(ex, "Load config error");
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
namespace Nacos.Microsoft.Extensions.Configuration
{
using global::Microsoft.Extensions.Configuration;
using global::Microsoft.Extensions.Logging;
using Nacos.Config;
using System;
using System.Collections.Generic;

public class NacosConfigurationSource : IConfigurationSource
Expand All @@ -11,7 +13,6 @@ public class NacosConfigurationSource : IConfigurationSource
/// </summary>
public List<string> ServerAddresses { get; set; }


/// <summary>
/// The configuration listeners
/// </summary>
Expand All @@ -20,19 +21,19 @@ public class NacosConfigurationSource : IConfigurationSource
/// <summary>
/// Determines if the Nacos Server is optional
/// </summary>
[System.Obsolete("please use Listeners to configure")]
[Obsolete("please use Listeners to configure")]
public bool Optional { get; set; }

/// <summary>
/// Configuration ID
/// </summary>
[System.Obsolete("please use Listeners to configure")]
[Obsolete("please use Listeners to configure")]
public string DataId { get; set; }

/// <summary>
/// Configuration group
/// </summary>
[System.Obsolete("please use Listeners to configure")]
[Obsolete("please use Listeners to configure")]
public string Group { get; set; }

/// <summary>
Expand Down Expand Up @@ -79,6 +80,11 @@ public class NacosConfigurationSource : IConfigurationSource
/// </summary>
public INacosConfigurationParser NacosConfigurationParser { get; set; }

/// <summary>
/// The logging builder, default will use AddConsole
/// </summary>
public Action<ILoggingBuilder> LoggingBuilder { get; set; }

/// <summary>
/// Build the provider
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,15 @@
{
using global::Microsoft.Extensions.DependencyInjection;
using global::Microsoft.Extensions.Logging;
using System;

public class NacosLoggerFactory : ILoggerFactory
{
public NacosLoggerFactory()
{
}

static NacosLoggerFactory()
{
_factory = GetLoggerFactory();
}

public static readonly NacosLoggerFactory Instance = new NacosLoggerFactory();

public ILogger CreateLogger(string name)
{
return _factory.CreateLogger(name);
}


public void AddProvider(ILoggerProvider provider)
{
}
Expand All @@ -31,14 +20,32 @@ public void Dispose()
_factory?.Dispose();
}

public static NacosLoggerFactory GetInstance(Action<ILoggingBuilder> builder = null)
{
if (_loggingFactory != null) return _loggingFactory;

_factory = GetLoggerFactory(builder);
var obj = new NacosLoggerFactory();
return _loggingFactory = obj;
}

private static ILoggerFactory _factory;
private static NacosLoggerFactory _loggingFactory;

private static ILoggerFactory GetLoggerFactory()
private static ILoggerFactory GetLoggerFactory(Action<ILoggingBuilder> builder = null)
{
if (_factory != null) return _factory;

var serviceCollection = new ServiceCollection();
serviceCollection.AddLogging(x => x.AddConsole());
if (builder != null)
{
serviceCollection.AddLogging(builder);
}
else
{
serviceCollection.AddLogging(x => x.AddConsole());
}

ServiceProvider serviceProvider = serviceCollection.BuildServiceProvider();
ILoggerFactory loggerFactory = serviceProvider.GetService<ILoggerFactory>();
return loggerFactory;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,9 @@ public NacosV2ConfigurationProvider(NacosV2ConfigurationSource configurationSour
ConfigUseRpc = configurationSource.ConfigUseRpc,
});

_logger = Nacos.Microsoft.Extensions.Configuration.NacosLog.NacosLoggerFactory.Instance.CreateLogger<NacosV2ConfigurationProvider>();

_client = new NacosConfigService(Nacos.Microsoft.Extensions.Configuration.NacosLog.NacosLoggerFactory.Instance, options);
var nacosLoggerFactory = Nacos.Microsoft.Extensions.Configuration.NacosLog.NacosLoggerFactory.GetInstance(configurationSource.LoggingBuilder);
_logger = nacosLoggerFactory.CreateLogger<NacosV2ConfigurationProvider>();
_client = new NacosConfigService(nacosLoggerFactory, options);
if (configurationSource.Listeners != null && configurationSource.Listeners.Any())
{
var tasks = new List<Task>();
Expand All @@ -68,11 +68,11 @@ public NacosV2ConfigurationProvider(NacosV2ConfigurationSource configurationSour
}
else
{
#pragma warning disable CS0618 // 类型或成员已过时
#pragma warning disable CS0618
var listener = new MsConfigListener(_configurationSource.DataId, _configurationSource.Group, _configurationSource.Optional, this, _logger);
_client.AddListener(_configurationSource.DataId, _configurationSource.Group, listener);
_listenerDict.Add($"{_configurationSource.DataId}#{_configurationSource.Group}", listener);
#pragma warning restore CS0618 // 类型或成员已过时
#pragma warning restore CS0618
}
}

Expand Down Expand Up @@ -120,7 +120,7 @@ public override void Load()
}
catch (Exception ex)
{
_logger?.LogWarning(ex, "MS Config Query config error, dataid={0}", listener.DataId);
_logger?.LogWarning(ex, "MS Config Query config error, dataid={0}, group={1}, tenant={2}", listener.DataId, listener.Group, listener.Tenant);
if (!listener.Optional)
{
throw;
Expand All @@ -146,7 +146,7 @@ public override void Load()
}
catch (Exception ex)
{
_logger?.LogWarning(ex, "MS Config Query config error, dataid={0}", _configurationSource.DataId);
_logger?.LogWarning(ex, "MS Config Query config error, dataid={0}, group={1}, tenant={2}", _configurationSource.DataId, _configurationSource.Group, _configurationSource.Tenant);
if (!_configurationSource.Optional)
{
throw;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
namespace Nacos.Microsoft.Extensions.Configuration
{
using global::Microsoft.Extensions.Configuration;
using global::Microsoft.Extensions.DependencyInjection;
using global::Microsoft.Extensions.Logging;
using Nacos.Config;
using System;
using System.Collections.Generic;

public class NacosV2ConfigurationSource : Nacos.V2.NacosSdkOptions, IConfigurationSource
Expand Down Expand Up @@ -39,6 +42,11 @@ public class NacosV2ConfigurationSource : Nacos.V2.NacosSdkOptions, IConfigurati
/// </summary>
public INacosConfigurationParser NacosConfigurationParser { get; set; }

/// <summary>
/// The logging builder, default will use AddConsole
/// </summary>
public Action<ILoggingBuilder> LoggingBuilder { get; set; }

/// <summary>
/// Build the provider
/// </summary>
Expand Down

0 comments on commit 5229ef7

Please sign in to comment.