Files
SteamWare/SteamWareLib/logger.cs
T
Samuele Locatelli a54cd875ce refresh
2021-07-16 18:00:40 +02:00

651 lines
23 KiB
C#

using System;
using System.IO;
using System.Threading;
namespace SteamWare
{
/// <summary>
/// tipo di log ammesso
/// </summary>
public enum tipoLog
{
/// <summary>
/// informazioni di debug
/// </summary>
DEBUG,
/// <summary>
/// dump diagnostica
/// </summary>
DUMP_DIAGN,
/// <summary>
/// errori
/// </summary>
ERROR,
/// <summary>
/// eccezioni nell'esecuzione try/catch
/// </summary>
EXCEPTION,
/// <summary>
/// errori fatali
/// </summary>
FATAL,
/// <summary>
/// informazioni opzionali
/// </summary>
INFO,
/// <summary>
/// log dei lemmi invocati per traduzione da vocabolario
/// </summary>
LEMMA,
/// <summary>
/// fase di avvio componente
/// </summary>
STARTUP,
/// <summary>
/// avvisi
/// </summary>
WARNING
}
/// <summary>
/// classe gesione log files applicazioni
/// </summary>
public class logger
{
#region dichiarazione variabili
/// <summary>
/// metodo gestione wirteLock su file log
/// </summary>
private static ReaderWriterLockSlim _readWriteLock = new ReaderWriterLockSlim();
/// <summary>
/// Ultima verifica directory (x shrink)
/// </summary>
private static DateTime lastDirCheck;
/// <summary>
/// controlla se si debba mantenere sotto controllo la dimensioen della cartella logs
/// </summary>
protected bool _doShrinkFolder;
/// <summary>
/// directory base x logs
/// </summary>
protected string _logBaseDir;
/// <summary>
/// nome del file corrente
/// </summary>
protected string _logfileName;
/// <summary>
/// max mb di log da accumulare
/// </summary>
protected int _logMaxMb;
/// <summary>
/// max numero di veto count da accettare
/// </summary>
protected int _vetoRedisCheckLimit = 100;
/// <summary>
/// max numero di veto count da accettare
/// </summary>
protected int _vetoRedisPausePurge = 20;
/// <summary>
/// max numero di key da eliminare ogni check
/// </summary>
protected int _vetoRedisPurgeMax = 200;
/// <summary>
/// Indica se sia abilitato log diagnostico esteso...
/// </summary>
protected bool enableDumpDiag = false;
#endregion dichiarazione variabili
#region metodi esposti
/// <summary>
/// singleton del logger
/// </summary>
public static logger lg = new logger();
/// <summary>
/// avvio del logger nella dir desiderata
/// </summary>
public logger()
{
string _logDir = memLayer.ML.confReadString("_logDir");
try
{
_logBaseDir = fileMover.getFilePath(_logDir);
}
catch (Exception exc)
{
_logBaseDir = _logDir != "" ? _logDir : "~/logs/";
}
_logMaxMb = 100; // di default 100 mb...
try
{
_doShrinkFolder = memLayer.ML.confReadBool("doShrinkFolder");
}
catch
{
_doShrinkFolder = true;
}
try
{
enableDumpDiag = memLayer.ML.confReadBool("enableDumpDiag");
}
catch
{
enableDumpDiag = false;
}
// imposto i parametri per la pulizia dei veto su Redis
try
{
if (!string.IsNullOrEmpty(memLayer.ML.CRS("vetoRedisCheckLimit")))
{
_vetoRedisCheckLimit = memLayer.ML.CRI("vetoRedisCheckLimit");
}
}
catch
{ }
try
{
if (!string.IsNullOrEmpty(memLayer.ML.CRS("vetoRedisPausePurge")))
{
_vetoRedisPausePurge = memLayer.ML.CRI("vetoRedisPausePurge");
}
}
catch
{ }
try
{
if (!string.IsNullOrEmpty(memLayer.ML.CRS("vetoRedisPurgeMax")))
{
_vetoRedisPurgeMax = memLayer.ML.CRI("vetoRedisPurgeMax");
}
}
catch
{ }
// all'avvio imposto ultimo check a 23 ore fa... così farà shrink DOPO 1 h da avvio
lastDirCheck = DateTime.Now.AddHours(-23);
}
/// <summary>
/// avvio del logger nella dir desiderata
/// </summary>
public logger(string _baseDir)
{
_logBaseDir = _baseDir;
_logMaxMb = 40; // di default 40 mb...
}
/// <summary>
/// avvio del logger nella dir desiderata con il max di dati indicato
/// </summary>
public logger(string _baseDir, int _logMaxMB)
{
_logBaseDir = _baseDir;
_logMaxMb = _logMaxMB;
}
/// <summary>
/// livello di log applicazione (da web.config, chiave '_logLevel')
/// </summary>
public int logLevel
{
get
{
int answ = -1;
try
{
answ = memLayer.ML.CRI("_logLevel");
}
catch
{
scriviLog("non ho trovato chiave di registro x logLevel...", tipoLog.ERROR);
}
return answ;
}
}
/// <summary>
/// Vera chiamata scrittura log x override con gestione REDIS di calmierazione
/// </summary>
/// <param name="_testoPre"></param>
/// <returns></returns>
private bool doScriviLog(string _testoPre)
{
bool fatto = false;
// attenzione: rimpiazzo eventuali "</br>" con newline...
string _testo = string.Format("{0:H:mm:ss ffff} \t{1}", DateTime.Now, _testoPre.Replace("<br>", Environment.NewLine).Replace("<br/>", Environment.NewLine).Replace("<br />", Environment.NewLine));
// se è configurato x shrink ed è passato almeno 1 gg da ultimo check...
if (_doShrinkFolder && lastDirCheck.AddDays(1) < DateTime.Now)
{
// verifica dim directory ed eventualmente cancella... - opzionale
shrinkDir();
// salvo nuova ora di check
lastDirCheck = DateTime.Now;
}
// (ri)genera il nome del file di log...
newLogfileName();
// scrivo thread safe
fatto = WriteToFileThreadSafe(_logfileName, _testo);
return fatto;
}
/// <summary>
/// Effettua verifica e pulizia eventuali vecchi messaggi errore...
/// </summary>
private void purgeOldVeto()
{
// limite minimo di chaivi salvate per cui procedere coi controlli
int checkLimit = _vetoRedisCheckLimit;
// limito cleanup x avere un operazione graduale...
int maxCleanup = _vetoRedisPurgeMax;
// parto recuperando i valori VETO.... se > 100...
string redKeyCounters = memLayer.ML.redHash("Logger:Counter:*");
string redLastCheck = memLayer.ML.redHash("Logger:CheckLock");
// se non ho un veto check...
if (string.IsNullOrEmpty(memLayer.ML.getRSV(redLastCheck)))
{
memLayer.ML.setRSV(redLastCheck, "LOCK", _vetoRedisPausePurge);
int numCount = memLayer.ML.redCountKey(redKeyCounters);
if (numCount > checkLimit)
{
// se necessario riduco valore maxCleanup --> checkLimit...
maxCleanup = numCount < maxCleanup ? checkLimit : maxCleanup;
var redKeysList2check = memLayer.ML.redGetKeys(redKeyCounters);
foreach (var item in redKeysList2check)
{
// cerco il duale... se NON lo trovo
if (!memLayer.ML.redHashPresentSz(item.ToString().Replace(":Logger:Counter:", ":Logger:Veto:")))
{
//// loggo!
//doScriviLog(item);
// elimino...
memLayer.ML.redDelKey(item);
maxCleanup--;
}
if (maxCleanup <= 0)
{
break;
}
}
}
}
}
/// <summary>
/// formatta un blococ di diagnostica (titolo, contenuto / eccezione)
/// </summary>
/// <param name="titolo"></param>
/// <param name="contenuto"></param>
/// <returns></returns>
protected string formDiagBlock(string titolo, string contenuto)
{
string answ = SteamwareStrings.charTitle(titolo, '-', 60);
try
{
answ += SteamwareStrings.addLine(contenuto);
}
catch
{
answ += string.Format("Errore diagnostica {0}", titolo);
}
return answ;
}
/// <summary>
/// Restituisce il numero di chiavi di vedo e di chiavi di count ative
/// </summary>
public void getLoggerVetoStats(out int numVeto, out int numCount)
{
string redKeyCounters = memLayer.ML.redHash("Logger:Counter:*");
string redKeyVeto = memLayer.ML.redHash("Logger:Veto:*");
numCount = memLayer.ML.redCountKey(redKeyCounters);
numVeto = memLayer.ML.redCountKey(redKeyVeto);
}
/// <summary>
/// resetta il logfile odierno
/// </summary>
public void resetLogFile()
{
newLogfileName();
FileInfo fi = new FileInfo(_logfileName);
fi.Delete();
scriviLog("ResetFile", tipoLog.STARTUP);
}
/// <summary>
/// scrive su log un dump di diagnostica
/// </summary>
/// <param name="testoLog">Causale diagnostica</param>
/// <param name="pingTargets">target per test PING</param>
/// <param name="wwwTargets">target x download www page</param>
public void scriviDiagnostica(string testoLog, string[] pingTargets, string[] wwwTargets)
{
string txtDiag = "";
try
{
scriviLog(string.Format("[{0}]{1}{2}", tipoLog.DUMP_DIAGN, Environment.NewLine, SteamwareStrings.charLine('+', 80)));
scriviLog(string.Format("[{0}]{1}{2}", tipoLog.DUMP_DIAGN, Environment.NewLine, SteamwareStrings.charLine('+', 80)));
scriviLog(string.Format("[{0}] - {1}{2}", tipoLog.DUMP_DIAGN, testoLog, Environment.NewLine));
}
catch
{ }
try
{
scriviLog(string.Format("[{0}]{1}{2}", tipoLog.DUMP_DIAGN, Environment.NewLine, formDiagBlock("UPTIME", Diagnostica.uptime)));
}
catch
{ }
try
{
scriviLog(string.Format("[{0}]{1}{2}", tipoLog.DUMP_DIAGN, Environment.NewLine, formDiagBlock("STORAGE", Diagnostica.diskUsage)));
}
catch
{ }
try
{
scriviLog(string.Format("[{0}]{1}{2}", tipoLog.DUMP_DIAGN, Environment.NewLine, formDiagBlock("USB", Diagnostica.usbDevices)));
}
catch
{ }
try
{
scriviLog(string.Format("[{0}]{1}{2}", tipoLog.DUMP_DIAGN, Environment.NewLine, formDiagBlock("SERIAL", Diagnostica.serialPorts)));
}
catch
{ }
try
{
scriviLog(string.Format("[{0}]{1}{2}", tipoLog.DUMP_DIAGN, Environment.NewLine, formDiagBlock("NETWORKING (interfaces)", Diagnostica.networkInterfaces)));
}
catch
{ }
try
{
// se richiesto faccio PING test
if (pingTargets.Length > 0)
{
txtDiag = "";
foreach (string target in pingTargets)
{
txtDiag += SteamwareStrings.addLine(Diagnostica.pingIp(target));
}
scriviLog(string.Format("[{0}]{1}{2}", tipoLog.DUMP_DIAGN, Environment.NewLine, formDiagBlock("NETWORKING (ping)", txtDiag)));
}
}
catch
{ }
try
{
// se richiesto faccio PING test
if (wwwTargets.Length > 0)
{
txtDiag = "";
foreach (string target in wwwTargets)
{
txtDiag += SteamwareStrings.addLine(string.Format("WebPage Test ({2}): {0}{1}", Environment.NewLine, Diagnostica.getPageContent(target), target));
}
scriviLog(string.Format("[{0}]{1}{2}", tipoLog.DUMP_DIAGN, Environment.NewLine, formDiagBlock("NETWORKING (www)", txtDiag)));
}
}
catch
{ }
// chiudo
scriviLog(string.Format("[{0}]{1}{2}", tipoLog.DUMP_DIAGN, Environment.NewLine, SteamwareStrings.charLine('-', 80)));
scriviLog(string.Format("[{0}]{1}{2}", tipoLog.DUMP_DIAGN, Environment.NewLine, SteamwareStrings.charLine('-', 80)));
}
/// <summary>
/// scrive sul file log di default il valore della variabile string passata su una riga... (tab delim?!?)
/// </summary>
/// <param name="topic">TOPIC del log</param>
/// <param name="fullMessage">Contenuto del log</param>
/// <returns></returns>
public bool scriviLog(string topic, string fullMessage)
{
bool needWrite = false;
bool fatto = false;
// preparo hash redis
string hKey = topic.Replace(":", "_").Replace("/", "_").Replace("#", "_").Replace("(", "").Replace(")", "").Replace("|", "_").Replace(" ", "_").Replace("__", "_").Replace("__", "_").Replace("__", "_").Replace("__", "_");
//se troppo lunga trimmo...
if (hKey.Length > 100)
{
hKey = hKey.Substring(0, 100);
}
string hVetoErrore = memLayer.ML.redHash("Logger:Veto:" + hKey);
string hCountErrore = memLayer.ML.redHash("Logger:Counter:" + hKey);
bool redisEnabled = memLayer.ML.confReadBool("cacheOnRedis");
// verifico mitigazione
int logMitigSec = 30;
try
{
if (memLayer.ML.confReadString("logMitigSec") != "")
{
logMitigSec = memLayer.ML.confReadInt("logMitigSec");
}
}
catch
{ }
// verifico SE HO redis (in quel caso gli errori li loggo 1 volta poi metto un VETO ed un counter)
if (redisEnabled)
{
// cerco se ho un veto precedente in redis
string vetoPar = memLayer.ML.getRSV(hVetoErrore);
if (!string.IsNullOrEmpty(vetoPar))
{
needWrite = false;
}
else
{
// metto veto per TTL default... (durata std = 30 sec)
memLayer.ML.setRSV(hVetoErrore, DateTime.UtcNow.ToString(), logMitigSec);
// abilito log...
needWrite = true;
}
memLayer.ML.setRCntI(hCountErrore);
// controllo eventuali messaggi vecchi da "scodare" dal log redis
purgeOldVeto();
}
else
{
// altrimenti log direttamente
needWrite = true;
}
// se devo DAVVERO scrivere
if (needWrite)
{
if (redisEnabled)
{
int numRep = memLayer.ML.getRCnt(hCountErrore);
if (numRep > 1)
{
// cambio messaggio con un inizio pari al num di ripetizioni...
fullMessage = string.Format("{0} x {1}", numRep, fullMessage);
}
// reset counter
memLayer.ML.resetRCnt(hCountErrore);
}
fatto = doScriviLog(fullMessage);
}
return fatto;
}
/// <summary>
/// scrive sul file log di default il valore della variabile string passata su una riga... (tab delim?!?)
/// </summary>
/// <param name="fullMessage">testo iniziale del log</param>
/// <returns></returns>
public bool scriviLog(string fullMessage)
{
return scriviLog(fullMessage, fullMessage);
}
/// <summary>
/// scrive un messaggio di log con etichetta pre
/// </summary>
/// <param name="fullMessage">testo messaggio</param>
/// <param name="tipo">tipo di log da registrare (etichetta [...])</param>
/// <returns></returns>
public bool scriviLog(string fullMessage, tipoLog tipo)
{
bool answ = false;
answ = scriviLog(string.Format("[{0}] - {1}", tipo, fullMessage));
// se è un tipo EXCEPTION allora scrivo anche log diagnostico
if (tipo == tipoLog.EXCEPTION && enableDumpDiag)
{
try
{
string[] pingTagets = SteamWare.StringSplitter.CSplitter.Split(memLayer.ML.CRS("pingTargets"), "#", true, -1, SteamWare.StringSplitter.ComparisonMethod.Text);
string[] wwwTagets = SteamWare.StringSplitter.CSplitter.Split(memLayer.ML.CRS("wwwTargets"), "#", true, -1, SteamWare.StringSplitter.ComparisonMethod.Text);
// chiamo scrittura diagnostica
scriviDiagnostica("DUMP diagnostico causa Eccezione", pingTagets, wwwTagets);
}
catch
{ }
}
return answ;
}
/// <summary>
/// scrive un messaggio di log con etichetta pre
/// </summary>
/// <param name="topic">topic messaggio</param>
/// <param name="fullMessage">testo messaggio</param>
/// <param name="tipo">tipo di log da registrare (etichetta [...])</param>
/// <returns></returns>
public bool scriviLog(string topic, string fullMessage, tipoLog tipo)
{
bool answ = false;
answ = scriviLog($"{tipo}:{topic}", $"[{tipo}] - {fullMessage}");
// se è un tipo EXCEPTION allora scrivo anche log diagnostico
if (tipo == tipoLog.EXCEPTION && enableDumpDiag)
{
try
{
string[] pingTagets = SteamWare.StringSplitter.CSplitter.Split(memLayer.ML.CRS("pingTargets"), "#", true, -1, SteamWare.StringSplitter.ComparisonMethod.Text);
string[] wwwTagets = SteamWare.StringSplitter.CSplitter.Split(memLayer.ML.CRS("wwwTargets"), "#", true, -1, SteamWare.StringSplitter.ComparisonMethod.Text);
// chiamo scrittura diagnostica
scriviDiagnostica("DUMP diagnostico causa Eccezione", pingTagets, wwwTagets);
}
catch
{ }
}
return answ;
}
/// <summary>
/// Esecuzione scrittura ThreadSafe
/// </summary>
/// <param name="text2write"></param>
/// <param name="logPath"></param>
public bool WriteToFileThreadSafe(string logPath, string text2write)
{
bool answ = false;
// Set Status to Locked
_readWriteLock.EnterWriteLock();
try
{
// Append text to the file
using (StreamWriter sw = File.AppendText(logPath))
{
sw.WriteLine(text2write);
sw.Close();
answ = true;
}
}
finally
{
// Release lock
_readWriteLock.ExitWriteLock();
}
return answ;
}
#endregion metodi esposti
#region metodi privati
private void compressAndRemove(FileInfo[] _fis)
{
foreach (FileInfo _file in _fis)
{
if (_file.CreationTime < DateTime.Now.AddDays(-2)) // zippo files + vecchi di 2 gg...
{
fileMover.obj.zippaSingoloFile(_file);
// cancello l'originale...
fileMover.obj.eliminaFile(_file);
}
}
// verifico directory e dimensione...
while (fileMover.obj.totalMb() > _logMaxMb)
{
// cancello i + vecchi fino a rientrare alla dimensione max...
fileMover.obj.deleteOldest();
}
}
/// <summary>
/// fornisce il file + vecchio
/// </summary>
/// <param name="_di"></param>
/// <returns></returns>
protected void deleteOldest(DirectoryInfo _di)
{
FileInfo[] _fis = _di.GetFiles();
DateTime _oldest = DateTime.Now;
string _nome = "";
foreach (FileInfo _file in _fis)
{
if (_file.CreationTime < _oldest)
{
_nome = _file.Name;
}
}
FileInfo fi = new FileInfo(_nome);
fi.Delete();
}
/// <summary>
/// fornisce il nome del file in cui loggare (ed eventualmente crea...)
/// </summary>
protected void newLogfileName()
{
DateTime CurrentDateTime = DateTime.Now;
_logfileName = _logBaseDir + String.Format("{0}.log", CurrentDateTime.ToString("yyyy-MM-dd"));
}
/// <summary>
/// provvede a verificare la dim della cartella dei log e cancella i + vecchi fino a restare a dim inferiori a _logMaxMb
/// </summary>
protected void shrinkDir()
{
// ottengo elenco files *.log
fileMover.obj.setDirectory(_logBaseDir);
FileInfo[] _fis = fileMover.obj.elencoFiles_FI("*.log");
compressAndRemove(_fis);
// acnhe per i "Vecchi" formati .txt
_fis = fileMover.obj.elencoFiles_FI("*.txt");
compressAndRemove(_fis);
}
#endregion metodi privati
}
}