Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Logging #19

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
2 changes: 1 addition & 1 deletion App.config
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8"/>
</startup>
</configuration>
37 changes: 32 additions & 5 deletions Config.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,14 +51,19 @@ public static IPAddress TheIPAddress
/// <summary> Use numbers for the ping instead of a graph. </summary>
public static bool UseNumbers;


#region Logging options
public static bool EnableLogging;
public static string LogDirPath;
#endregion

static Config() => Reset();

public static void SetAll(int delay, int maxPing, Color bgColor, Color goodColor, Color normalColor,
Color badColor, bool runOnStartup, IPAddress address,
bool alarmConnectionLost, bool alarmTimeOut, bool alarmResumed, bool useNumbers,
string _SFXConnectionLost, string _SFXTimeOut, string _SFXResumed, bool offlineCounter)
public static void SetAll(
int delay, int maxPing, Color bgColor, Color goodColor, Color normalColor,
Color badColor, bool runOnStartup, IPAddress address,
bool alarmConnectionLost, bool alarmTimeOut, bool alarmResumed, bool useNumbers,
string _SFXConnectionLost, string _SFXTimeOut, string _SFXResumed, bool offlineCounter,
bool enableLogging, string logPath)
{
Delay = delay;
MaxPing = maxPing;
Expand All @@ -76,6 +81,16 @@ public static void SetAll(int delay, int maxPing, Color bgColor, Color goodColor
SFXTimeOut = _SFXTimeOut;
SFXResumed = _SFXResumed;
OfflineCounter = offlineCounter;
EnableLogging = enableLogging;
LogDirPath = logPath;

if (EnableLogging)
{
if (!Directory.Exists(LogDirPath))
{
Directory.CreateDirectory(LogDirPath);
}
}
}

public static void Reset()
Expand All @@ -97,6 +112,7 @@ public static void Reset()
SFXTimeOut = NONE_SFX;
SFXResumed = NONE_SFX;
RunOnStartup = false;
EnableLogging = false;
}

public static void Load()
Expand Down Expand Up @@ -182,6 +198,14 @@ public static void Load()
case nameof(OfflineCounter):
bool.TryParse(split[1], out OfflineCounter);
break;

case nameof(EnableLogging):
bool.TryParse(split[1], out EnableLogging);
break;

case nameof(LogDirPath):
LogDirPath = split[1];
break;
}
}
}
Expand Down Expand Up @@ -236,6 +260,9 @@ public static void Save()

sb.AppendLine($"{nameof(OfflineCounter)} {OfflineCounter}");

sb.AppendLine($"{nameof(EnableLogging)} {EnableLogging}");
sb.AppendLine($"{nameof(LogDirPath)} {LogDirPath}");

File.WriteAllText(CONF_FILE_NAME, sb.ToString());
}

Expand Down
140 changes: 125 additions & 15 deletions NotificationIcon.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
using PingoMeter.vendor;
using Microsoft.Win32;
using PingoMeter.vendor;
using PingoMeter.vendor.StartupCreator;

using System;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Media;
Expand Down Expand Up @@ -35,6 +37,10 @@ internal sealed class NotificationIcon
SoundPlayer SFXTimeOut;
SoundPlayer SFXResumed;

IPStatus? previousLogStatus = null;
string previousLogMessage = null;
DateTimeOffset lastPowerModeChangeTime = DateTimeOffset.MinValue;

enum PingHealthEnum
{
Good,
Expand Down Expand Up @@ -84,15 +90,21 @@ public NotificationIcon()
noneIcon = Icon.FromHandle(hiconOriginal);
g = Graphics.FromImage(drawable);
font = new Font("Consolas", 9f, FontStyle.Bold);
font100 = new Font("Consolas", 7f, FontStyle.Bold);;
font100 = new Font("Consolas", 7f, FontStyle.Bold);
WriteLog("Startup", null, $"{Process.GetCurrentProcess().ProcessName} started");

SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged;

SetIcon();
}

~NotificationIcon()
{
SystemEvents.PowerModeChanged -= SystemEvents_PowerModeChanged;
DestroyIcon(hicon);
DestroyIcon(hiconOriginal);
g.Dispose();
WriteLog("Shutdown", null, $"{Process.GetCurrentProcess().ProcessName} shutting down");
}

public void Run()
Expand Down Expand Up @@ -270,7 +282,12 @@ private void PingPool(object _)
{
PingReply reply = p.Send(Config.TheIPAddress, 5000, buffer);

switch (reply.Status)
//there is a lower-limit to the configured timeout, so we have to override the timeout process.
var calculatedStatus = (reply.Status == IPStatus.Success && reply.RoundtripTime > Config.MaxPing)
? IPStatus.TimedOut
: reply.Status;

switch (calculatedStatus)
{
case IPStatus.TimedOut:
DrawGraph(-1L);
Expand All @@ -287,6 +304,8 @@ private void PingPool(object _)
}

alarmStatus = AlarmEnum.TimeOut;

WriteLog(calculatedStatus, $"{ notifyIcon.Text } ({ reply.RoundtripTime }ms)", doRepeat: false);
}
else
{
Expand All @@ -306,18 +325,18 @@ private void PingPool(object _)
notifyIcon.ShowBalloonTip(BALLOON_TIP_TIME_OUT, "PingoMeter", "Ping resumed", ToolTipIcon.Info);
}

WriteLog(calculatedStatus, $"Ping resumed ({reply.RoundtripTime}ms)", doRepeat: false);

alarmStatus = AlarmEnum.OK;
timeOutAgain = false;
break;

default:

DrawGraph(-1L);

var statusName = GetIPStatusName(reply.Status);
notifyIcon.Text = "Status: " + statusName;



if (alarmStatus != AlarmEnum.ConnectionLost)
{
PlaySound(SFXConnectionLost, Config.SFXConnectionLost);
Expand All @@ -327,23 +346,40 @@ private void PingPool(object _)
}

alarmStatus = AlarmEnum.ConnectionLost;
WriteLog(calculatedStatus, "Connection Lost.", doRepeat: false);
break;
}
}
catch (PingException)
{
DrawGraph(-1L);
notifyIcon.Text = "Status: Connection lost.";

if (alarmStatus != AlarmEnum.ConnectionLost)
//false positives happen on wake.
//check if just woke up
int wakeTimeInMillis = 500;
var utcnow = DateTimeOffset.Now;
if ((utcnow - lastPowerModeChangeTime).TotalMilliseconds < wakeTimeInMillis)
{
PlaySound(SFXConnectionLost, Config.SFXConnectionLost);

if (Config.AlarmConnectionLost)
notifyIcon.ShowBalloonTip(BALLOON_TIP_TIME_OUT, "PingoMeter", "Connection lost", ToolTipIcon.Error);
//just woke up
DrawGraph(-1L);
notifyIcon.Text = "Status: Connection lost?";
WriteLog("Wake", null, $"{Process.GetCurrentProcess().ProcessName} lost connection because PC waking up");
}
else
{
DrawGraph(-1L);
notifyIcon.Text = "Status: Connection lost.";

alarmStatus = AlarmEnum.ConnectionLost;
if (alarmStatus != AlarmEnum.ConnectionLost)
{
PlaySound(SFXConnectionLost, Config.SFXConnectionLost);

if (Config.AlarmConnectionLost)
notifyIcon.ShowBalloonTip(BALLOON_TIP_TIME_OUT, "PingoMeter", "Connection lost", ToolTipIcon.Error);
}

alarmStatus = AlarmEnum.ConnectionLost;

WriteLog(IPStatus.Unknown, "Connection Lost (PingException).", doRepeat: false);
}
}
catch (Exception ex)
{
Expand All @@ -353,6 +389,7 @@ private void PingPool(object _)

notifyIcon.ShowBalloonTip(BALLOON_TIP_TIME_OUT, "PingoMeter", "Error: " + ex.Message, ToolTipIcon.Error);
alarmStatus = AlarmEnum.None;
WriteLog(IPStatus.Unknown, $"Error: {ex.Message}", doRepeat: false);
}

Thread.Sleep(Config.Delay);
Expand Down Expand Up @@ -503,5 +540,78 @@ private string GetIPStatusName(IPStatus status)
}
}

/// <summary>
/// Write into the monthly log-file
/// </summary>
/// <param name="status">IPStatus object that describes the info. Will be logged by both IP and text.</param>
/// <param name="message">Text message to log. Quotes will be escaped if necessary. Not null.</param>
/// <param name="doRepeat">bool to re-log the same message more than once if eg connection is out.</param>
private void WriteLog(IPStatus status, string message, bool doRepeat)
{
// note that we only care if the message is distinct if its UNKNOWN, otherwise we assume all messages are the same.
// this lets us add some metadata to the non-error messages without duplication.
if (doRepeat || !status.Equals(previousLogStatus) || !(message.Equals(previousLogMessage) || (int)status >= 0)) {
previousLogStatus = status;
previousLogMessage = message;
var eventName = status.ToString();
var ipStatusNum = (int)status;
WriteLog(eventName, ipStatusNum, message);
}
}

/// <summary>
/// Write into the monthly log-file
/// </summary>
/// <param name="ipStatusNum">Event number to log.</param>
/// /// <param name="eventName">Event name to log. Will match the .</param>
/// <param name="message">Text message to log. Quotes will be escaped if necessary. Not null.</param>
private void WriteLog(string eventName, int? ipStatusNum, string message)
{
if (Config.EnableLogging)
{
var now = DateTime.Now;

// csv escape
// this should probably all be done with a proper CSV package but this project doesn't have any
// external package dependencies so I don't want to start now.
var messageEscapedCsv = (message.Contains("\"") || message.Contains("\n"))
? $"\"{message.Replace("\"", "\"\"")}\""
: message;

if (!Directory.Exists(Config.LogDirPath))
{
Directory.CreateDirectory(Config.LogDirPath);
}

var logFilePath = Path.Combine(Config.LogDirPath, $@"{Process.GetCurrentProcess().ProcessName}-{now.Year}-{now.Month}.log.csv");
if(!File.Exists(logFilePath))
{
string[] headings = { "Date", "Event", "IPStatus", "IPAddress", "Message" };
string headingLine = string.Join(", ", headings);
using (StreamWriter writer = new StreamWriter(logFilePath))
{
writer.WriteLine(headingLine);
writer.Flush();
}
}

using (StreamWriter writer = new StreamWriter(logFilePath, append:true))
{
var date = now.ToString("yyyy-MM-dd HH:mm:ss");
var ipAddressLogEntry = ipStatusNum.HasValue
? Config.TheIPAddress.ToString()
: string.Empty; //no need to log address for startup/shutdown operations.
string[] body = { date, eventName, ipStatusNum.ToString(), ipAddressLogEntry, messageEscapedCsv };
string bodyLine = string.Join(", ", body);
writer.WriteLine(bodyLine);
writer.Flush();
}
}
}

private void SystemEvents_PowerModeChanged(object sender, PowerModeChangedEventArgs e)
{
lastPowerModeChangeTime = DateTimeOffset.Now;
}
}
}
2 changes: 1 addition & 1 deletion PingoMeter.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
<OutputType>WinExe</OutputType>
<RootNamespace>PingoMeter</RootNamespace>
<AssemblyName>PingoMeter</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<TargetFrameworkProfile />
Expand Down
2 changes: 1 addition & 1 deletion Properties/Resources.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Properties/Settings.Designer.cs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading