Aggiunta progetto logger (iniziale) come nuovo nuget

This commit is contained in:
Samuele E. Locatelli
2020-02-20 15:46:04 +01:00
parent a5031d373d
commit 95d758a92d
12 changed files with 4592 additions and 1 deletions
Vendored
+12 -1
View File
@@ -7,7 +7,7 @@ pipeline {
steps {
/* calcolo numero versione... diverso x branch MASTER/DEVELOP */
script {
withEnv(['NEXT_BUILD_NUMBER=723']) {
withEnv(['NEXT_BUILD_NUMBER=724']) {
// env.versionNumber = VersionNumber(versionNumberString : '3.5.${BUILD_DATE_FORMATTED, "yyMM"}.${BUILDS_ALL_TIME}', projectStartDate : '2006-01-01', skipFailedBuilds: true)
env.versionNumber = VersionNumber(versionNumberString : '3.5.${BUILD_DATE_FORMATTED, "yyMM"}.${BUILDS_ALL_TIME}', projectStartDate : '2006-01-01', skipFailedBuilds: true, overrideBuildsAllTime: '${NEXT_BUILD_NUMBER}')
env.versionNumberBeta = VersionNumber(versionNumberString : '3.5.${BUILD_DATE_FORMATTED, "yyMM"}-beta.${BUILDS_ALL_TIME}', projectStartDate : '2006-01-01', skipFailedBuilds: true, overrideBuildsAllTime: '${NEXT_BUILD_NUMBER}')
@@ -42,6 +42,10 @@ pipeline {
// Reports lib
bat "\"${tool 'MSBuild-15.0'}\" SteamWare.Reports\\SteamWare.Reports.csproj -target:Build /p:Configuration=Release /p:Platform=\"Any CPU\" /p:OutputPath=bin/ /m"
},
LOGGER: {
// Reports lib
bat "\"${tool 'MSBuild-15.0'}\" SteamWare.Logger\\SteamWare.Logger.csproj -target:Build /p:Configuration=Release /p:Platform=\"Any CPU\" /p:OutputPath=bin/ /m"
},
failFast: false)
}
}
@@ -86,6 +90,12 @@ pipeline {
// creo package NuGet... con version in modo da fare ANCHE le beta
bat "e:\\nuget.exe pack ${WORKSPACE}\\SteamWare.Reports\\SteamWare.Reports.csproj -properties Configuration=${env.config} -Version ${env.packVers}"
},
LOGGER: {
// BUILD Reports lib!
bat "\"${tool 'MSBuild-16.0'}\" SteamWare.Logger\\SteamWare.Logger.csproj -target:Build /p:Configuration=${env.config} /p:Platform=\"Any CPU\" /p:OutputPath=bin/${env.config} /m"
// creo package NuGet... con version in modo da fare ANCHE le beta
bat "e:\\nuget.exe pack ${WORKSPACE}\\SteamWare.Logger\\SteamWare.Logger.csproj -properties Configuration=${env.config} -Version ${env.packVers}"
},
failFast: false)
}
else
@@ -103,6 +113,7 @@ pipeline {
// bat "e:\\nuget.exe push SteamWare.${env.versionNumberBeta}.nupkg -Source http://nexus.steamware.net/repository/nuget-hosted"
bat "e:\\nuget.exe push SteamWare.${env.packVers}.nupkg -Source http://nexus.steamware.net/repository/nuget-hosted"
bat "e:\\nuget.exe push SteamWare.Reports.${env.packVers}.nupkg -Source http://nexus.steamware.net/repository/nuget-hosted"
bat "e:\\nuget.exe push SteamWare.Logger.${env.packVers}.nupkg -Source http://nexus.steamware.net/repository/nuget-hosted"
}
}
}
+37
View File
@@ -0,0 +1,37 @@
using NLog;
using NLog.Config;
using NLog.Targets;
namespace SteamWare.Log
{
/// <summary>
/// Classe helper x LOG basata su NLog
/// </summary>
public static class Log
{
/// <summary>
/// S
/// </summary>
public static Logger Instance { get; private set; }
static Log()
{
#if DEBUG
// Setup the logging view for Sentinel - http://sentinel.codeplex.com
var sentinalTarget = new NLogViewerTarget()
{
Name = "sentinal",
Address = "udp://127.0.0.1:9999",
IncludeNLogData = false
};
var sentinalRule = new LoggingRule("*", LogLevel.Trace, sentinalTarget);
LogManager.Configuration.AddTarget("sentinal", sentinalTarget);
LogManager.Configuration.LoggingRules.Add(sentinalRule);
#endif
LogManager.ReconfigExistingLoggers();
Instance = LogManager.GetCurrentClassLogger();
}
}
}
+34
View File
@@ -0,0 +1,34 @@
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
autoReload="true"
throwExceptions="false"
internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">
<!-- optional, add some variables
https://github.com/nlog/NLog/wiki/Configuration-file#variables
-->
<variable name="myvar" value="myvalue"/>
<!--
See https://github.com/nlog/nlog/wiki/Configuration-file
for information on customizing logging rules and outputs.
-->
<targets>
<!--
add your targets here
See https://github.com/nlog/NLog/wiki/Targets for possible targets.
See https://github.com/nlog/NLog/wiki/Layout-Renderers for the possible layout renderers.
-->
<!-- Write events to a file with the date in the filename. -->
<target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
layout="${longdate} ${uppercase:${level}} ${message}" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="f" />
</rules>
</nlog>
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Le informazioni generali relative a un assembly sono controllate dal seguente
// set di attributi. Modificare i valori di questi attributi per modificare le informazioni
// associate a un assembly.
[assembly: AssemblyTitle("SteamWare.Logger")]
[assembly: AssemblyDescription("Classi utility Logging by Steamware")]
[assembly: AssemblyConfiguration("")]
// [assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SteamWare.Logger")]
// [assembly: AssemblyCopyright("Copyright © 2020")]
[assembly: AssemblyTrademark("SteamWare")]
[assembly: AssemblyCulture("")]
// Se si imposta ComVisible su false, i tipi in questo assembly non saranno visibili
// ai componenti COM. Se è necessario accedere a un tipo in questo assembly da
// COM, impostare su true l'attributo ComVisible per tale tipo.
[assembly: ComVisible(false)]
// Se il progetto viene esposto a COM, il GUID seguente verrà utilizzato come ID della libreria dei tipi
[assembly: Guid("97a9f482-c173-4f0f-9f8f-7bb41c59cdd6")]
// Le informazioni sulla versione di un assembly sono costituite dai seguenti quattro valori:
//
// Versione principale
// Versione secondaria
// Numero di build
// Revisione
//
// È possibile specificare tutti i valori oppure impostare valori predefiniti per i numeri relativi alla revisione e alla build
// usando l'asterisco '*' come illustrato di seguito:
// [assembly: AssemblyVersion("1.0.*")]
//[assembly: AssemblyVersion("1.0.0.0")]
//[assembly: AssemblyFileVersion("1.0.0.0")]
+71
View File
@@ -0,0 +1,71 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{97A9F482-C173-4F0F-9F8F-7BB41C59CDD6}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>SteamWare.Log</RootNamespace>
<AssemblyName>SteamWare.Log</AssemblyName>
<TargetFrameworkVersion>v4.6.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="NLog, Version=4.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c, processorArchitecture=MSIL">
<HintPath>..\packages\NLog.4.6.8\lib\net45\NLog.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Configuration" />
<Reference Include="System.Core" />
<Reference Include="System.IO.Compression" />
<Reference Include="System.Runtime.Serialization" />
<Reference Include="System.ServiceModel" />
<Reference Include="System.Transactions" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\SteamWareLib\SteamWare.cs">
<Link>SteamWare.cs</Link>
</Compile>
<Compile Include="Logging.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<Content Include="NLog.config">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<None Include="logs\.placeholder">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="NLog.xsd">
<SubType>Designer</SubType>
</None>
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
+316
View File
@@ -0,0 +1,316 @@
using System;
namespace SteamWare.Log
{
/// <summary>
/// classe gestione logging esteso di eventi e note utente (correlabili)
/// </summary>
public class log2note
{
#region area protected
/// <summary>
/// TableAdapter di accesso alla tabella anagrafica filtraggi
/// </summary>
protected DS_loggingTableAdapters.T_anagFiltroTableAdapter taAnagFilt;
/// <summary>
/// TableAdapter di accesso alla tabella anagrafica record
/// </summary>
protected DS_loggingTableAdapters.T_anagRecordTableAdapter taAnagRec;
/// <summary>
/// TableAdapter di accesso alla tabella logging record di eventi
/// </summary>
protected DS_loggingTableAdapters.T_logRecordsTableAdapter taLogRec;
/// <summary>
/// TableAdapter di accesso alla tabella logging utente
/// </summary>
protected DS_loggingTableAdapters.T_logUtenteTableAdapter taLogUt;
/// <summary>
/// TableAdapter di accesso alla vista logging eventi
/// </summary>
public DS_loggingTableAdapters.v_logRecordsTableAdapter ta_vLogRec;
/// <summary>
/// TableAdapter di accesso alla vista logging utente
/// </summary>
public DS_loggingTableAdapters.v_logUtenteTableAdapter ta_vLogUt;
/// <summary>
/// effettua setup dei connection strings da web.config delal singola applicazione
/// </summary>
protected void setupConnectionString()
{
// cambio le connString
string _connectionString = memLayer.ML.confReadString("LoggingConnectionString");
taAnagFilt.Connection.ConnectionString = _connectionString;
taAnagRec.Connection.ConnectionString = _connectionString;
taLogRec.Connection.ConnectionString = _connectionString;
taLogUt.Connection.ConnectionString = _connectionString;
ta_vLogUt.Connection.ConnectionString = _connectionString;
ta_vLogRec.Connection.ConnectionString = _connectionString;
}
/// <summary>
/// avvio i tari tableAdapters
/// </summary>
private void setupTA()
{
taAnagFilt = new DS_loggingTableAdapters.T_anagFiltroTableAdapter();
taAnagRec = new DS_loggingTableAdapters.T_anagRecordTableAdapter();
taLogRec = new DS_loggingTableAdapters.T_logRecordsTableAdapter();
taLogUt = new DS_loggingTableAdapters.T_logUtenteTableAdapter();
ta_vLogRec = new DS_loggingTableAdapters.v_logRecordsTableAdapter();
ta_vLogUt = new DS_loggingTableAdapters.v_logUtenteTableAdapter();
}
/// <summary>
/// avvio della classe istanziando db e
/// </summary>
log2note()
{
setupTA();
setupConnectionString();
}
#endregion
#region area public
/// <summary>
/// oggetto statico di accesso ai metodi della classe...
/// </summary>
public static log2note l2n = new log2note();
#region area oggetti restituiti
/// <summary>
/// tabella eventi
/// </summary>
/// <returns></returns>
public DS_logging.v_logRecordsDataTable tabLogEventi()
{
return ta_vLogRec.GetData();
}
/// <summary>
/// tabella note
/// </summary>
/// <returns></returns>
public DS_logging.v_logUtenteDataTable tabLogNote()
{
return ta_vLogUt.GetData();
}
/// <summary>
/// tabella eventi secondo filtro
/// </summary>
/// <param name="filtro">filtro gestito come condizione "LIKE '%{0}%'" rispetto al filtro salvato con l'evento</param>
/// <returns></returns>
public DS_logging.v_logRecordsDataTable tabLogEventi(string filtro)
{
return ta_vLogRec.getByFiltro(filtro);
}
/// <summary>
/// tabella note secondo filtro
/// </summary>
/// <param name="filtro">filtro gestito come condizione "LIKE '%{0}%'" rispetto al filtro salvato con l'evento</param>
/// <returns></returns>
public DS_logging.v_logUtenteDataTable tabLogNote(string filtro)
{
return ta_vLogUt.getByFiltro(filtro);
}
/// <summary>
/// tabella eventi secondo filtro e condizione ulteriore WHERE esplicitata
/// </summary>
/// <param name="filtro">filtro gestito come condizione "LIKE '%{0}%'" rispetto al filtro salvato con l'evento</param>
/// <param name="_where">ulteriore condizione WHERE per filtrare i dati (testo {0} della condizione "WHERE {0}" </param>
/// <returns></returns>
public DS_logging.v_logRecordsDataTable tabLogEventi(string filtro, string _where)
{
DS_logging.v_logRecordsDataTable _tab = new DS_logging.v_logRecordsDataTable();
foreach (DS_logging.v_logRecordsRow riga in ta_vLogRec.getByFiltro(filtro).Select(_where))
{
_tab.Addv_logRecordsRow(riga);
}
return _tab;
}
/// <summary>
/// tabella note secondo filtro e condizione ulteriore WHERE esplicitata
/// </summary>
/// <param name="filtro">filtro gestito come condizione "LIKE '%{0}%'" rispetto al filtro salvato con l'evento</param>
/// <param name="_where">ulteriore condizione WHERE per filtrare i dati (testo {0} della condizione "WHERE {0}" </param>
/// <returns></returns>
public DS_logging.v_logUtenteDataTable tabLogNote(string filtro, string _where)
{
DS_logging.v_logUtenteDataTable _tab = new DS_logging.v_logUtenteDataTable();
foreach (DS_logging.v_logUtenteRow riga in ta_vLogUt.getByFiltro(filtro).Select(_where))
{
_tab.Addv_logUtenteRow(riga);
}
return _tab;
}
/// <summary>
/// tabella note secondo filtro
/// </summary>
/// <param name="filtro">filtro gestito come condizione "LIKE '%{0}%'" rispetto al filtro salvato con l'evento</param>
/// <returns></returns>
public DS_logging.T_logUtenteDataTable tabLogUt(string filtro)
{
return taLogUt.getByFiltro(filtro);
}
#endregion
#region area insert valori
/// <summary>
/// inserisce l'evento indicato dai parametri
/// </summary>
/// <param name="_userEv">user che ha generato l'evento</param>
/// <param name="_pagina">pagina/form applicaizone in cui l'evento si è generato</param>
/// <param name="_valOrig">valore originale(se c'è)</param>
/// <param name="_valNew">valore nuovo/modificato</param>
/// <param name="_evento">descrizione evento (poi gestita con anagrafica interna)</param>
/// <param name="_filtro">filtro logico evento (poi gestita con anagrafica interna)</param>
public void insEvento(string _userEv, string _pagina, string _valOrig, string _valNew, string _evento, string _filtro)
{
taLogRec.sp_insRecFull(_userEv, _pagina, _valOrig, _valNew, _evento, _filtro);
}
/// <summary>
/// inserisce la nota utente indicata dai parametri, restituisce idx della nota creata...
/// </summary>
/// <param name="_userNota">user che ha inserito la nota</param>
/// <param name="_nota">testo della nota</param>
/// <param name="_val">valore ulteriore da associare alla nota (es: label, codice, versione, ...)</param>
/// <param name="_filtro">filtro logico evento (poi gestita con anagrafica interna)</param>
/// <returns>intero dell'idx della nota creata</returns>
public int insNota(string _userNota, string _nota, string _val, string _filtro)
{
int? answ = 0;
taLogUt.sp_insLogUtFull(_userNota, _nota, _val, _filtro, ref answ);
return (int)answ;
}
#endregion
#region area gestione eventi (cestina, delete, associazione a note,...)
/// <summary>
/// associa l'evento e la nota indicati
/// </summary>
/// <param name="idxRecord">idx del record da associare</param>
/// <param name="_idxNota">idx chiave della nota da associare</param>
public void associaEvento2Nota(int idxRecord, int _idxNota)
{
taLogRec.sp_setRec2nota(idxRecord, _idxNota);
}
/// <summary>
/// associa l'ultimo evento del filtro indicato alla nota
/// </summary>
/// <param name="filtro">filtro associato all'ultimo evento...</param>
/// <param name="_idxNota">idx chiave della nota da associare</param>
public void associaLastEvento2Nota(string filtro, int _idxNota)
{
taLogRec.sp_setLastRec2nota(filtro, _idxNota);
}
/// <summary>
/// segna come cestinati tutti gli eventi dell'utente indicato non ancora associati o cestinati
/// </summary>
/// <param name="_userEv">utente generatore dell'evento</param>
public void cestinaEventiUser(string _userEv)
{
taLogRec.sp_cestinaLogRecUt(_userEv);
}
/// <summary>
/// segna come cestinati tutti gli eventi dell'utente indicato non ancora associati o cestinati
/// </summary>
/// <param name="_filtro">utente generatore dell'evento</param>
public void cestinaEventiFiltro(string _filtro)
{
taLogRec.sp_cestinaLogRecFiltro(_filtro);
}
/// <summary>
/// Elimina gli eventi cestinati generati dall'utente indicato
/// </summary>
/// <param name="_userEv">utente generatore dell'evento</param>
public void eliminaEventiDaUser(string _userEv)
{
taLogRec.sp_deleteLogUser(_userEv);
}
/// <summary>
/// Elimina gli eventi cestinati anteriori alla data selezionata
/// </summary>
/// <param name="_dataOra">dataOra dell'evento</param>
public void associaEvento2Nota(DateTime _dataOra)
{
taLogRec.sp_deleteLogMaxData(_dataOra);
}
/// <summary>
/// effettua la registrazione dell'evento in session
/// </summary>
public void registraEventi(string _userEv, string _pagina)
{
// controllo: loggin SOLO se la scheda ha logging abilitato nella riga del db...
bool logEn = memLayer.ML.BoolSessionObj("logEn");
memLayer.ML.emptySessionVal("logEn");
if (logEn)
{
// leggo e svuoto info x logging
string ev2log = memLayer.ML.StringSessionObj("ev2log");
memLayer.ML.emptySessionVal("ev2log");
string valOrig = memLayer.ML.StringSessionObj("valOrig");
memLayer.ML.emptySessionVal("valOrig");
string valNew = memLayer.ML.StringSessionObj("valNew");
memLayer.ML.emptySessionVal("valNew");
string filtEv = memLayer.ML.StringSessionObj("filtEv");
memLayer.ML.emptySessionVal("filtEv");
// effettuo logging evento
l2n.insEvento(_userEv, _pagina, valOrig, valNew, ev2log, filtEv);
}
}
#endregion
#endregion
}
/// <summary>
/// metodo di comportamento del controllo di logging
/// </summary>
public enum logControlMode
{
/// <summary>
/// nasconde pannello log
/// </summary>
hideLog,
/// <summary>
/// memorizza log inserito
/// </summary>
recordLog,
/// <summary>
/// mostra pannello log
/// </summary>
showLog
}
/// <summary>
/// metodo di comportamento del controllo di logging
/// </summary>
public enum tipoApprovazione
{
/// <summary>
/// indica il primo step del doppio livello di approvazione (completamento)
/// </summary>
completamento,
/// <summary>
/// SOLO con incremento indice di revisione dell'oggetto approvato
/// </summary>
revisione,
/// <summary>
/// SOLO mantenendo indice di revisione corrente
/// </summary>
semplice,
/// <summary>
/// permette SIA con revisione che senza (e anche rev -1)
/// </summary>
tutto
}
}
+500
View File
@@ -0,0 +1,500 @@
using System;
using System.IO;
using System.Threading;
namespace SteamWare.Log
{
/// <summary>
/// classe gesione log files applicazioni
/// </summary>
public class logger
{
#region dichiarazione variabili
/// <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>
/// controlla se si debba mantenere sotto controllo la dimensioen della cartella logs
/// </summary>
protected bool _doShrinkFolder;
/// <summary>
/// Ultima verifica directory (x shrink)
/// </summary>
private static DateTime lastDirCheck;
/// <summary>
/// metodo gestione wirteLock su file log
/// </summary>
private static ReaderWriterLockSlim _readWriteLock = new ReaderWriterLockSlim();
/// <summary>
/// Indica se sia abilitato log diagnostico esteso...
/// </summary>
protected bool enableDumpDiag = false;
#endregion
#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 = SteamwareStrings.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;
}
// all'avvio imposto ultimo check a 23 ore fa... così farà shrink DOPO 1 h da avvio
lastDirCheck = DateTime.Now.AddHours(-23);
}
/// <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>
/// 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>
/// resetta il logfile odierno
/// </summary>
public void resetLogFile()
{
newLogfileName();
FileInfo fi = new FileInfo(_logfileName);
fi.Delete();
scriviLog("ResetFile", tipoLog.STARTUP);
}
/// <summary>
/// scrive sul file log di default il valore della variabile string passata su una riga... (tab delim?!?)
/// </summary>
/// <param name="_testoPre">testo iniziale del log</param>
/// <returns></returns>
public bool scriviLog(string _testoPre)
{
bool needWrite = false;
bool fatto = false;
// preparo hash redis
string hKey = _testoPre.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 (vetoPar != null && 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);
}
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...
_testoPre = string.Format("{0} x {1}", numRep, _testoPre);
}
// reset counter
memLayer.ML.resetRCnt(hCountErrore);
}
fatto = doScriviLog(_testoPre);
}
return fatto;
}
/// <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>
/// 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;
}
/// <summary>
/// scrive un messaggio di log con etichetta pre
/// </summary>
/// <param name="testoLog">testo messaggio</param>
/// <param name="tipo">tipo di log da registrare (etichetta [...])</param>
/// <returns></returns>
public bool scriviLog(string testoLog, tipoLog tipo)
{
bool answ = false;
answ = scriviLog(string.Format("[{0}] - {1}", tipo, testoLog));
// 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 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>
/// 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;
}
#endregion
#region metodi privati
/// <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("yyyyMMdd"));
}
/// <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);
}
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();
}
#endregion
}
/// <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
}
}
+1
View File
@@ -0,0 +1 @@

+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="NLog" version="4.6.8" targetFramework="net462" />
<package id="NLog.Config" version="4.6.8" targetFramework="net462" />
<package id="NLog.Schema" version="4.6.8" targetFramework="net462" />
</packages>
@@ -32,7 +32,12 @@
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Configuration" />
<Reference Include="System.Core" />
<Reference Include="System.IO.Compression" />
<Reference Include="System.Runtime.Serialization" />
<Reference Include="System.ServiceModel" />
<Reference Include="System.Transactions" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
@@ -41,9 +46,13 @@
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="..\SteamWareLib\SteamWare.cs">
<Link>SteamWare.cs</Link>
</Compile>
<Compile Include="devInfoParam.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="reportGenObj.cs" />
</ItemGroup>
<ItemGroup />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
+14
View File
@@ -9,6 +9,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestBench", "TestBench\Test
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SteamWare.Reports", "SteamWare.Reports\SteamWare.Reports.csproj", "{1792D70C-D854-415B-ACF1-76BBCB8AC6FE}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SteamWare.Logger", "..\..\..\VisualStudioProject\SteamWare\SteamWare.Logger\SteamWare.Logger.csproj", "{97A9F482-C173-4F0F-9F8F-7BB41C59CDD6}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|.NET = Debug|.NET
@@ -53,6 +55,18 @@ Global
{1792D70C-D854-415B-ACF1-76BBCB8AC6FE}.Release|Any CPU.Build.0 = Release|Any CPU
{1792D70C-D854-415B-ACF1-76BBCB8AC6FE}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{1792D70C-D854-415B-ACF1-76BBCB8AC6FE}.Release|Mixed Platforms.Build.0 = Release|Any CPU
{97A9F482-C173-4F0F-9F8F-7BB41C59CDD6}.Debug|.NET.ActiveCfg = Debug|Any CPU
{97A9F482-C173-4F0F-9F8F-7BB41C59CDD6}.Debug|.NET.Build.0 = Debug|Any CPU
{97A9F482-C173-4F0F-9F8F-7BB41C59CDD6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{97A9F482-C173-4F0F-9F8F-7BB41C59CDD6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{97A9F482-C173-4F0F-9F8F-7BB41C59CDD6}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU
{97A9F482-C173-4F0F-9F8F-7BB41C59CDD6}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU
{97A9F482-C173-4F0F-9F8F-7BB41C59CDD6}.Release|.NET.ActiveCfg = Release|Any CPU
{97A9F482-C173-4F0F-9F8F-7BB41C59CDD6}.Release|.NET.Build.0 = Release|Any CPU
{97A9F482-C173-4F0F-9F8F-7BB41C59CDD6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{97A9F482-C173-4F0F-9F8F-7BB41C59CDD6}.Release|Any CPU.Build.0 = Release|Any CPU
{97A9F482-C173-4F0F-9F8F-7BB41C59CDD6}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU
{97A9F482-C173-4F0F-9F8F-7BB41C59CDD6}.Release|Mixed Platforms.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE