Skip to content
This repository has been archived by the owner on Dec 7, 2023. It is now read-only.

Move SystemLog plugin into neo-cli as a native logger with on/off functionalities. #582

Merged
merged 7 commits into from
May 13, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions Neo.ConsoleService/ConsoleColorSet.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
using System;

namespace Neo.ConsoleService
{
public class ConsoleColorSet
{
#region Constants

public static readonly ConsoleColorSet Debug = new ConsoleColorSet(ConsoleColor.Cyan);
public static readonly ConsoleColorSet Info = new ConsoleColorSet(ConsoleColor.White);
public static readonly ConsoleColorSet Warning = new ConsoleColorSet(ConsoleColor.Yellow);
public static readonly ConsoleColorSet Error = new ConsoleColorSet(ConsoleColor.Red);
public static readonly ConsoleColorSet Fatal = new ConsoleColorSet(ConsoleColor.Red);

#endregion

public ConsoleColor Foreground;
public ConsoleColor Background;

/// <summary>
/// Create a new color set with the current console colors
/// </summary>
public ConsoleColorSet() : this(Console.ForegroundColor, Console.BackgroundColor) { }

/// <summary>
/// Create a new color set
/// </summary>
/// <param name="foreground">Foreground color</param>
public ConsoleColorSet(ConsoleColor foreground) : this(foreground, Console.BackgroundColor) { }

/// <summary>
/// Create a new color set
/// </summary>
/// <param name="foreground">Foreground color</param>
/// <param name="background">Background color</param>
public ConsoleColorSet(ConsoleColor foreground, ConsoleColor background)
{
Foreground = foreground;
Background = background;
}

/// <summary>
/// Apply the current set
/// </summary>
public void Apply()
{
Console.ForegroundColor = Foreground;
Console.BackgroundColor = Background;
}
}
}
97 changes: 97 additions & 0 deletions neo-cli/CLI/Logger.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
using Neo.Plugins;
using System;
using System.Text;
using System.IO;
using static System.IO.Path;
using System.Reflection;
using Neo.ConsoleService;

namespace Neo.CLI
{
public class Logger : Plugin, ILogPlugin
{
public override string Name => "SystemLog";
public override string ConfigFile => Combine(GetDirectoryName(Assembly.GetEntryAssembly().Location), "config.json");

public bool Started { get; set; }

public Logger() : base()
{
Started = Settings.Default.Logger.Started; // default is started to log
}

private static void GetErrorLogs(StringBuilder sb, Exception ex)
{
sb.AppendLine(ex.GetType().ToString());
sb.AppendLine(ex.Message);
sb.AppendLine(ex.StackTrace);
if (ex is AggregateException ex2)
{
foreach (Exception inner in ex2.InnerExceptions)
{
sb.AppendLine();
GetErrorLogs(sb, inner);
}
}
else if (ex.InnerException != null)
{
sb.AppendLine();
GetErrorLogs(sb, ex.InnerException);
}
}

void ILogPlugin.Log(string source, LogLevel level, object message)
{
if (!Started)
return;

if (message is Exception ex)
{
var sb = new StringBuilder();
GetErrorLogs(sb, ex);
message = sb.ToString();
}

lock (typeof(Logger))
{
DateTime now = DateTime.Now;
var log = $"[{now.TimeOfDay:hh\\:mm\\:ss\\.fff}] {message}";

if (Settings.Default.Logger.ConsoleOutput)
{
var currentColor = new ConsoleColorSet();

switch (level)
{
case LogLevel.Debug: ConsoleColorSet.Debug.Apply(); break;
case LogLevel.Error: ConsoleColorSet.Error.Apply(); break;
case LogLevel.Fatal: ConsoleColorSet.Fatal.Apply(); break;
case LogLevel.Info: ConsoleColorSet.Info.Apply(); break;
case LogLevel.Warning: ConsoleColorSet.Warning.Apply(); break;
}

Console.WriteLine(log);
currentColor.Apply();
}

if (!string.IsNullOrEmpty(Settings.Default.Logger.Path))
{
StringBuilder sb = new StringBuilder(source);
foreach (char c in GetInvalidFileNameChars())
sb.Replace(c, '-');
var path = Combine(Settings.Default.Logger.Path, sb.ToString());
Directory.CreateDirectory(path);
path = Combine(path, $"{now:yyyy-MM-dd}.log");
try
{
File.AppendAllLines(path, new[] { $"[{level}]{log}" });
}
catch (IOException)
{
Console.WriteLine("Error writing the log file: " + path);
}
}
}
}
}
}
5 changes: 5 additions & 0 deletions neo-cli/CLI/MainService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@ private set
protected override string Prompt => "neo";
public override string ServiceName => "NEO-CLI";

private Logger logger;
shargon marked this conversation as resolved.
Show resolved Hide resolved

/// <summary>
/// Constructor
/// </summary>
Expand Down Expand Up @@ -369,6 +371,9 @@ public async void Start(string[] args)
Settings.Initialize(new ConfigurationBuilder().AddJsonFile("config.mainnet.json").Build());
break;
}

logger = new Logger();

NeoSystem = new NeoSystem(Settings.Default.Storage.Engine);

foreach (var plugin in Plugin.Plugins)
Expand Down
16 changes: 16 additions & 0 deletions neo-cli/Settings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ namespace Neo
{
public class Settings
{
public LoggerSettings Logger { get; }
public StorageSettings Storage { get; }
public P2PSettings P2P { get; }
public UnlockWalletSettings UnlockWallet { get; }
Expand Down Expand Up @@ -39,13 +40,28 @@ public static Settings Default

public Settings(IConfigurationSection section)
{
this.Logger = new LoggerSettings(section.GetSection("Logger"));
this.Storage = new StorageSettings(section.GetSection("Storage"));
this.P2P = new P2PSettings(section.GetSection("P2P"));
this.UnlockWallet = new UnlockWalletSettings(section.GetSection("UnlockWallet"));
this.PluginURL = section.GetValue("PluginURL", "https://github.com/neo-project/neo-modules/releases/download/v{1}/{0}.zip");
}
}

public class LoggerSettings
{
public string Path { get; }
public bool ConsoleOutput { get; }
public bool Started { get; }

public LoggerSettings(IConfigurationSection section)
{
this.Path = string.Format(section.GetSection("Path").Value, ProtocolSettings.Default.Magic.ToString("X8"));
this.ConsoleOutput = section.GetSection("ConsoleOutput").Get<bool>();
this.Started = section.GetSection("Started").Get<bool>();
}
}

public class StorageSettings
{
public string Engine { get; }
Expand Down
5 changes: 5 additions & 0 deletions neo-cli/config.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
{
"ApplicationConfiguration": {
"Logger": {
"Path": "SystemLogs_{0}",
"ConsoleOutput": false,
"Started": false
},
"Storage": {
"Engine": "LevelDBStore"
},
Expand Down
5 changes: 5 additions & 0 deletions neo-cli/config.mainnet.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
{
"ApplicationConfiguration": {
"Logger": {
"Path": "SystemLogs_{0}",
"ConsoleOutput": false,
"Started": false
},
"Storage": {
"Engine": "LevelDBStore"
},
Expand Down
5 changes: 5 additions & 0 deletions neo-cli/config.testnet.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
{
"ApplicationConfiguration": {
"Logger": {
"Path": "SystemLogs_{0}",
"ConsoleOutput": false,
"Started": false
},
"Storage": {
"Engine": "LevelDBStore"
},
Expand Down