Added unhandled exception logging to Core and Monitor

This commit is contained in:
djbadders 2019-11-11 23:36:18 +00:00
parent e6dab15612
commit 99c0c628dc
5 changed files with 163 additions and 58 deletions

View File

@ -3,14 +3,10 @@ using System.Collections.Generic;
using System.Threading; using System.Threading;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Reflection;
using Core.Main;
using Core.Helper; using Core.Helper;
using Core.Main.DataObjects.PTMagicData; using Core.Main.DataObjects.PTMagicData;
using Core.MarketAnalyzer; using Core.MarketAnalyzer;
using Core.ProfitTrailer; using Core.ProfitTrailer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json; using Newtonsoft.Json;
namespace Core.Main namespace Core.Main

View File

@ -20,6 +20,7 @@
<CopyToOutputDirectory>Always</CopyToOutputDirectory> <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content> </Content>
<Content Include="wwwroot\assets\js\dca.js" CopyToOutputDirectory="Always" /> <Content Include="wwwroot\assets\js\dca.js" CopyToOutputDirectory="Always" />
<None Include="nlog.config" CopyToOutputDirectory="Always" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.5.1" /> <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.5.1" />

View File

@ -1,35 +1,49 @@
using System; using System;
using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Security.Permissions;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Core.Main; using Core.Main;
using Core.Helper;
using Microsoft.Extensions.DependencyInjection;
namespace Monitor { namespace Monitor
public class Program { {
public static void Main(string[] args) { public class Program
Console.WriteLine("##########################################################"); {
Console.WriteLine("#********************************************************#");
Console.WriteLine("INFO: Starting PT Magic Monitor..."); // Create a logger
Console.WriteLine("INFO: Beginning startup checks..."); private static LogHelper _log = ServiceHelper.BuildLoggerService().GetRequiredService<LogHelper>();
// Main entry point
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlAppDomain)]
public static void Main(string[] args)
{
// Register a global exception handler
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(GlobalUnhandledExceptionHandler);
// Start
WriteConsoleLogLine("##########################################################");
WriteConsoleLogLine("#********************************************************#");
WriteConsoleLogLine("INFO: Starting PT Magic Monitor...");
WriteConsoleLogLine("INFO: Beginning startup checks...");
string monitorBasePath = Directory.GetCurrentDirectory(); string monitorBasePath = Directory.GetCurrentDirectory();
if (!System.IO.File.Exists(monitorBasePath + Path.DirectorySeparatorChar + "appsettings.json")) { if (!System.IO.File.Exists(monitorBasePath + Path.DirectorySeparatorChar + "appsettings.json"))
{
monitorBasePath += Path.DirectorySeparatorChar + "Monitor"; monitorBasePath += Path.DirectorySeparatorChar + "Monitor";
} }
// Startup checks // Startup checks
string appsettingsJson = monitorBasePath + Path.DirectorySeparatorChar + "appsettings.json"; string appsettingsJson = monitorBasePath + Path.DirectorySeparatorChar + "appsettings.json";
if (!File.Exists(appsettingsJson)) { if (!File.Exists(appsettingsJson))
Console.WriteLine("ERROR: appsettings.json not found: '" + appsettingsJson + "'. Please check if the file exists. If not, review the PT Magic setup steps listed on the wiki!"); {
WriteConsoleLogLine("ERROR: appsettings.json not found: '" + appsettingsJson + "'. Please check if the file exists. If not, review the PT Magic setup steps listed on the wiki!");
if (!Console.IsInputRedirected) Console.ReadKey(); if (!Console.IsInputRedirected) Console.ReadKey();
} else { }
Console.WriteLine("INFO: appsettings.json found in " + monitorBasePath); else
{
WriteConsoleLogLine("INFO: appsettings.json found in " + monitorBasePath);
IConfiguration config = new ConfigurationBuilder() IConfiguration config = new ConfigurationBuilder()
.SetBasePath(monitorBasePath) .SetBasePath(monitorBasePath)
@ -38,61 +52,80 @@ namespace Monitor {
string ptMagicBasePath = config.GetValue<string>("PTMagicBasePath"); string ptMagicBasePath = config.GetValue<string>("PTMagicBasePath");
if (!ptMagicBasePath.EndsWith(Path.DirectorySeparatorChar)) { if (!ptMagicBasePath.EndsWith(Path.DirectorySeparatorChar))
{
ptMagicBasePath += Path.DirectorySeparatorChar; ptMagicBasePath += Path.DirectorySeparatorChar;
} }
// More startup checks // More startup checks
// Check if PT Magic directoy is correctly configured // Check if PT Magic directoy is correctly configured
if (!Directory.Exists(ptMagicBasePath)) { if (!Directory.Exists(ptMagicBasePath))
Console.WriteLine("ERROR: PT Magic directory not found: '" + ptMagicBasePath + "'. Please check your setting for 'PTMagicBasePath' in 'Monitor/appsettings.json'"); {
WriteConsoleLogLine("ERROR: PT Magic directory not found: '" + ptMagicBasePath + "'. Please check your setting for 'PTMagicBasePath' in 'Monitor/appsettings.json'");
if (!Console.IsInputRedirected) Console.ReadKey(); if (!Console.IsInputRedirected) Console.ReadKey();
} else { }
Console.WriteLine("INFO: PT Magic directory found at " + ptMagicBasePath); else
{
WriteConsoleLogLine("INFO: PT Magic directory found at " + ptMagicBasePath);
// Check if PT Magic settings file exists // Check if PT Magic settings file exists
string settingsGeneralJson = ptMagicBasePath + "settings.general.json"; string settingsGeneralJson = ptMagicBasePath + "settings.general.json";
if (!File.Exists(settingsGeneralJson)) { if (!File.Exists(settingsGeneralJson))
Console.WriteLine("ERROR: PT Magic settings not found: '" + settingsGeneralJson + "'. Please check if you setup PT Magic correctly!"); {
WriteConsoleLogLine("ERROR: PT Magic settings not found: '" + settingsGeneralJson + "'. Please check if you setup PT Magic correctly!");
if (!Console.IsInputRedirected) Console.ReadKey(); if (!Console.IsInputRedirected) Console.ReadKey();
} else { }
Console.WriteLine("INFO: settings.general.json found at " + settingsGeneralJson); else
{
WriteConsoleLogLine("INFO: settings.general.json found at " + settingsGeneralJson);
// Check if PT Magic settings file exists // Check if PT Magic settings file exists
string lastRuntimeSummaryJson = ptMagicBasePath + Constants.PTMagicPathData + Path.DirectorySeparatorChar + "LastRuntimeSummary.json"; string lastRuntimeSummaryJson = ptMagicBasePath + Constants.PTMagicPathData + Path.DirectorySeparatorChar + "LastRuntimeSummary.json";
if (!File.Exists(lastRuntimeSummaryJson)) { if (!File.Exists(lastRuntimeSummaryJson))
Console.WriteLine("ERROR: PT Magic runtime summary not found: '" + lastRuntimeSummaryJson + "'. Please wait for PT Magic to complete its first run!"); {
WriteConsoleLogLine("ERROR: PT Magic runtime summary not found: '" + lastRuntimeSummaryJson + "'. Please wait for PT Magic to complete its first run!");
if (!Console.IsInputRedirected) Console.ReadKey(); if (!Console.IsInputRedirected) Console.ReadKey();
} else { }
Console.WriteLine("INFO: LastRuntimeSummary.json found at " + lastRuntimeSummaryJson); else
{
WriteConsoleLogLine("INFO: LastRuntimeSummary.json found at " + lastRuntimeSummaryJson);
PTMagicConfiguration ptMagicConfiguration = null; PTMagicConfiguration ptMagicConfiguration = null;
try { try
{
ptMagicConfiguration = new PTMagicConfiguration(ptMagicBasePath); ptMagicConfiguration = new PTMagicConfiguration(ptMagicBasePath);
} catch (Exception ex) { }
catch (Exception ex)
{
throw ex; throw ex;
} }
string wwwrootPath = monitorBasePath + Path.DirectorySeparatorChar + "wwwroot"; string wwwrootPath = monitorBasePath + Path.DirectorySeparatorChar + "wwwroot";
if (!Directory.Exists(wwwrootPath)) { if (!Directory.Exists(wwwrootPath))
Console.WriteLine("ERROR: wwwroot directory not found: '" + wwwrootPath + "'. Did you copy all files as instructed on the wiki?"); {
WriteConsoleLogLine("ERROR: wwwroot directory not found: '" + wwwrootPath + "'. Did you copy all files as instructed on the wiki?");
if (!Console.IsInputRedirected) Console.ReadKey(); if (!Console.IsInputRedirected) Console.ReadKey();
} else { }
Console.WriteLine("INFO: wwwroot directory found at " + wwwrootPath); else
{
WriteConsoleLogLine("INFO: wwwroot directory found at " + wwwrootPath);
string assetsPath = wwwrootPath + Path.DirectorySeparatorChar + "assets"; string assetsPath = wwwrootPath + Path.DirectorySeparatorChar + "assets";
if (!Directory.Exists(assetsPath)) { if (!Directory.Exists(assetsPath))
Console.WriteLine("ERROR: assets directory not found: '" + assetsPath + "'. Did you copy all files as instructed on the wiki?"); {
WriteConsoleLogLine("ERROR: assets directory not found: '" + assetsPath + "'. Did you copy all files as instructed on the wiki?");
if (!Console.IsInputRedirected) Console.ReadKey(); if (!Console.IsInputRedirected) Console.ReadKey();
} else { }
Console.WriteLine("INFO: assets directory found at " + assetsPath); else
Console.WriteLine("INFO: ALL CHECKS COMPLETED - ATTEMPTING TO START WEBSERVER..."); {
Console.WriteLine("#********************************************************#"); WriteConsoleLogLine("INFO: assets directory found at " + assetsPath);
Console.WriteLine(""); WriteConsoleLogLine("INFO: ALL CHECKS COMPLETED - ATTEMPTING TO START WEBSERVER...");
Console.WriteLine("DO NOT CLOSE THIS WINDOW! THIS IS THE WEBSERVER FOR YOUR MONITOR!"); WriteConsoleLogLine("#********************************************************#");
Console.WriteLine(""); WriteConsoleLogLine("");
Console.WriteLine("##########################################################"); WriteConsoleLogLine("DO NOT CLOSE THIS WINDOW! THIS IS THE WEBSERVER FOR YOUR MONITOR!");
Console.WriteLine(""); WriteConsoleLogLine("");
WriteConsoleLogLine("##########################################################");
WriteConsoleLogLine("");
BuildWebHost(args, monitorBasePath, monitorBasePath + Path.DirectorySeparatorChar + "wwwroot", ptMagicConfiguration.GeneralSettings.Monitor.Port).Run(); BuildWebHost(args, monitorBasePath, monitorBasePath + Path.DirectorySeparatorChar + "wwwroot", ptMagicConfiguration.GeneralSettings.Monitor.Port).Run();
} }
@ -112,5 +145,31 @@ namespace Monitor {
.UseContentRoot(contentRoot) .UseContentRoot(contentRoot)
.UseWebRoot(webroot) .UseWebRoot(webroot)
.Build(); .Build();
// Log writer
private static void WriteConsoleLogLine(string line)
{
// Write to console and log
Console.WriteLine(line);
_log.DoLogInfo(line);
}
// Global unhandled exception handler
private static void GlobalUnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs args)
{
Exception e = (Exception)args.ExceptionObject;
Console.WriteLine("Unhandled exception occurred: " + e.ToString());
if (args.IsTerminating)
{
_log.DoLogCritical("Unhandled fatal exception occurred: ", e);
}
else
{
_log.DoLogError("Unhandled fatal exception occurred: " + e.ToString());
} }
} }
}
}

28
Monitor/nlog.config Normal file
View File

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="utf-8" ?>
<!-- XSD manual extracted from package NLog.Schema: https://www.nuget.org/packages/NLog.Schema-->
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xsi:schemaLocation="NLog NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true"
internalLogLevel="Info" >
<!-- the targets to write to -->
<targets>
<!-- write logs to file -->
<target xsi:type="File" name="File" fileName="${basedir}/_logs/${shortdate}.txt"
layout="${date} ${level:uppercase=true} - ${message} ${exception:format=type,message,stacktrace}"
archiveEvery="Day"
archiveNumbering="Rolling"
maxArchiveFiles="7" />
<target xsi:type="ColoredConsole" name="Console"
layout="${date} ${level:uppercase=true} - ${message} ${exception:format=type,message,stacktrace}" />
</targets>
<!-- rules to map from logger name to target -->
<rules>
<logger name="*" minlevel="Info" writeTo="Console" />
<logger name="*" minlevel="Debug" writeTo="File" />
</rules>
</nlog>

View File

@ -1,10 +1,8 @@
using System; using System;
using System.Threading; using System.Threading;
using System.IO;
using System.Reflection; using System.Reflection;
using Core.Main; using System.Security.Permissions;
using Core.Helper; using Core.Helper;
using Core.Main.DataObjects.PTMagicData;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
[assembly: AssemblyVersion("2.2.10")] [assembly: AssemblyVersion("2.2.10")]
@ -14,10 +12,18 @@ namespace PTMagic
{ {
class Program class Program
{ {
static void Main(string[] args) // Create a logger
private static LogHelper _log = ServiceHelper.BuildLoggerService().GetRequiredService<LogHelper>();
// Main class entry
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlAppDomain)]
public static void Main(string[] args)
{ {
// Register a global exception handler
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(GlobalUnhandledExceptionHandler);
// Init PTMagic // Init PTMagic
Core.Main.PTMagic ptMagic = new Core.Main.PTMagic(ServiceHelper.BuildLoggerService().GetRequiredService<LogHelper>()); Core.Main.PTMagic ptMagic = new Core.Main.PTMagic(_log);
ptMagic.CurrentVersion = Assembly.GetExecutingAssembly().GetName().Version; ptMagic.CurrentVersion = Assembly.GetExecutingAssembly().GetName().Version;
// Start process // Start process
@ -29,5 +35,20 @@ namespace PTMagic
Thread.Sleep(10000); Thread.Sleep(10000);
} }
} }
// Global unhandled exception handler
private static void GlobalUnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs args)
{
Exception e = (Exception)args.ExceptionObject;
if (args.IsTerminating)
{
_log.DoLogCritical("Unhandled fatal exception occurred: ", e);
}
else
{
_log.DoLogError("Unhandled fatal exception occurred: " + e.ToString());
}
}
} }
} }