| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114 |
- using System.Diagnostics;
- namespace crusherScanner
- {
- /// <summary>
- /// Log file handler.
- /// </summary>
- internal static class Logging
- {
- private static string logFile = "";
- private static readonly string LocalLogDir = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\crusherScanner";
- /// <summary>
- /// Create/Append the current log file.
- /// </summary>
- /// <param name="message">Message to be written into the log file.</param>
- /// <returns></returns>
- 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;
- }
- /// <summary>
- /// Open the current log file in the system default text editor.
- /// </summary>
- public static void OpenInTextEditor()
- {
- StartProcess(LocalLogDir + "\\" + logFile);
- }
- /// <summary>
- /// Open the directroy that contains the log files.
- /// </summary>
- public static void OpenLogDirectory()
- {
- StartProcess(LocalLogDir);
- }
- /// <summary>
- /// Remove all log files from the log directory.
- /// </summary>
- 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);
- }
- }
- }
- /// <summary>
- /// Pass a location or file to the operating system to open.
- /// </summary>
- /// <param name="target">Location or file to open.</param>
- private static void StartProcess(string target)
- {
- new Process
- {
- StartInfo = new ProcessStartInfo(target)
- {
- UseShellExecute = true
- }
- }.Start();
- }
- }
- }
|