Merge pull request #1 from Timerix22/new_logging

New logging
This commit is contained in:
Timerix22 2022-11-18 02:46:18 +06:00 committed by GitHub
commit 717d428300
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
30 changed files with 464 additions and 114 deletions

3
.gitmodules vendored Normal file
View File

@ -0,0 +1,3 @@
[submodule "DTLib.Logging/Ben.Demystifier"]
path = DTLib.Logging/Ben.Demystifier
url = https://github.com/Timerix22/Ben.Demystifier.git

@ -0,0 +1 @@
Subproject commit f64d655f490602b5858baeed3572ea2a9b850013

View File

@ -0,0 +1,26 @@
<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>
<PackageReference Include="Microsoft.Extensions.Logging" Version="7.0.0" />
</ItemGroup>
<ItemGroup>
<Compile Remove="Ben.Demystifier\**" />
<None Remove="Ben.Demystifier\**" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\DTLib\DTLib.csproj" />
<ProjectReference Include="Ben.Demystifier\src\Ben.Demystifier\Ben.Demystifier.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,15 @@
using Microsoft.Extensions.DependencyInjection;
namespace DTLib.Logging.DependencyInjection;
public class LoggerService<TCaller> : ServiceDescriptor
{
DTLib.Logging.New.ILogger _logger;
public LoggerService(DTLib.Logging.New.ILogger logger) : base(
typeof(Microsoft.Extensions.Logging.ILogger<TCaller>),
new MyLoggerWrapper<TCaller>(logger))
{
_logger = logger;
}
}

View File

@ -0,0 +1,39 @@
using DTLib.Logging.New;
using Microsoft.Extensions.Logging;
namespace DTLib.Logging.DependencyInjection;
public class MyLoggerWrapper<TCaller> : Microsoft.Extensions.Logging.ILogger<TCaller>
{
public DTLib.Logging.New.ILogger Logger;
public MyLoggerWrapper(DTLib.Logging.New.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(typeof(TCaller).Name, 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)
}
;
}

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,34 @@
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 && PrintSeverity)
sb.Append('[').Append(context).Append('/').Append(severity.ToString()).Append(']');
else if(PrintContext)
sb.Append('[').Append(context).Append(']');
else 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,22 @@
namespace DTLib.Logging.New;
public enum LogSeverity
{
Debug,
Info,
Warn,
Error
}
internal static class LogSeverityHelper
{
public static bool CheckSeverity(this ILogger logger, LogSeverity severity)
=> severity switch
{
LogSeverity.Debug => logger.DebugLogEnabled,
LogSeverity.Info => logger.InfoLogEnabled,
LogSeverity.Warn => logger.WarnLogEnabled,
LogSeverity.Error => logger.ErrorLogenabled,
_ => throw new ArgumentOutOfRangeException(nameof(severity), severity, "unknown severity")
};
}

View File

@ -0,0 +1,42 @@
namespace DTLib.Logging.New;
/// <summary>
/// This class can be used for unite many loggers into one
/// </summary>
public class CompositeLogger : ILogger
{
public bool DebugLogEnabled { get; set; } = false;
public bool InfoLogEnabled { get; set; } = true;
public bool WarnLogEnabled { get; set; } = true;
public bool ErrorLogenabled { get; set; } = true;
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)
{
if(!this.CheckSeverity(severity))
return;
for (int i = 0; i < _loggers.Length; i++)
_loggers[i].Log(context, severity, message, format);
}
public void Dispose()
{
for (int i = 0; i < _loggers.Length; i++)
{
_loggers[i].Dispose();
}
}
}

View File

@ -0,0 +1,47 @@
namespace DTLib.Logging.New;
// вывод лога в консоль и файл
public class ConsoleLogger : ILogger
{
public bool DebugLogEnabled { get; set; } = false;
public bool InfoLogEnabled { get; set; } = true;
public bool WarnLogEnabled { get; set; } = true;
public bool ErrorLogenabled { get; set; } = true;
public ILogFormat Format { get; }
readonly object consolelocker = new();
public ConsoleLogger(ILogFormat format)
=> Format = format;
public ConsoleLogger() : this(new DefaultLogFormat())
{}
public void Log(string context, LogSeverity severity, object message, ILogFormat format)
{
if(!this.CheckSeverity(severity))
return;
var msg = format.CreateMessage(context, severity, message);
lock (consolelocker)
ColoredConsole.Write(ColorFromSeverity(severity),msg);
}
private static ConsoleColor ColorFromSeverity(LogSeverity severity)
=> severity switch
{
LogSeverity.Debug => ConsoleColor.Gray,
LogSeverity.Info => ConsoleColor.White,
LogSeverity.Warn => ConsoleColor.Yellow,
LogSeverity.Error => ConsoleColor.Red,
_ => throw new ArgumentOutOfRangeException(nameof(severity), severity, null)
};
public void Dispose()
{
lock (consolelocker) {}
}
~ConsoleLogger() => Dispose();
}

View File

@ -0,0 +1,55 @@
namespace DTLib.Logging.New;
public class FileLogger : ILogger
{
public bool DebugLogEnabled { get; set; } = false;
public bool InfoLogEnabled { get; set; } = true;
public bool WarnLogEnabled { get; set; } = true;
public bool ErrorLogenabled { get; set; } = true;
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)
{
if(!this.CheckSeverity(severity))
return;
var msg = format.CreateMessage(context, severity, message);
lock (LogfileStream)
{
LogfileStream.Write(msg.ToBytes(StringConverter.UTF8));
LogfileStream.Flush();
}
}
public virtual void Dispose()
{
try
{
LogfileStream?.Flush();
LogfileStream?.Dispose();
}
catch (ObjectDisposedException) { }
}
~FileLogger() => Dispose();
}

View File

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

View File

@ -0,0 +1,12 @@
using Ben.Demystifier;
namespace DTLib.Logging.New;
public static class LoggerExtensions
{
public static void Log(this ILogger logger, string context, LogSeverity severity, object message)
=> logger.Log(context, severity, message, logger.Format);
public static void LogException(this ILogger logger, string context, Exception ex)
=> logger.Log(context, LogSeverity.Error, ex.Demystify());
}

View File

@ -23,8 +23,8 @@ public class FSP
lock (MainSocket)
{
Debug("b", $"requesting file download: {filePath_server}");
MainSocket.SendPackage("requesting file download".ToBytes());
MainSocket.SendPackage(filePath_server.ToBytes());
MainSocket.SendPackage("requesting file download".ToBytes(StringConverter.UTF8));
MainSocket.SendPackage(filePath_server.ToBytes(StringConverter.UTF8));
}
DownloadFile(filePath_client);
}
@ -44,8 +44,8 @@ public class FSP
lock (MainSocket)
{
Debug("b", $"requesting file download: {filePath_server}");
MainSocket.SendPackage("requesting file download".ToBytes());
MainSocket.SendPackage(filePath_server.ToBytes());
MainSocket.SendPackage("requesting file download".ToBytes(StringConverter.UTF8));
MainSocket.SendPackage(filePath_server.ToBytes(StringConverter.UTF8));
}
return DownloadFileToMemory();
}
@ -65,8 +65,8 @@ public class FSP
lock (MainSocket)
{
BytesDownloaded = 0;
Filesize = MainSocket.GetPackage().BytesToString().ToUInt();
MainSocket.SendPackage("ready".ToBytes());
Filesize = MainSocket.GetPackage().BytesToString(StringConverter.UTF8).ToUInt();
MainSocket.SendPackage("ready".ToBytes(StringConverter.UTF8));
int packagesCount = 0;
byte[] buffer = new byte[5120];
int fullPackagesCount = (Filesize / buffer.Length).Truncate();
@ -89,7 +89,7 @@ public class FSP
// получение остатка
if ((Filesize - fileStream.Position) > 0)
{
MainSocket.SendPackage("remain request".ToBytes());
MainSocket.SendPackage("remain request".ToBytes(StringConverter.UTF8));
buffer = MainSocket.GetPackage();
BytesDownloaded += (uint)buffer.Length;
fileStream.Write(buffer, 0, buffer.Length);
@ -109,7 +109,7 @@ public class FSP
Filesize = File.GetSize(filePath).ToUInt();
lock (MainSocket)
{
MainSocket.SendPackage(Filesize.ToString().ToBytes());
MainSocket.SendPackage(Filesize.ToString().ToBytes(StringConverter.UTF8));
MainSocket.GetAnswer("ready");
byte[] buffer = new byte[5120];
int packagesCount = 0;
@ -142,7 +142,7 @@ public class FSP
if (!dirOnServer.EndsWith(Путь.Разд))
dirOnServer += Путь.Разд;
Debug("b", "downloading manifest <", "c", dirOnServer + "manifest.dtsod", "b", ">");
var manifest = new DtsodV23(DownloadFileToMemory(dirOnServer + "manifest.dtsod").BytesToString());
var manifest = new DtsodV23(DownloadFileToMemory(dirOnServer + "manifest.dtsod").BytesToString(StringConverter.UTF8));
Debug("g", $"found {manifest.Values.Count} files in manifest");
var hasher = new Hasher();
foreach (string fileOnServer in manifest.Keys)

View File

@ -37,19 +37,19 @@ public static class Package
if (data.Length == 0)
throw new Exception($"SendPackage() error: package has zero size");
var list = new List<byte>();
byte[] packageSize = data.Length.ToBytes();
byte[] packageSize = data.Length.IntToBytes();
if (packageSize.Length == 1)
list.Add(0);
list.AddRange(packageSize);
list.AddRange(data);
socket.Send(list.ToArray());
}
public static void SendPackage(this Socket socket, string data) => SendPackage(socket, data.ToBytes());
public static void SendPackage(this Socket socket, string data) => SendPackage(socket, data.ToBytes(StringConverter.UTF8));
// получает пакет и выбрасывает исключение, если пакет не соответствует образцу
public static void GetAnswer(this Socket socket, string answer)
{
string rec = socket.GetPackage().BytesToString();
string rec = socket.GetPackage().BytesToString(StringConverter.UTF8);
if (rec != answer)
throw new Exception($"GetAnswer() error: invalid answer: <{rec}>");
}
@ -59,5 +59,5 @@ public static class Package
socket.SendPackage(request);
return socket.GetPackage();
}
public static byte[] RequestPackage(this Socket socket, string request) => socket.RequestPackage(request.ToBytes());
public static byte[] RequestPackage(this Socket socket, string request) => socket.RequestPackage(request.ToBytes(StringConverter.UTF8));
}

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

@ -15,24 +15,24 @@ public static class TestAutoarr
public static void Fill(Autoarr<KVPair> ar)
{
Info.Log("c", "----------[TestAutoarr/Fill]----------");
OldLogger.Log("c", "----------[TestAutoarr/Fill]----------");
for(uint i=0;i<ar.MaxLength;i++)
ar.Add(new KVPair($"key_{i}",new Unitype(i)));
Info.Log("g", "test completed");
OldLogger.Log("g", "test completed");
}
public static void Print(Autoarr<KVPair> ar)
{
Info.Log("c", "----------[TestAutoarr/Print]---------");
OldLogger.Log("c", "----------[TestAutoarr/Print]---------");
foreach (KVPair pair in ar)
Info.Log("h", pair.ToString());
Info.Log("g", "test completed");
OldLogger.Log("h", pair.ToString());
OldLogger.Log("g", "test completed");
}
public static void Free(Autoarr<KVPair> ar)
{
Info.Log("c", "----------[TestAutoarr/Free]----------");
OldLogger.Log("c", "----------[TestAutoarr/Free]----------");
ar.Dispose();
Info.Log("g", "test completed");
OldLogger.Log("g", "test completed");
}
}

View File

@ -16,73 +16,73 @@ public static class TestDtsodV23
public static void TestBaseTypes()
{
Info.Log("c", "-----[TestDtsodV23/TestBaseTypes]-----");
OldLogger.Log("c", "-----[TestDtsodV23/TestBaseTypes]-----");
DtsodV23 dtsod = new(File.ReadAllText($"Dtsod{Путь.Разд}TestResources{Путь.Разд}DtsodV23{Путь.Разд}base_types.dtsod"));
foreach (var pair in dtsod)
Info.Log("b", pair.Value.GetType().Name + ' ', "w", pair.Key + ' ', "c", pair.Value.ToString());
Info.Log("g", "test completed");
OldLogger.Log("b", pair.Value.GetType().Name + ' ', "w", pair.Key + ' ', "c", pair.Value.ToString());
OldLogger.Log("g", "test completed");
}
public static void TestLists()
{
Info.Log("c", "-------[TestDtsodV23/TestLists]-------");
OldLogger.Log("c", "-------[TestDtsodV23/TestLists]-------");
DtsodV23 dtsod = new(File.ReadAllText($"Dtsod{Путь.Разд}TestResources{Путь.Разд}DtsodV23{Путь.Разд}lists.dtsod"));
foreach (var pair in dtsod)
{
Info.Log("b", pair.Value.GetType().Name + ' ', "w", pair.Key, "c",
OldLogger.Log("b", pair.Value.GetType().Name + ' ', "w", pair.Key, "c",
$" count: {pair.Value.Count}");
foreach (var el in pair.Value)
Info.Log("b", '\t'+el.GetType().Name + ' ', "c", el.ToString());
OldLogger.Log("b", '\t'+el.GetType().Name + ' ', "c", el.ToString());
}
Info.Log("g", "test completed");
OldLogger.Log("g", "test completed");
}
public static void TestComplexes()
{
Info.Log("c", "-----[TestDtsodV23/TestComplexes]-----");
OldLogger.Log("c", "-----[TestDtsodV23/TestComplexes]-----");
DtsodV23 dtsod = new(File.ReadAllText($"Dtsod{Путь.Разд}TestResources{Путь.Разд}DtsodV23{Путь.Разд}complexes.dtsod"));
foreach (var complex in dtsod)
{
Info.Log("b", complex.Value.GetType().Name + ' ', "w", complex.Key,
OldLogger.Log("b", complex.Value.GetType().Name + ' ', "w", complex.Key,
"b", " size: ", "c", complex.Value.Keys.Count.ToString());
foreach (var pair in (DtsodV23) complex.Value)
Info.Log("b", '\t' + pair.Value.GetType().Name + ' ', "w", pair.Key + ' ',
OldLogger.Log("b", '\t' + pair.Value.GetType().Name + ' ', "w", pair.Key + ' ',
"c", pair.Value.ToString());
}
Info.Log("g", "test completed");
OldLogger.Log("g", "test completed");
}
public static void TestReSerialization()
{
Info.Log("c", "--[TestDtsodV23/TestReSerialization]--");
OldLogger.Log("c", "--[TestDtsodV23/TestReSerialization]--");
var dtsod = new DtsodV23(new DtsodV23(new DtsodV23(
new DtsodV23(File.ReadAllText($"Dtsod{Путь.Разд}TestResources{Путь.Разд}DtsodV23{Путь.Разд}complexes.dtsod")).ToString()).ToString()).ToString());
Info.Log("y", dtsod.ToString());
Info.Log("g", "test completed");
OldLogger.Log("y", dtsod.ToString());
OldLogger.Log("g", "test completed");
}
public static void TestSpeed()
{
Info.Log("c", "-------[TestDtsodV23/TestSpeed]-------");
OldLogger.Log("c", "-------[TestDtsodV23/TestSpeed]-------");
IDtsod dtsod=null;
string text = File.ReadAllText($"Dtsod{Путь.Разд}TestResources{Путь.Разд}DtsodV23{Путь.Разд}messages.dtsod");
LogOperationTime("V21 deserialization",64,()=>dtsod=new DtsodV21(text));
LogOperationTime("V21 serialization", 64, () => _=dtsod.ToString());
LogOperationTime("V23 deserialization", 64, () => dtsod = new DtsodV23(text));
LogOperationTime("V23 serialization", 64, () => _ = dtsod.ToString());
Info.Log("g", "test completed");
OldLogger.Log("g", "test completed");
}
public static void TestMemoryConsumption()
{
Info.Log("c", "----[TestDtsodV23/TestMemConsumpt]----");
OldLogger.Log("c", "----[TestDtsodV23/TestMemConsumpt]----");
string text = File.ReadAllText($"Dtsod{Путь.Разд}TestResources{Путь.Разд}DtsodV23{Путь.Разд}messages.dtsod");
var a = GC.GetTotalMemory(true);
var dtsods = new DtsodV23[64];
for (int i = 0; i < dtsods.Length; i++)
dtsods[i] = new(text);
var b = GC.GetTotalMemory(true);
Info.Log("b", "at the start: ","c",$"{a/1024} kb\n",
OldLogger.Log("b", "at the start: ","c",$"{a/1024} kb\n",
"b", "at the end: ", "c", $"{b / 1024} kb\n{dtsods.Count()}","b"," dtsods initialized");
Info.Log("g", "test completed");
OldLogger.Log("g", "test completed");
}
}

View File

@ -17,57 +17,57 @@ public static class TestDtsodV24
public static void TestBaseTypes()
{
Info.Log("c", "-----[TestDtsodV24/TestBaseTypes]-----");
OldLogger.Log("c", "-----[TestDtsodV24/TestBaseTypes]-----");
DtsodV24 dtsod = new(File.ReadAllText($"Dtsod{Путь.Разд}TestResources{Путь.Разд}DtsodV24{Путь.Разд}base_types.dtsod"));
foreach (var pair in dtsod)
Info.Log("b", pair.ToString());
Info.Log("g", "test completed");
OldLogger.Log("b", pair.ToString());
OldLogger.Log("g", "test completed");
}
public static void TestComplexes()
{
Info.Log("c", "-----[TestDtsodV24/TestComplexes]-----");
OldLogger.Log("c", "-----[TestDtsodV24/TestComplexes]-----");
DtsodV24 dtsod = new(File.ReadAllText($"Dtsod{Путь.Разд}TestResources{Путь.Разд}DtsodV24{Путь.Разд}complexes.dtsod"));
Info.Log("h", dtsod.ToString());
Info.Log("g", "test completed");
OldLogger.Log("h", dtsod.ToString());
OldLogger.Log("g", "test completed");
}
public static void TestLists()
{
Info.Log("c", "-------[TestDtsodV24/TestLists]-------");
OldLogger.Log("c", "-------[TestDtsodV24/TestLists]-------");
DtsodV24 dtsod = new(File.ReadAllText($"Dtsod{Путь.Разд}TestResources{Путь.Разд}DtsodV24{Путь.Разд}lists.dtsod"));
foreach (KVPair pair in dtsod)
{
var list = new Autoarr<Unitype>(pair.value.VoidPtr, false);
Info.Log("b", pair.key.HGlobalUTF8ToString(), "w", $" length: {list.Length}");
OldLogger.Log("b", pair.key.HGlobalUTF8ToString(), "w", $" length: {list.Length}");
foreach (var el in list)
{
Info.Log("h", '\t' + el.ToString());
OldLogger.Log("h", '\t' + el.ToString());
if (el.TypeCode == KerepTypeCode.AutoarrUnitypePtr)
{
var ar = new Autoarr<Unitype>(el.VoidPtr, false);
foreach (var k in ar)
{
Info.Log($"\t\t{k.ToString()}");
OldLogger.Log($"\t\t{k.ToString()}");
}
}
}
}
Info.Log("g", "test completed");
OldLogger.Log("g", "test completed");
}
public static void TestReSerialization()
{
Info.Log("c", "--[TestDtsodV24/TestReSerialization]--");
OldLogger.Log("c", "--[TestDtsodV24/TestReSerialization]--");
var dtsod = new DtsodV24(new DtsodV24(new DtsodV24(
new DtsodV24(File.ReadAllText($"Dtsod{Путь.Разд}TestResources{Путь.Разд}DtsodV24{Путь.Разд}complexes.dtsod")).ToString()).ToString()).ToString());
Info.Log("h", dtsod.ToString());
Info.Log("g", "test completed");
OldLogger.Log("h", dtsod.ToString());
OldLogger.Log("g", "test completed");
}
public static void TestSpeed()
{
Info.Log("c", "-------[TestDtsodV24/TestSpeed]-------");
OldLogger.Log("c", "-------[TestDtsodV24/TestSpeed]-------");
IDtsod dtsod=null;
string _text = File.ReadAllText($"Dtsod{Путь.Разд}TestResources{Путь.Разд}DtsodV23{Путь.Разд}messages.dtsod");
string text = "";
@ -77,6 +77,6 @@ public static class TestDtsodV24
File.WriteAllText($"Dtsod{Путь.Разд}TestResources{Путь.Разд}DtsodV24{Путь.Разд}messages.dtsod",text);
LogOperationTime("V24 deserialization", 64, () => dtsod = new DtsodV24(text));
LogOperationTime("V24 serialization", 64, () => text = dtsod.ToString());
Info.Log("g", "test completed");
OldLogger.Log("g", "test completed");
}
}

View File

@ -16,7 +16,7 @@ public static class TestPInvoke
static public void TestUTF8()
{
Info.Log("c", "--------[TestPInvoke/TestUTF8]--------", "b", "");
OldLogger.Log("c", "--------[TestPInvoke/TestUTF8]--------", "b", "");
IntPtr ptr;
string str="_$\"\\\\'''\ta ыыы000;2;=:%d;```";
for(int i=0; i<1000; i++)
@ -24,7 +24,7 @@ public static class TestPInvoke
ptr = Unmanaged.StringToHGlobalUTF8(str);
str = Unmanaged.HGlobalUTF8ToString(ptr);
}
Info.Log("y", str);
OldLogger.Log("y", str);
}
[DllImport("kerep", CallingConvention = CallingConvention.Cdecl)]
@ -32,9 +32,9 @@ public static class TestPInvoke
public static void TestPrintf()
{
Info.Log("c", "---------[TestPInvoke/Printf]---------", "b", "");
OldLogger.Log("c", "---------[TestPInvoke/Printf]---------", "b", "");
pinvoke_print("ъъ~ 中文");
Info.Log("g", "test completed");
OldLogger.Log("g", "test completed");
}
[DllImport("kerep", CallingConvention = CallingConvention.Cdecl)]
@ -42,11 +42,11 @@ public static class TestPInvoke
public static unsafe void TestMarshalling()
{
Info.Log("c", "---------[TestAutoarr/TestMarshalling]----------");
OldLogger.Log("c", "---------[TestAutoarr/TestMarshalling]----------");
string msg = "ъъ~ 中文";
test_marshalling(msg, out var kptr);
KVPair k = *(KVPair*)kptr;
Info.Log("b", k.ToString());
Info.Log("g", "test completed");
OldLogger.Log("b", k.ToString());
OldLogger.Log("g", "test completed");
}
}

View File

@ -8,19 +8,20 @@ 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;
using DTLib.Logging.New;
namespace DTLib.Tests;
public static class Program
{
public static readonly ConsoleLogger Info = new("logs", "DTLib.Tests");
public static readonly Logging.ConsoleLogger OldLogger = new("logs", "DTLib.Tests");
public static readonly ILogger NewLogger = new CompositeLogger(new ConsoleLogger(), new FileLogger(OldLogger.LogfileName));
public static void Main()
{
PublicLog.LogEvent += Info.Log;
Logging.PublicLog.LogEvent += OldLogger.Log;
Console.OutputEncoding = Encoding.UTF8;
Console.InputEncoding = Encoding.UTF8;
Console.Title="tester";
@ -32,7 +33,7 @@ public static class Program
TestDtsodV24.TestAll();
}
catch (Exception ex)
{ Info.Log("r", ex.ToString()); }
{ NewLogger.LogException("Main", ex); }
Console.ResetColor();
}
}

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

@ -9,14 +9,19 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DTLib.Tests", "DTLib.Tests\
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{6308F24E-A4FF-46B3-B72F-30E05DDCB1D5}"
ProjectSection(SolutionItems) = preProject
.gitignore = .gitignore
README.md = README.md
.gitignore = .gitignore
.gitmodules = .gitmodules
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DTLib.Dtsod", "DTLib.Dtsod\DTLib.Dtsod.csproj", "{ADE425F5-8645-47F0-9AA8-33FA748D36BE}"
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
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Ben.Demystifier", "DTLib.Logging\Ben.Demystifier\src\Ben.Demystifier\Ben.Demystifier.csproj", "{AC7CB524-4D59-42E0-9F96-1C201A92494B}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -39,6 +44,14 @@ 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
{AC7CB524-4D59-42E0-9F96-1C201A92494B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{AC7CB524-4D59-42E0-9F96-1C201A92494B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AC7CB524-4D59-42E0-9F96-1C201A92494B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AC7CB524-4D59-42E0-9F96-1C201A92494B}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE

View File

@ -30,36 +30,36 @@ public static class ColoredConsole
_ => throw new Exception($"ColoredConsole.ParseColor({color}) error: incorrect color"),
};
public static void Write(ConsoleColor color,string msg)
{
Console.ForegroundColor = color;
Console.Write(msg);
Console.ForegroundColor = ConsoleColor.Gray;
}
public static void Write(string msg) => Write(ConsoleColor.Gray, msg);
// вывод цветного текста
public static void Write(params string[] input)
{
if (input.Length == 1)
{
if (Console.ForegroundColor != ConsoleColor.Gray)
Console.ForegroundColor = ConsoleColor.Gray;
Console.Write(input[0]);
}
else if (input.Length % 2 == 0)
{
StringBuilder strB = new();
if (input.Length % 2 != 0)
throw new Exception("ColoredConsole.Write() error: every text string must have color string before");
for (ushort i = 0; i < input.Length; i++)
{
ConsoleColor c = ParseColor(input[i]);
if (Console.ForegroundColor != c)
{
Console.Write(strB.ToString());
Console.ForegroundColor = c;
strB.Clear();
Console.ForegroundColor = ParseColor(input[i++]);
Console.Write(input[i]);
}
strB.Append(input[++i]);
}
if (strB.Length > 0)
Console.Write(strB.ToString());
}
else throw new Exception("ColoredConsole.Write() error: every text string must have color string before");
Console.ForegroundColor = ConsoleColor.Gray;
}
public static void WriteLine() => Console.WriteLine();
public static void WriteLine(ConsoleColor color,string msg)
{
Console.ForegroundColor = color;
Console.WriteLine(msg);
Console.ForegroundColor = ConsoleColor.Gray;
}
public static void WriteLine(params string[] input)
{
@ -68,11 +68,13 @@ public static class ColoredConsole
}
// ввод цветного текста
public static string Read(string color)
public static string Read(ConsoleColor color)
{
ConsoleColor c = ParseColor(color);
if (Console.ForegroundColor != c)
Console.ForegroundColor = c;
return Console.ReadLine();
Console.ForegroundColor = color;
var r = Console.ReadLine();
Console.ForegroundColor = ConsoleColor.Gray;
return r;
}
public static string Read(string color) => Read(ParseColor(color));
}

View File

@ -35,7 +35,7 @@ public static class BaseConverter
return output;
}
public static byte[] ToBytes(this int num)
public static byte[] IntToBytes(this int num)
{
List<byte> output = new();
while (num != 0)

View File

@ -2,11 +2,10 @@
public static class StringConverter
{
public static ASCIIEncoding ASCII = new ASCIIEncoding();
public static Encoding UTF8 = new UTF8Encoding(false);
public static Encoding UTF8BOM = new UTF8Encoding(true);
public static byte[] ToBytes(this string str) => UTF8.GetBytes(str);
public static string BytesToString(this byte[] bytes) => UTF8.GetString(bytes);
public static byte[] ToBytes(this string str, Encoding encoding) => encoding.GetBytes(str);
public static string BytesToString(this byte[] bytes, Encoding encoding) => encoding.GetString(bytes);
// хеш в виде массива байт в строку (хеш изначально не в кодировке UTF8, так что метод выше не работает с ним)
public static string HashToString(this byte[] hash)
@ -51,6 +50,11 @@ public static class StringConverter
builder.Append(parts[i]);
return builder.ToString();
}
// String.Join(sep,string...) does some low-level memory manipulations, that are faster than StringBuilder
public static string MergeToString(params string[] parts)
=>string.Join(null, parts);
public static string MergeToString<T>(this IEnumerable<T> collection, string separator)
{
StringBuilder builder = new();

View File

@ -6,7 +6,7 @@ public static class Unmanaged
{
public static unsafe IntPtr StringToHGlobalUTF8(this string s)
{
byte[] buf = s.ToBytes();
byte[] buf = s.ToBytes(StringConverter.UTF8);
int bl = buf.Length;
byte* ptr=(byte*)Marshal.AllocHGlobal(bl + 1);
for (int i = 0; i < bl; i++)

View File

@ -39,7 +39,7 @@ public static class File
return output;
}
public static string ReadAllText(string file) => ReadAllBytes(file).BytesToString();
public static string ReadAllText(string file) => ReadAllBytes(file).BytesToString(StringConverter.UTF8);
public static void WriteAllBytes(string file, byte[] content)
{
@ -48,7 +48,7 @@ public static class File
stream.Close();
}
public static void WriteAllText(string file, string content) => WriteAllBytes(file, content.ToBytes());
public static void WriteAllText(string file, string content) => WriteAllBytes(file, content.ToBytes(StringConverter.UTF8));
public static void AppendAllBytes(string file, byte[] content)
{
@ -57,7 +57,7 @@ public static class File
stream.Close();
}
public static void AppendAllText(string file, string content) => AppendAllBytes(file, content.ToBytes());
public static void AppendAllText(string file, string content) => AppendAllBytes(file, content.ToBytes(StringConverter.UTF8));
public static System.IO.FileStream OpenRead(string file) =>
Exists(file)

View File

@ -1,6 +1,4 @@
using System.Globalization;
namespace DTLib.Logging;
namespace DTLib.Logging;
public class FileLogger : IDisposable
{
@ -24,16 +22,16 @@ public class FileLogger : IDisposable
{
LastLogMessageTime = DateTime.Now.ToString(MyTimeFormat.ForText);
LogfileStream.WriteByte('['.ToByte());
LogfileStream.Write(LastLogMessageTime.ToBytes());
LogfileStream.Write("]: ".ToBytes());
LogfileStream.Write(LastLogMessageTime.ToBytes(StringConverter.UTF8));
LogfileStream.Write("]: ".ToBytes(StringConverter.UTF8));
if (msg.Length == 1)
LogfileStream.Write(msg[0].ToBytes());
LogfileStream.Write(msg[0].ToBytes(StringConverter.UTF8));
else
{
var strb = new StringBuilder();
for (ushort i = 1; i < msg.Length; i += 2)
strb.Append(msg[i]);
LogfileStream.Write(strb.ToString().ToBytes());
LogfileStream.Write(strb.ToString().ToBytes(StringConverter.UTF8));
}
LogfileStream.WriteByte('\n'.ToByte());
LogfileStream.Flush();