new logging system

This commit is contained in:
Timerix22 2022-11-17 18:27:43 +06:00
parent 20f2c7c7e7
commit a94dd76799
15 changed files with 281 additions and 5 deletions

View File

@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net6.0;net48</TargetFrameworks>
<LangVersion>10</LangVersion>
<ImplicitUsings>disable</ImplicitUsings>
<Nullable>disable</Nullable>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<DebugType>embedded</DebugType>
<ProduceReferenceAssembly>False</ProduceReferenceAssembly>
<Configurations>Debug;Release</Configurations>
<Platforms>AnyCPU;x64;x86;arm64</Platforms>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\DTLib\DTLib.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="6.0.3" />
</ItemGroup>
</Project>

11
DTLib.Logging/Global.cs Normal file
View File

@ -0,0 +1,11 @@
global using System;
global using System.Collections;
global using System.Collections.Generic;
global using System.Linq;
global using System.Text;
global using System.Threading.Tasks;
global using DTLib.Extensions;
global using DTLib.Filesystem;
namespace DTLib.Logging.New;

View File

@ -0,0 +1,28 @@
namespace DTLib.Logging.New;
public class DefaultLogFormat : ILogFormat
{
public bool PrintTimeStamp { get; set; }
public bool PrintContext { get; set; }
public bool PrintSeverity { get; set; }
public DefaultLogFormat(bool printTimeStamp = false, bool printContext = true, bool printSeverity = true)
{
PrintTimeStamp = printTimeStamp;
PrintContext = printContext;
PrintSeverity = printSeverity;
}
public string CreateMessage(string context, LogSeverity severity, object message)
{
var sb = new StringBuilder();
if (PrintTimeStamp) sb.Append('[').Append(DateTime.Now.ToString(MyTimeFormat.ForText)).Append(']');
if(PrintContext) sb.Append('[').Append(context).Append(']');
if(PrintSeverity) sb.Append('[').Append(severity.ToString()).Append(']');
if (sb.Length != 0) sb.Append(": ");
sb.Append(message.ToString());
sb.Append('\n');
return sb.ToString();
}
}

View File

@ -0,0 +1,10 @@
namespace DTLib.Logging.New;
public interface ILogFormat
{
bool PrintTimeStamp { get; set; }
bool PrintContext { get; set; }
bool PrintSeverity { get; set; }
string CreateMessage(string context, LogSeverity severity, object message);
}

View File

@ -0,0 +1,9 @@
namespace DTLib.Logging.New;
public enum LogSeverity
{
Debug=1,
Info=2,
Warn=4,
Error=8
}

View File

@ -0,0 +1,38 @@
namespace DTLib.Logging.New;
/// <summary>
/// This class can be used for unite many loggers into one
/// </summary>
public class CompositeLogger : ILogger
{
public ILogFormat Format { get; }
protected ILogger[] _loggers;
public CompositeLogger(ILogFormat format, params ILogger[] loggers)
{
Format = format;
_loggers = loggers;
}
public CompositeLogger(params ILogger[] loggers) : this(new DefaultLogFormat(), loggers)
{}
public void Log(string context, LogSeverity severity, object message, ILogFormat format)
{
for (int i = 0; i < _loggers.Length; i++)
_loggers[i].Log(context, severity, message, format);
}
public void Log(string context, LogSeverity severity, object message)
=> Log(context, severity, message, Format);
public void Dispose()
{
for (int i = 0; i < _loggers.Length; i++)
{
_loggers[i].Dispose();
}
}
}

View File

@ -0,0 +1,33 @@
namespace DTLib.Logging.New;
// вывод лога в консоль и файл
public class ConsoleLogger : ILogger
{
readonly object consolelocker = new();
public ILogFormat Format { get; }
public ConsoleLogger(ILogFormat format)
=> Format = format;
public ConsoleLogger() : this(new DefaultLogFormat())
{}
public void Log(string context, LogSeverity severity, object message, ILogFormat format)
{
var msg = format.CreateMessage(context, severity, message);
lock (consolelocker)
ColoredConsole.Write(msg);
}
public void Log(string context, LogSeverity severity, object message)
=> Log(context, severity, message, Format);
public void Dispose()
{
lock (consolelocker) {}
}
~ConsoleLogger() => Dispose();
}

View File

@ -0,0 +1,52 @@
namespace DTLib.Logging.New;
public class FileLogger : ILogger
{
public ILogFormat Format { get; }
public string LogfileName { get; protected set; }
public System.IO.FileStream LogfileStream { get; protected set; }
public FileLogger(string logfile, ILogFormat format)
{
Format = format;
LogfileName = logfile;
LogfileStream = File.OpenAppend(logfile);
}
public FileLogger(string logfile) : this(logfile, new DefaultLogFormat())
{}
public FileLogger(string dir, string programName, ILogFormat format)
: this($"{dir}{Путь.Разд}{programName}_{DateTime.Now.ToString(MyTimeFormat.ForFileNames)}.log", format)
{}
public FileLogger(string dir, string programName) : this(dir, programName, new DefaultLogFormat())
{}
public void Log(string context, LogSeverity severity, object message, ILogFormat format)
{
var msg = format.CreateMessage(context, severity, format).ToBytes(StringConverter.UTF8);
lock (LogfileStream)
{
LogfileStream.Write(msg);
LogfileStream.Flush();
}
}
public void Log(string context, LogSeverity severity, object message)
=> Log(context, severity, message, Format);
public virtual void Dispose()
{
try
{
LogfileStream?.Flush();
LogfileStream?.Close();
LogfileStream?.Dispose();
}
catch (ObjectDisposedException) { }
}
~FileLogger() => Dispose();
}

View File

@ -0,0 +1,9 @@
namespace DTLib.Logging.New;
public interface ILogger : IDisposable
{
ILogFormat Format { get; }
void Log(string context, LogSeverity severity, object message);
void Log(string context, LogSeverity severity, object message, ILogFormat format);
}

View File

@ -0,0 +1,18 @@
using Microsoft.Extensions.Logging;
namespace DTLib.Logging.New.Microsoft;
public class LoggerService<TCaller> : IServiceProvider
{
ILogger _logger;
public LoggerService(ILogger logger)
{
_logger = logger;
}
public object GetService(Type serviceType)
{
return new MyLoggerWrapper<TCaller>(_logger);
}
}

View File

@ -0,0 +1,38 @@
using Microsoft.Extensions.Logging;
namespace DTLib.Logging.New.Microsoft;
internal class MyLoggerWrapper<TCaller> : ILogger<TCaller>
{
private ILogger _logger;
public MyLoggerWrapper(ILogger logger)=>
_logger = logger;
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
string message = formatter(state, exception);
_logger.Log(nameof(TCaller), LogSeverity_FromLogLevel(logLevel), message);
}
private bool _isEnabled=true;
public bool IsEnabled(LogLevel logLevel) => _isEnabled;
public IDisposable BeginScope<TState>(TState state)
{
throw new NotImplementedException();
}
static LogSeverity LogSeverity_FromLogLevel(LogLevel l)
=> l switch
{
LogLevel.Trace => LogSeverity.Debug,
LogLevel.Debug => LogSeverity.Debug,
LogLevel.Information => LogSeverity.Info,
LogLevel.Warning => LogSeverity.Warn,
LogLevel.Error => LogSeverity.Error,
LogLevel.Critical => LogSeverity.Error,
LogLevel.None => throw new NotImplementedException("LogLevel.None is not supported"),
_ => throw new ArgumentOutOfRangeException(nameof(l), l, null)
}
;
}

View File

@ -21,6 +21,7 @@
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\DTLib.Logging\DTLib.Logging.csproj" />
<ProjectReference Include="..\DTLib.Network\DTLib.Network.csproj" />
<ProjectReference Include="..\DTLib.Dtsod\DTLib.Dtsod.csproj" />
<ProjectReference Include="..\DTLib\DTLib.csproj" />

View File

@ -8,7 +8,7 @@ global using DTLib;
global using DTLib.Extensions;
global using DTLib.Filesystem;
global using DTLib.Dtsod;
global using static DTLib.Logging.Tester;
global using static DTLib.Tests.TesterLog;
global using static DTLib.Tests.Program;
using DTLib.Logging;

View File

@ -1,9 +1,9 @@
using System.Diagnostics;
using System.Globalization;
using DTLib.Logging;
namespace DTLib.Logging;
namespace DTLib.Tests;
public static class Tester
public static class TesterLog
{
public static void LogOperationTime(string op_name, int repeats, Action operation)
{
@ -13,6 +13,6 @@ public static class Tester
operation();
clock.Stop();
double time=(double)(clock.ElapsedTicks)/Stopwatch.Frequency/repeats;
Log("y",$"operation ","b",op_name,"y"," lasted ","b",time.ToString(MyTimeFormat.ForText),"y"," seconds");
PublicLog.Log("y",$"operation ","b",op_name,"y"," lasted ","b",time.ToString(MyTimeFormat.ForText),"y"," seconds");
}
}

View File

@ -17,6 +17,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DTLib.Dtsod", "DTLib.Dtsod\
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DTLib.Network", "DTLib.Network\DTLib.Network.csproj", "{24B7D0A2-0462-424D-B3F5-29A6655FE472}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DTLib.Logging", "DTLib.Logging\DTLib.Logging.csproj", "{00B76172-32BB-4B72-9891-47FAEF63386C}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -39,6 +41,10 @@ Global
{24B7D0A2-0462-424D-B3F5-29A6655FE472}.Debug|Any CPU.Build.0 = Debug|Any CPU
{24B7D0A2-0462-424D-B3F5-29A6655FE472}.Release|Any CPU.ActiveCfg = Release|Any CPU
{24B7D0A2-0462-424D-B3F5-29A6655FE472}.Release|Any CPU.Build.0 = Release|Any CPU
{00B76172-32BB-4B72-9891-47FAEF63386C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{00B76172-32BB-4B72-9891-47FAEF63386C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{00B76172-32BB-4B72-9891-47FAEF63386C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{00B76172-32BB-4B72-9891-47FAEF63386C}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE