SafeNet/SafeNetLib/LOGS.cs
2021-02-24 13:50:23 +02:00

282 lines
9.6 KiB
C#

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Threading;
using System.Diagnostics;
using System.Timers;
using System.Globalization;
namespace SafeNetLib
{
public class LOGS
{
public static bool active = true;
private const int expirationDays = 7;
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;
private 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);
//msgQueue.PostItem(DateTime.Now.ToString("HH:mm:ss") + "\t" + procID + "\t" + 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);
//msgQueue_Error.PostItem(DateTime.Now.ToString("HH:mm:ss") + "\t" + procID + "\t" + msg);
//msgQueue.PostItem(DateTime.Now.ToString("HH:mm:ss") + "\t" + procID + "\t" + msg);
//msgQueue.PostItem("::::error::::" + DateTime.Now.ToString("HH:mm:ss") + "\t" + procID + "\t" + msg);
}
}
catch (Exception ex)
{
Console.WriteLine("####LOG_Error: Could not print debug information ####\n" + ex.ToString());
}
}
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
if (!WRITE_LOGS)
return;
try
{
string dirPath = "";
if (path == "")
dirPath = System.Environment.CurrentDirectory +
Path.DirectorySeparatorChar + "Logs";
else
dirPath = path +
Path.DirectorySeparatorChar + "Logs";
if (!Directory.Exists(dirPath))
{
Directory.CreateDirectory(dirPath);
}
ProcessLogs(dirPath, logFileName, msgQueue);
//process errors logs
//ProcessLogs(dirPath, "error.log", msgQueue_Error);
//maintenace
Maintenace(dirPath, logFileName);
//remove older log files
//RemoveOlder(dirPath, expirationDays);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
private void ProcessLogs(string dirPath, string name, InterthreadMessageQueue<string> msgQueue)
{
string filePath = "";
if (WRITE_LOGS)
{
//string filePath = dirPath + Path.DirectorySeparatorChar + "log_" + DateTime.Now.ToString("dd_MMM_yyyy") + ".log";
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
{
//StreamWriter sw = File.AppendText(filePath);
if (msgQueue != null)
{
string line = msgQueue.GetItem(100);
while (line != default(string))
{
//sw.WriteLine(line);
if (WRITE_LOGS)
{
using (System.IO.StreamWriter file = new System.IO.StreamWriter(filePath, true))
{
file.WriteLine(line);
}
}
line = msgQueue.GetItem(100);
}
}
//sw.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
//Console.WriteLine("Write to file timer!!!!!");
}
private void Maintenace(string dirPath, string filename)
{
if (!WRITE_LOGS)
return;
string filePath = dirPath + Path.DirectorySeparatorChar + filename;
/*
// Open the stream and read it back.
//read file creation time/// first line of file
DateTime dateCreated;
using (StreamReader sr = File.OpenText(filePath))
{
string s = "";
if ((s = sr.ReadLine()) != null)
{
dateCreated = DateTime.Parse(s);
}
else
dateCreated = DateTime.UtcNow;
}*/
DateTime dateCreated;
DateTime.TryParseExact(filename.Substring(0,filename.Length - 4), "yyyyMMdd_HHmm", null,
DateTimeStyles.None, out dateCreated);
DateTime dtNow = DateTime.Now;
//Console.WriteLine("dateCreated:" + dateCreated.ToString());
//Console.WriteLine("dtNow:" + dtNow.ToString());
//LOG("dtNow.DayOfYear:" + dtNow.DayOfYear);
//LOG("dateCreated.DayOfYear:" + dateCreated.DayOfYear);
TimeSpan ts_sub = dtNow.Subtract(dateCreated);
//Console.Write("TOTAL DAYS " + ts_sub.TotalDays);
//Console.Write("TOTAL Minutes " + ts_sub.TotalMinutes);
if (ts_sub.TotalHours > 6)
{
logFileName = String.Format("{0:yyyyMMdd_HHmm}.{1}", DateTime.Now, "log");
//process normal logs
ProcessLogs(dirPath, logFileName, msgQueue);
Thread.Sleep(1000);
/*
//new file name
string newfilePath = dirPath + Path.DirectorySeparatorChar + "log_" + dateCreated.ToString("dd_MMM_yyyy") + ".log";
if (File.Exists(newfilePath))
File.Delete(newfilePath);
File.Move(filePath, newfilePath);
if (File.Exists(filePath))
{
File.Delete(filePath);
}*/
}
}
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.ConsWrite(DebugMSG_Type.always, "Error in RemoveOlder: " + ex.ToString());
}
}
}
}
}