using System.Diagnostics;
namespace crusherScanner
{
///
/// Log file handler.
///
internal static class Logging
{
private static string logFile = "";
private static readonly string LocalLogDir = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\crusherScanner";
///
/// Create/Append the current log file.
///
/// Message to be written into the log file.
///
public static bool Append(string message)
{
var dt = DateTime.Now;
if (!Directory.Exists(LocalLogDir))
{
try
{
Directory.CreateDirectory(LocalLogDir);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error in logging!", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
}
// if no log file for this instance create one
if (logFile == "")
{
logFile = dt.ToString("yyyyMMdd") + "-0.log";
for (int i = 1; i < 100; i++)
{
// if an old log file is detected create a new one for this instance.
if (File.Exists(LocalLogDir + "\\" + logFile))
{
logFile = dt.ToString("yyyyMMdd") + "-" + i + ".log";
}
else
{
break;
}
}
}
try
{
File.AppendAllText(LocalLogDir + "\\" + logFile, dt.ToString("yyyyMMddTHHmmss") + "---" + message + "\n");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error in logging!", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
return true;
}
///
/// Open the current log file in the system default text editor.
///
public static void OpenInTextEditor()
{
StartProcess(LocalLogDir + "\\" + logFile);
}
///
/// Open the directroy that contains the log files.
///
public static void OpenLogDirectory()
{
StartProcess(LocalLogDir);
}
///
/// Remove all log files from the log directory.
///
public static void PurgeLogs()
{
DialogResult result = MessageBox.Show("Are you sure you want to delete ALL logs?", "Purge Logs", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation);
if (result == DialogResult.Yes)
{
var logs = Directory.EnumerateFiles(LocalLogDir, "*-*.log");
foreach (var log in logs)
{
File.Delete(log);
}
}
}
///
/// Pass a location or file to the operating system to open.
///
/// Location or file to open.
private static void StartProcess(string target)
{
new Process
{
StartInfo = new ProcessStartInfo(target)
{
UseShellExecute = true
}
}.Start();
}
}
}