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

Move SystemLog to neo-cli #587

Merged
merged 22 commits into from
May 26, 2020
Merged
Show file tree
Hide file tree
Changes from 9 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
41 changes: 41 additions & 0 deletions Neo.ConsoleService/ConsoleColorSet.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
using System;

namespace Neo.ConsoleService
{
public class ConsoleColorSet
{
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;
}
}
}
103 changes: 103 additions & 0 deletions neo-cli/CLI/Logger.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
using Neo.ConsoleService;
using Neo.Plugins;
using System;
using System.IO;
using System.Reflection;
using System.Text;
using static System.IO.Path;

namespace Neo.CLI
{
public class Logger : Plugin, ILogPlugin
erikzhang marked this conversation as resolved.
Show resolved Hide resolved
{
private static readonly ConsoleColorSet DebugColor = new ConsoleColorSet(ConsoleColor.Cyan);
private static readonly ConsoleColorSet InfoColor = new ConsoleColorSet(ConsoleColor.White);
private static readonly ConsoleColorSet WarningColor = new ConsoleColorSet(ConsoleColor.Yellow);
private static readonly ConsoleColorSet ErrorColor = new ConsoleColorSet(ConsoleColor.Red);
private static readonly ConsoleColorSet FatalColor = new ConsoleColorSet(ConsoleColor.Red);

public override string Name => "SystemLog";
public override string ConfigFile => Combine(GetDirectoryName(Assembly.GetEntryAssembly().Location), "config.json");
erikzhang marked this conversation as resolved.
Show resolved Hide resolved

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: DebugColor.Apply(); break;
case LogLevel.Error: ErrorColor.Apply(); break;
case LogLevel.Fatal: FatalColor.Apply(); break;
case LogLevel.Info: InfoColor.Apply(); break;
case LogLevel.Warning: WarningColor.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;

/// <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:/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>();
erikzhang marked this conversation as resolved.
Show resolved Hide resolved
}
}

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