Refactoring

Refactoring configuration and log
pull/1/head
a.bozhenov 6 years ago
parent 9c914a2387
commit 2be9f7b7e2

@ -1,5 +1,4 @@
using System; using ZeroLevel.Network;
using ZeroLevel.Network;
namespace ZeroLevel.Services.Applications namespace ZeroLevel.Services.Applications
{ {
@ -11,19 +10,25 @@ namespace ZeroLevel.Services.Applications
public string Group { get; private set; } public string Group { get; private set; }
public string Type { get; private set; } public string Type { get; private set; }
protected readonly IConfiguration _config; protected readonly IConfigurationSet _configSet;
protected IConfiguration _config => _configSet?.Default;
protected Exchange Exchange { get; } protected Exchange Exchange { get; }
protected BaseZeroExchangeService(IConfiguration configuration = null) private BaseZeroExchangeService()
{
}
protected BaseZeroExchangeService(IConfigurationSet configuration = null)
: base() : base()
{ {
_config = configuration ?? Configuration.Default; _configSet = configuration ?? Configuration.DefaultSet;
base.Name = ReadName(_config); base.Name = ReadName();
this.Key = ReadKey(_config); this.Key = ReadKey();
this.Version = ReadVersion(_config); this.Version = ReadVersion();
this.Group = ReadServiceGroup(_config); this.Group = ReadServiceGroup();
this.Type = ReadServiceType(_config); this.Type = ReadServiceType();
var discovery = _config.First("discovery"); var discovery = _config.First("discovery");
@ -52,51 +57,62 @@ namespace ZeroLevel.Services.Applications
#region Config #region Config
private string ReadName(IConfiguration configuration) private string ReadName()
{ {
if (_config.Contains("ServiceName")) return FindInConfig<string>(new[] { "ServiceName", "AppName" }, string.Empty, "service")
return _config.First("ServiceName"); ?? this.GetType().Name;
if (_config.Contains("AppName"))
return _config.First("AppName");
return this.GetType().Name;
} }
private string ReadKey(IConfiguration configuration) private string ReadKey()
{ {
if (_config.Contains("ServiceKey")) return FindInConfig<string>(new[] { "ServiceKey", "AppKey" }, string.Empty, "service");
return _config.First("ServiceKey");
if (_config.Contains("AppKey"))
return _config.First("AppKey");
return null;
} }
private string ReadVersion(IConfiguration configuration) private string ReadVersion()
{ {
if (_config.Contains("Version")) return FindInConfig<string>(new[] { "Version", "AppVersion" }, string.Empty, "service")
return _config.First("Version"); ?? "1.0";
if (_config.Contains("AppVersion"))
return _config.First("AppVersion");
return "1.0";
} }
private string ReadServiceGroup(IConfiguration configuration) private string ReadServiceGroup()
{ {
if (_config.Contains("DiscoveryGroup")) return FindInConfig<string>(new[] { "DiscoveryGroup", "ServiceGroup" }, string.Empty, "service")
return _config.First("DiscoveryGroup"); ?? ExServiceInfo.DEFAULT_GROUP_NAME;
if (_config.Contains("ServiceGroup"))
return _config.First("ServiceGroup");
return ExServiceInfo.DEFAULT_GROUP_NAME;
} }
private string ReadServiceType(IConfiguration configuration) private string ReadServiceType()
{ {
if (_config.Contains("DiscoveryType")) return FindInConfig<string>(new[] { "DiscoveryType", "ServiceType" }, string.Empty, "service")
return _config.First("DiscoveryType"); ?? ExServiceInfo.DEFAULT_TYPE_NAME;
if (_config.Contains("ServiceType"))
return _config.First("ServiceType");
return ExServiceInfo.DEFAULT_TYPE_NAME;
} }
protected T FindInConfig<T>(string[] keys, params string[] sections)
{
foreach (var section in sections)
{
if (string.IsNullOrWhiteSpace(section))
{
foreach (var key in keys)
{
if (_configSet.Default.Contains(key))
{
return _configSet.Default.First<T>(key);
}
}
}
else if (_configSet.ContainsSection(section))
{
foreach (var key in keys)
{
if (_configSet[section].Contains(key))
{
return _configSet[section].First<T>(key);
}
}
}
}
return default(T);
}
#endregion Config #endregion Config
public string Endpoint { get; private set; } public string Endpoint { get; private set; }

@ -39,10 +39,13 @@ namespace ZeroLevel
return null; return null;
} }
public static void Startup<T>(string[] args, Func<bool> preStartConfiguration = null, Func<bool> postStartConfiguration = null) public static void Startup<T>(string[] args,
where T : IZeroService, new() Func<bool> preStartConfiguration = null,
Func<bool> postStartConfiguration = null)
where T : IZeroService
{ {
var service = Initialize<T>(args, preStartConfiguration, postStartConfiguration); var service = Initialize<T>(args, Configuration.ReadSetFromApplicationConfig(),
preStartConfiguration, postStartConfiguration);
if (service != null) if (service != null)
{ {
service.Start(); service.Start();
@ -50,13 +53,31 @@ namespace ZeroLevel
} }
} }
private static IZeroService Initialize<T>(string[] args, Func<bool> preStartConfiguration = null, Func<bool> postStartConfiguration = null) public static void Startup<T>(string[] args,
where T : IZeroService, new() Func<IConfigurationSet> configuration,
Func<bool> preStartConfiguration = null,
Func<bool> postStartConfiguration = null)
where T : IZeroService
{ {
IZeroService service = null; var service = Initialize<T>(args, configuration(), preStartConfiguration, postStartConfiguration);
if (service != null)
{
service.Start();
Shutdown(service);
}
}
Configuration.Save(Configuration.ReadFromApplicationConfig()); private static IZeroService Initialize<T>(string[] args,
Log.CreateLoggingFromConfiguration(Configuration.Default); IConfigurationSet configurationSet,
Func<bool> preStartConfiguration = null,
Func<bool> postStartConfiguration = null)
where T : IZeroService
{
IZeroService service = null;
IConfigurationSet config = Configuration.DefaultSet;
config.CreateSection("commandline", Configuration.ReadFromCommandLine(args));
config.Merge(configurationSet);
Log.CreateLoggingFromConfiguration(Configuration.DefaultSet);
if (preStartConfiguration != null) if (preStartConfiguration != null)
{ {
try try
@ -75,7 +96,7 @@ namespace ZeroLevel
} }
try try
{ {
service = new T(); service = Activator.CreateInstance<T>();
} }
catch (Exception ex) catch (Exception ex)
{ {

@ -274,6 +274,23 @@ namespace ZeroLevel.Services.Config
return this; return this;
} }
public IConfiguration Append(string key, IEnumerable<string> values)
{
if (false == _freezed)
{
key = GetKey(key);
if (false == _keyValues.ContainsKey(key))
{
_keyValues.TryAdd(key, new List<string>());
}
foreach (var value in values)
{
_keyValues[key].Add(value?.Trim() ?? null);
}
}
return this;
}
/// <summary> /// <summary>
/// Set unique value for key /// Set unique value for key
/// </summary> /// </summary>
@ -434,5 +451,13 @@ namespace ZeroLevel.Services.Config
} }
#endregion Binary Serializable #endregion Binary Serializable
public void CopyTo(IConfiguration config)
{
foreach (var key in config.Keys)
{
this.Append(key, config[key]);
}
}
} }
} }

@ -93,6 +93,22 @@ namespace ZeroLevel.Services.Config
throw new Exception("Sections change freezed"); throw new Exception("Sections change freezed");
} }
public IConfiguration CreateSection(string sectionName, IConfiguration config)
{
var key = GetKey(sectionName);
IConfiguration exists;
if (_sections.TryGetValue(key, out exists))
{
return exists;
}
else if (false == _sectionsFreezed)
{
_sections.TryAdd(key, config);
return _sections[key];
}
throw new Exception("Sections change freezed");
}
public IConfiguration GetSection(string sectionName) public IConfiguration GetSection(string sectionName)
{ {
var key = GetKey(sectionName); var key = GetKey(sectionName);
@ -230,7 +246,16 @@ namespace ZeroLevel.Services.Config
_sections.TryAdd(key, reader.Read<BaseConfiguration>()); _sections.TryAdd(key, reader.Read<BaseConfiguration>());
} }
} }
#endregion Binary Serializable #endregion Binary Serializable
public void Merge(IConfigurationSet set)
{
set.Default.CopyTo(this.Default);
foreach (var sectionName in set.SectionNames)
{
var section = this.CreateSection(sectionName);
set[sectionName].CopyTo(section);
}
}
} }
} }

@ -44,7 +44,7 @@ namespace ZeroLevel
public static IConfiguration Empty { get { return _empty; } } public static IConfiguration Empty { get { return _empty; } }
public static IConfigurationSet EmptySet { get { return _emptySet; } } public static IConfigurationSet EmptySet { get { return _emptySet; } }
public static IConfiguration Default { get; private set; } public static IConfiguration Default => DefaultSet?.Default;
public static IConfigurationSet DefaultSet { get; private set; } public static IConfigurationSet DefaultSet { get; private set; }
public static void Save(string name, IConfiguration configuration) public static void Save(string name, IConfiguration configuration)
@ -54,13 +54,13 @@ namespace ZeroLevel
public static void Save(IConfiguration configuration) public static void Save(IConfiguration configuration)
{ {
if (Default == null) if (DefaultSet == null)
{ {
Default = configuration; DefaultSet = Configuration.CreateSet(configuration);
} }
else else
{ {
throw new Exception("Default configuration set already"); throw new Exception("Default configuration exists already");
} }
} }
@ -123,7 +123,6 @@ namespace ZeroLevel
#endregion Factory #endregion Factory
#region Read configuration #region Read configuration
/// <summary> /// <summary>
/// Creating a configuration from the AppSettings section of the app.config or web.config file /// Creating a configuration from the AppSettings section of the app.config or web.config file
/// </summary> /// </summary>

@ -135,5 +135,7 @@ namespace ZeroLevel
bool Unfreeze(); bool Unfreeze();
#endregion Create, Clean, Delete #endregion Create, Clean, Delete
void CopyTo(IConfiguration config);
} }
} }

@ -48,6 +48,8 @@ namespace ZeroLevel
/// <param name="sectionName">Section name</param> /// <param name="sectionName">Section name</param>
IConfiguration CreateSection(string sectionName); IConfiguration CreateSection(string sectionName);
IConfiguration CreateSection(string sectionName, IConfiguration config);
/// <summary> /// <summary>
/// Get configuration section by name /// Get configuration section by name
/// </summary> /// </summary>
@ -87,6 +89,7 @@ namespace ZeroLevel
/// </summary> /// </summary>
bool UnfreezeSections(); bool UnfreezeSections();
void Merge(IConfigurationSet set);
#endregion Methods #endregion Methods
} }
} }

@ -10,6 +10,8 @@ namespace ZeroLevel.Services.Config.Implementation
{ {
private readonly string _configFilePath; private readonly string _configFilePath;
public bool ExistsAppConfigFile => string.IsNullOrWhiteSpace(_configFilePath) == false;
internal AppWebConfigReader(string configFilePath = null) internal AppWebConfigReader(string configFilePath = null)
{ {
if (configFilePath == null) if (configFilePath == null)

@ -5,6 +5,8 @@
{ {
private readonly AppWebConfigReader _reader; private readonly AppWebConfigReader _reader;
public bool ExistsAppConfigFile => _reader.ExistsAppConfigFile;
internal ApplicationConfigReader() internal ApplicationConfigReader()
{ {
_reader = new AppWebConfigReader(); _reader = new AppWebConfigReader();

@ -96,28 +96,28 @@ namespace ZeroLevel.Services.Logging.Implementation
return this; return this;
} }
internal static TextFileLoggerOptions CreateOptionsBy(IConfiguration config, string logPrefix) internal static TextFileLoggerOptions CreateOptionsBy(IConfiguration config, string path, string logPrefix)
{ {
if (config.Contains(logPrefix)) if (config.Contains(logPrefix))
{ {
var options = new TextFileLoggerOptions(). var options = new TextFileLoggerOptions().
SetFolderPath(config.First(logPrefix)); SetFolderPath(path);
config.DoWithFirst<long>($"{logPrefix}.backlog", backlog => config.DoWithFirst<long>($"{logPrefix}backlog", backlog =>
{ {
if (backlog > 0) if (backlog > 0)
{ {
Log.Backlog(backlog); Log.Backlog(backlog);
} }
}); });
config.DoWithFirst<bool>($"{logPrefix}.archive", enable => config.DoWithFirst<bool>($"{logPrefix}archive", enable =>
{ {
if (enable) if (enable)
{ {
options.EnableAutoArchiving(); options.EnableAutoArchiving();
} }
}); });
config.DoWithFirst<int>($"{logPrefix}.sizeinkb", size => config.DoWithFirst<int>($"{logPrefix}sizeinkb", size =>
{ {
if (size >= 1) if (size >= 1)
{ {
@ -125,7 +125,7 @@ namespace ZeroLevel.Services.Logging.Implementation
} }
}); });
config.DoWithFirst<int>($"{logPrefix}.cleanolderdays", days => config.DoWithFirst<int>($"{logPrefix}cleanolderdays", days =>
{ {
if (days > 0) if (days > 0)
{ {

@ -190,43 +190,44 @@ namespace ZeroLevel
#endregion Register loggers #endregion Register loggers
#region Settings #region Settings
public static void CreateLoggingFromConfiguration(IConfigurationSet configSet)
public static void CreateLoggingFromConfiguration()
{ {
CreateLoggingFromConfiguration(Configuration.ReadFromApplicationConfig()); IConfiguration config;
} bool log_section = false;
if (configSet.Default.Contains("log"))
public static void CreateLoggingFromConfiguration(IConfiguration config)
{
if (config.FirstOrDefault("console", false))
{ {
AddConsoleLogger(LogLevel.System | LogLevel.FullDebug); config = configSet.Default;
} }
if (config.Contains("log")) else if (configSet.ContainsSection("log"))
{ {
var options = TextFileLoggerOptions.CreateOptionsBy(config, "log"); config = configSet["log"];
if (options != null) log_section = true;
{
AddTextFileLogger(options);
}
} }
var debug = string.Empty; else
if (config.Contains("debug"))
{ {
debug = "debug"; return;
} }
if (config.Contains("trace")) string logPath = null;
if (config.Contains("log"))
{ {
debug = "trace"; logPath = config.First("log");
} }
if (false == string.IsNullOrWhiteSpace(debug)) else if (log_section && config.Contains("path"))
{ {
var options = TextFileLoggerOptions.CreateOptionsBy(config, debug); logPath = config.First("path");
}
if (false == string.IsNullOrWhiteSpace(logPath))
{
var options = TextFileLoggerOptions.CreateOptionsBy(config, logPath, log_section ? string.Empty : "log.");
if (options != null) if (options != null)
{ {
AddTextFileLogger(options, LogLevel.Debug); AddTextFileLogger(options);
} }
} }
if (config.FirstOrDefault("console", false))
{
AddConsoleLogger(LogLevel.System | LogLevel.FullDebug);
}
} }
/// <summary> /// <summary>

@ -6,7 +6,8 @@
<Authors>ogoun</Authors> <Authors>ogoun</Authors>
<Company>ogoun</Company> <Company>ogoun</Company>
<AssemblyVersion>2.0.6.0</AssemblyVersion> <AssemblyVersion>2.0.6.0</AssemblyVersion>
<PackageReleaseNotes>File client/server</PackageReleaseNotes> <PackageReleaseNotes>Refactoring configuration and log
File client/server (no stable)</PackageReleaseNotes>
<PackageProjectUrl>https://github.com/ogoun/Zero/wiki</PackageProjectUrl> <PackageProjectUrl>https://github.com/ogoun/Zero/wiki</PackageProjectUrl>
<Copyright>Copyright Ogoun 2019</Copyright> <Copyright>Copyright Ogoun 2019</Copyright>
<PackageLicenseUrl>https://opensource.org/licenses/MIT</PackageLicenseUrl> <PackageLicenseUrl>https://opensource.org/licenses/MIT</PackageLicenseUrl>

Loading…
Cancel
Save

Powered by TurnKey Linux.