Skip to content

Commit

Permalink
Removed console log target from config.json as it's always enabled by…
Browse files Browse the repository at this point in the history
… default.

Improved initialization of ConfigMangaer and LogManager.
  • Loading branch information
bonesoul committed Sep 25, 2014
1 parent 67ab8c7 commit ca28e2e
Show file tree
Hide file tree
Showing 8 changed files with 86 additions and 100 deletions.
68 changes: 35 additions & 33 deletions src/CoiniumServ/Configuration/ConfigManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Reflection;
using CoiniumServ.Coin.Config;
using CoiniumServ.Daemon;
using CoiniumServ.Daemon.Config;
using CoiniumServ.Factories;
using CoiniumServ.Logging;
Expand All @@ -36,6 +36,8 @@
using CoiniumServ.Server.Web;
using CoiniumServ.Statistics;
using CoiniumServ.Utils.Helpers.IO;
using CoiniumServ.Utils.Platform;
using libCoiniumServ.Versions;
using Serilog;

namespace CoiniumServ.Configuration
Expand Down Expand Up @@ -66,55 +68,47 @@ public class ConfigManager:IConfigManager

private readonly IConfigFactory _configFactory;
private readonly IJsonConfigReader _jsonConfigReader;
private readonly ILogManager _logManager;

private ILogger _logger;
private readonly ILogger _logger;

public ConfigManager(IConfigFactory configFactory, IJsonConfigReader jsonConfigReader)
public ConfigManager(IConfigFactory configFactory, IJsonConfigReader jsonConfigReader, ILogManager logManager)
{
_configFactory = configFactory;
_jsonConfigReader = jsonConfigReader;

PoolConfigs = new List<IPoolConfig>(); // list of pool configurations.
_logManager = logManager;
_logger = Log.ForContext<ConfigManager>();

LoadGlobalConfig(); // read the global config.
// LoadDaemonManagerConfig(); // load the global daemon manager config. - disabled until we need it.
LoadSoftwareManagerConfig(); // load software manager config file.
LoadPoolConfigs(); // load the per-pool config files.
}

private void LoadGlobalConfig()
{
var data = _jsonConfigReader.Read(GlobalConfigFilename); // read the global config data.

if (data == null) // make sure it exists, else gracefully exists
// make sure we were able to load global config.
if (data == null)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Couldn't read config/config.json! Make sure you rename config/config-example.json as config/config.json.");
Console.ResetColor();

// gracefully exit
_logger.Error("Couldn't read config/config.json! Make sure you rename config/config-example.json as config/config.json.");
Environment.Exit(-1);
}

// load log config.
LogConfig = new LogConfig(data.logging); // read the log config first, so rest of the config loaders can use log subsystem.
_logManager.EmitConfiguration(LogConfig); // assign the log configuration to log manager.

// print a version banner.
_logger.Information("CoiniumServ {0:l} {1:l} warming-up..", VersionInfo.CodeName, Assembly.GetAssembly(typeof(Program)).GetName().Version);
PlatformManager.PrintPlatformBanner();

// load rest of the configs.
StackConfig = new StackConfig(data.stack);
StatisticsConfig = new StatisticsConfig(data.statistics);
WebServerConfig = new WebServerConfig(data.website);
LogConfig = new LogConfig(data.logging);
}

public void Initialize()
{
// these config files below need to access log-manager, that's why we wait it's configuration initialized with in ctor().

// LoadDaemonManagerConfig(); // load the global daemon manager config. - disabled until we need it.
LoadSoftwareManagerConfig(); // load software maanger config file.
LoadPoolConfigs(); // load the per-pool config files.
}

private void LoadDaemonManagerConfig()
{
var data = _jsonConfigReader.Read(DaemonManagerConfigFilename); // read the global config data.

if (data == null) // if we can't read daemon manager config file.
data = new ExpandoObject(); // create a fake object.

DaemonManagerConfig = _configFactory.GetDaemonManagerConfig(data);
}

private void LoadSoftwareManagerConfig()
Expand All @@ -126,9 +120,7 @@ private void LoadSoftwareManagerConfig()

private void LoadPoolConfigs()
{
_logger = Log.ForContext<ConfigManager>();
_logger.Debug("Discovering enabled pool configs..");

PoolConfigs = new List<IPoolConfig>(); // list of pool configurations.
var files = FileHelpers.GetFilesByExtension(PoolConfigRoot, ".json");

foreach (var file in files)
Expand Down Expand Up @@ -174,6 +166,16 @@ private void LoadPoolConfigs()
PoolConfigs.Select(config => config.Coin.Name).ToList());
}

private void LoadDaemonManagerConfig()
{
var data = _jsonConfigReader.Read(DaemonManagerConfigFilename); // read the global config data.

if (data == null) // if we can't read daemon manager config file.
data = new ExpandoObject(); // create a fake object.

DaemonManagerConfig = _configFactory.GetDaemonManagerConfig(data);
}

public ICoinConfig GetCoinConfig(string name)
{
var fileName = string.Format("{0}/{1}.json", CoinConfigRoot, name);
Expand Down
3 changes: 0 additions & 3 deletions src/CoiniumServ/Configuration/IConfigManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
#endregion
using System.Collections.Generic;
using CoiniumServ.Coin.Config;
using CoiniumServ.Daemon;
using CoiniumServ.Daemon.Config;
using CoiniumServ.Logging;
using CoiniumServ.Mining.Software;
Expand Down Expand Up @@ -50,7 +49,5 @@ public interface IConfigManager
ISoftwareRepositoryConfig SoftwareRepositoryConfig { get; }

ICoinConfig GetCoinConfig(string name);

void Initialize();
}
}
4 changes: 3 additions & 1 deletion src/CoiniumServ/Logging/ILogManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,5 +23,7 @@
namespace CoiniumServ.Logging
{
public interface ILogManager
{ }
{
void EmitConfiguration(ILogConfig config);
}
}
4 changes: 0 additions & 4 deletions src/CoiniumServ/Logging/ILogTarget.cs
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,6 @@ public interface ILogTarget: IConfig

public enum LogTargetType
{
/// <summary>
/// Logs to console.
/// </summary>
Console,
/// <summary>
/// Logs to a file.
/// </summary>
Expand Down
82 changes: 41 additions & 41 deletions src/CoiniumServ/Logging/LogManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,6 @@
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using CoiniumServ.Configuration;
using CoiniumServ.Utils.Helpers.IO;
using Serilog;
using Serilog.Core;
Expand All @@ -41,67 +39,71 @@ public class LogManager:ILogManager

private string _rootFolder;

private readonly ILogConfig _config;
private LoggerConfiguration _mainConfig; // used by console and file logs.
private LoggerConfiguration _packetLoggerConfig; // used by the packet log.

// todo: create console log by default without the need for configuration.

public LogManager(IConfigManager configManager)
public LogManager()
{
_config = configManager.LogConfig;

Initialize();
}

private void Initialize()
{
// read the root folder for logs.
_rootFolder = string.IsNullOrEmpty(_config.Root) ? "logs" : _config.Root;
var rootPath = FileHelpers.GetAbsolutePath(_rootFolder);

if (!Directory.Exists(rootPath)) // make sure log root exists.
Directory.CreateDirectory(rootPath);

// create the global logger.
var globalConfig = new LoggerConfiguration();
var packetLoggerConfig = new LoggerConfiguration();
_mainConfig = new LoggerConfiguration(); // set the main config for console and file logs.
SetupConfiguration(_mainConfig); // setup the configuration with enrichers and so.

// create the default console.
#if DEBUG
_mainConfig.WriteTo.ColoredConsole(LogEventLevel.Debug, ConsoleLogFormat); // use debug level for debug mode.
#else
_mainConfig.WriteTo.ColoredConsole(LogEventLevel.Information, ConsoleLogFormat); // use information level for release mode.
#endif
// bind the config to global log.
Log.Logger = _mainConfig.CreateLogger();

// set the packet log configuration.
_packetLoggerConfig = new LoggerConfiguration(); // will be used for packet logger.
SetupConfiguration(_packetLoggerConfig); // setup the configuration with enrichers and so.
}

// add enrichers
globalConfig.Enrich.With(new SourceEnricher());
globalConfig.Enrich.With(new ComponentEnricher());
private void SetupConfiguration(LoggerConfiguration configuration)
{
configuration.Enrich.With(new SourceEnricher()); // used for enriching logs with class names.
configuration.Enrich.With(new ComponentEnricher()); // used for enriching logs with pool names.
configuration.MinimumLevel.Verbose(); // lower the default minimum level to verbose as sinks can only rise them but not lower.
}

packetLoggerConfig.Enrich.With(new SourceEnricher());
packetLoggerConfig.Enrich.With(new ComponentEnricher());
public void EmitConfiguration(ILogConfig config)
{
// read the root folder for logs.
_rootFolder = string.IsNullOrEmpty(config.Root) ? "logs" : config.Root;
var rootPath = FileHelpers.GetAbsolutePath(_rootFolder);

foreach (var target in _config.Targets)
// make sure log root exists.
if (!Directory.Exists(rootPath))
Directory.CreateDirectory(rootPath);

// loop through file log targets from the config
foreach (var target in config.Targets)
{
if (!target.Enabled)
continue;

switch (target.Type)
{
case LogTargetType.Console:
CreateConsoleLog(globalConfig, target);
break;
case LogTargetType.File:
CreateFileLog(globalConfig, target);
CreateFileLog(_mainConfig, target);
break;
case LogTargetType.Packet:
CreatePacketLog(packetLoggerConfig, target);
CreatePacketLog(_packetLoggerConfig, target);
break;
}
}

// lower the default minimum level to verbose as sinks can only rise them but not lower.
globalConfig.MinimumLevel.Verbose();
packetLoggerConfig.MinimumLevel.Verbose();

Log.Logger = globalConfig.CreateLogger(); // bind the config to global log.
PacketLogger = packetLoggerConfig.CreateLogger();
}
if (config.Targets.Count(x => x.Type == LogTargetType.File) > 0) // if we have added new file loggers.
Log.Logger = _mainConfig.CreateLogger(); // recreate the global logger.

private void CreateConsoleLog(LoggerConfiguration config, ILogTarget target)
{
config.WriteTo.ColoredConsole(target.Level, ConsoleLogFormat);
PacketLogger = _packetLoggerConfig.CreateLogger(); // create the packet logger too even if doesn't really contain any outputs.
}

private void CreateFileLog(LoggerConfiguration config, ILogTarget target)
Expand All @@ -117,7 +119,6 @@ private void CreateFileLog(LoggerConfiguration config, ILogTarget target)
}
catch (UnauthorizedAccessException e)
{
// we can at least log the error to console.
Log.ForContext<LogManager>().Error("Error creating file log {0:l} - {1:l}", target.Filename, e.Message);
}
}
Expand All @@ -135,7 +136,6 @@ private void CreatePacketLog(LoggerConfiguration config, ILogTarget target)
}
catch (UnauthorizedAccessException e)
{
// we can at least log the error to console.
Log.ForContext<LogManager>().Error("Error creating file log {0:l} - {1:l}", target.Filename, e.Message);
}
}
Expand Down
5 changes: 2 additions & 3 deletions src/CoiniumServ/Logging/LogTarget.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,15 +43,14 @@ public LogTarget(dynamic config)

switch ((string) config.type)
{
case "console":
Type = LogTargetType.Console;
break;
case "file":
Type = LogTargetType.File;
break;
case "packet":
Type = LogTargetType.Packet;
break;
default:
return;
}

switch ((string) config.level)
Expand Down
15 changes: 5 additions & 10 deletions src/CoiniumServ/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,19 +62,14 @@ static void Main(string[] args)
ConsoleWindow.PrintBanner();
ConsoleWindow.PrintLicense();

// load the config-manager.
var configManager = configFactory.GetConfigManager();

// initialize log-manager as we'll need it below for the loading rest of the configuration files.
// initialize the log-manager.
objectFactory.GetLogManager();

// print a version banner.
_logger = Log.ForContext<Program>();
_logger.Information("CoiniumServ {0:l} {1:l} warming-up..", VersionInfo.CodeName, Assembly.GetAssembly(typeof(Program)).GetName().Version);
PlatformManager.PrintPlatformBanner();
// load the config-manager.
configFactory.GetConfigManager();

// rest of configurations need access to log-manager being already initialized.
configManager.Initialize();
// create logger to be used later.
_logger = Log.ForContext<Program>();

// run global managers
RunGlobalManagers(objectFactory);
Expand Down
5 changes: 0 additions & 5 deletions src/CoiniumServ/config/config-example.json
Original file line number Diff line number Diff line change
Expand Up @@ -87,11 +87,6 @@
"logging": {
"root": "logs",
"targets": [
{
"enabled": true,
"type": "console",
"level": "debug"
},
{
"enabled": true,
"type": "file",
Expand Down

0 comments on commit ca28e2e

Please sign in to comment.