SafeDispatch/SafeMobileLIB_DLL/Logs/LOGS.cs

279 lines
8.8 KiB
C#
Raw Normal View History

2024-02-22 16:43:59 +00:00
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Threading;
using System.Diagnostics;
using System.Timers;
using System.Globalization;
using System.IO.Compression;
using System.Linq;
namespace SafeMobileLib
{
public class LOGS
{
public static bool active = true;
public static int expirationDays = 7;
private const int maxLogHours = 4;
private static int procID;
private static InterthreadMessageQueue<string> msgQueue;
private static InterthreadMessageQueue<string> msgQueue_Error;
System.Timers.Timer aTimer;
private static string path = "";
public static Boolean WRITE_LOGS = false;
public static String logFileName = "";
public LOGS(string _path = "")
{
if (!WRITE_LOGS)
return;
logFileName = String.Format("{0:yyyyMMdd_HHmm}.{1}", DateTime.Now, "log");
try
{
path = _path;
Process currentProcess = Process.GetCurrentProcess();
procID = currentProcess.Id;
msgQueue = new InterthreadMessageQueue<string>();
msgQueue_Error = new InterthreadMessageQueue<string>();
aTimer = new System.Timers.Timer();
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
// Set the Interval to 10 seconds.
aTimer.Interval = 5000;
aTimer.Enabled = true;
}
catch (Exception ex)
{
Console.WriteLine("Could not StartLOG!!!");
}
}
public static void LOG(string msg)
{
if (!WRITE_LOGS)
return;
//add to log file
try
{
if (msgQueue != null && active)
{
msg = String.Format("[### {0:H:mm:ss} ###] {1}", DateTime.Now, msg);
msgQueue.PostItem(msg);
}
}
catch (Exception ex)
{
Console.WriteLine("####LOG: Could not print debug information ####\n" + ex.ToString());
}
}
public static void LOG_Error(string msg)
{
if (!WRITE_LOGS)
return;
//add to log file
try
{
if (msgQueue_Error != null && active)
{
msg = String.Format("[### {0:H:mm:ss} ###] {1}", DateTime.Now, msg);
msgQueue_Error.PostItem(msg);
msgQueue.PostItem(msg);
}
}
catch (Exception ex)
{
Console.WriteLine("####LOG_Error: Could not print debug information ####\n" + ex.ToString());
}
}
private long numberOfRunningTasks = 0;
private object lockProcess = new object();
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
if (!WRITE_LOGS)
return;
// check if other previous tick is still running and exit if required
bool shouldExit = false;
lock (lockProcess)
{
if (numberOfRunningTasks > 0)
shouldExit = true;
}
if (shouldExit)
return;
try
{
string dirPath = "";
if (path == "")
dirPath = Environment.CurrentDirectory +
Path.DirectorySeparatorChar + "Logs";
else
dirPath = path +
Path.DirectorySeparatorChar + "Logs";
if (!Directory.Exists(dirPath))
{
Directory.CreateDirectory(dirPath);
}
ProcessLogs(dirPath, logFileName, msgQueue);
//maintenace
Maintenace(dirPath, logFileName);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
private void ProcessLogs(string dirPath, string name, InterthreadMessageQueue<string> msgQueue)
{
lock (lockProcess)
{
numberOfRunningTasks++;
}
string filePath = "";
if (WRITE_LOGS)
{
filePath = dirPath + Path.DirectorySeparatorChar + name;
if (!File.Exists(filePath))
{
using (System.IO.FileStream fs = System.IO.File.Create(filePath))
{
Byte[] info = new UTF8Encoding(true).GetBytes(DateTime.UtcNow.ToString() + "\n");
// Add some information to the file.
fs.Write(info, 0, info.Length);
}
Console.WriteLine("Creating new file!!! path:" + filePath);
}
}
try
{
if (msgQueue != null)
{
using (StreamWriter file = new System.IO.StreamWriter(filePath, true))
{
string line = msgQueue.GetItem(100);
while (line != default(string))
{
if (WRITE_LOGS)
file.WriteLine(line);
line = msgQueue.GetItem(100);
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
lock (lockProcess)
{
numberOfRunningTasks = 0;
}
}
}
private void Maintenace(string dirPath, string filename)
{
if (!WRITE_LOGS)
return;
string filePath = dirPath + Path.DirectorySeparatorChar + filename;
DateTime dateCreated;
DateTime.TryParseExact(filename.Substring(0, filename.Length - 4), "yyyyMMdd_HHmm", null,
DateTimeStyles.None, out dateCreated);
DateTime dtNow = DateTime.Now;
TimeSpan ts_sub = dtNow.Subtract(dateCreated);
if (ts_sub.TotalHours > maxLogHours)
{
logFileName = String.Format("{0:yyyyMMdd_HHmm}.{1}", DateTime.Now, "log");
//process normal logs
ProcessLogs(dirPath, logFileName, msgQueue);
Thread.Sleep(1000);
// compress old file
using (ZipArchive zip = ZipFile.Open("Logs\\" + filename.Replace(".log", "") + ".zip", ZipArchiveMode.Create))
{
ZipArchiveEntry zae = zip.CreateEntryFromFile(filePath, filename);
if (zae != null)
// delete the txt log file because it was archived
File.Delete(filePath);
}
// delete zip archives if older than xx days
if (expirationDays > 0)
Directory.GetFiles(dirPath)
.Select(f => new FileInfo(f))
.Where(f => f.CreationTime < DateTime.Now.AddDays((-1) * expirationDays))
.ToList()
.ForEach(f => f.Delete());
}
}
private void RemoveOlder(string dirPath, int days)
{
if (!WRITE_LOGS)
return;
string[] filePaths = Directory.GetFiles(dirPath);
for (int i = 0; i < filePaths.Length; i++)
{
try
{
if (!File.Exists(filePaths[i]))
continue;
if (filePaths[i].Contains("current") || filePaths[i].Contains("error"))
continue;
DateTime dateCreated;
DateTime.TryParseExact(filePaths[i].Substring(0, filePaths[i].Length - 4), "yyyyMMdd_HHmm", null,
DateTimeStyles.None, out dateCreated);
DateTime dtNow = DateTime.Now;
TimeSpan ts_sub = dtNow.Subtract(dateCreated);
if (ts_sub.TotalDays > 7)
{
if (File.Exists(filePaths[i]))
{
File.Delete(filePaths[i]);
}
}
}
catch (Exception ex)
{
Utils.WriteLine("Error in RemoveOlder :" + ex.ToString());
}
}
}
}
}