diff --git a/.gitmodules b/.gitmodules
new file mode 100644
index 0000000..e231db6
--- /dev/null
+++ b/.gitmodules
@@ -0,0 +1,3 @@
+[submodule "DTLib.Logging/Ben.Demystifier"]
+ path = DTLib.Logging/Ben.Demystifier
+ url = https://github.com/Timerix22/Ben.Demystifier.git
diff --git a/DTLib.Logging/Ben.Demystifier b/DTLib.Logging/Ben.Demystifier
new file mode 160000
index 0000000..f64d655
--- /dev/null
+++ b/DTLib.Logging/Ben.Demystifier
@@ -0,0 +1 @@
+Subproject commit f64d655f490602b5858baeed3572ea2a9b850013
diff --git a/DTLib.Logging/DTLib.Logging.csproj b/DTLib.Logging/DTLib.Logging.csproj
new file mode 100644
index 0000000..ff0927c
--- /dev/null
+++ b/DTLib.Logging/DTLib.Logging.csproj
@@ -0,0 +1,26 @@
+
+
+
+ net6.0;net48
+ 10
+ disable
+ disable
+ true
+ embedded
+ False
+ Debug;Release
+ AnyCPU;x64;x86;arm64
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/DTLib.Logging/DependencyInjection/LoggerService.cs b/DTLib.Logging/DependencyInjection/LoggerService.cs
new file mode 100644
index 0000000..c544609
--- /dev/null
+++ b/DTLib.Logging/DependencyInjection/LoggerService.cs
@@ -0,0 +1,15 @@
+using Microsoft.Extensions.DependencyInjection;
+
+namespace DTLib.Logging.DependencyInjection;
+
+public class LoggerService : ServiceDescriptor
+{
+ DTLib.Logging.New.ILogger _logger;
+
+ public LoggerService(DTLib.Logging.New.ILogger logger) : base(
+ typeof(Microsoft.Extensions.Logging.ILogger),
+ new MyLoggerWrapper(logger))
+ {
+ _logger = logger;
+ }
+}
\ No newline at end of file
diff --git a/DTLib.Logging/DependencyInjection/MyLoggerWrapper.cs b/DTLib.Logging/DependencyInjection/MyLoggerWrapper.cs
new file mode 100644
index 0000000..98bbbef
--- /dev/null
+++ b/DTLib.Logging/DependencyInjection/MyLoggerWrapper.cs
@@ -0,0 +1,39 @@
+using DTLib.Logging.New;
+using Microsoft.Extensions.Logging;
+
+namespace DTLib.Logging.DependencyInjection;
+
+public class MyLoggerWrapper : Microsoft.Extensions.Logging.ILogger
+{
+ public DTLib.Logging.New.ILogger Logger;
+ public MyLoggerWrapper(DTLib.Logging.New.ILogger logger)=>
+ Logger = logger;
+
+ public void Log(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func 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 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)
+ }
+ ;
+}
\ No newline at end of file
diff --git a/DTLib.Logging/Global.cs b/DTLib.Logging/Global.cs
new file mode 100644
index 0000000..6f7c1f3
--- /dev/null
+++ b/DTLib.Logging/Global.cs
@@ -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;
+
diff --git a/DTLib.Logging/LogFormats/DefaultLogFormat.cs b/DTLib.Logging/LogFormats/DefaultLogFormat.cs
new file mode 100644
index 0000000..a51344f
--- /dev/null
+++ b/DTLib.Logging/LogFormats/DefaultLogFormat.cs
@@ -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();
+ }
+}
\ No newline at end of file
diff --git a/DTLib.Logging/LogFormats/ILogFormat.cs b/DTLib.Logging/LogFormats/ILogFormat.cs
new file mode 100644
index 0000000..3b1834f
--- /dev/null
+++ b/DTLib.Logging/LogFormats/ILogFormat.cs
@@ -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);
+}
\ No newline at end of file
diff --git a/DTLib.Logging/LogSeverity.cs b/DTLib.Logging/LogSeverity.cs
new file mode 100644
index 0000000..81d3d67
--- /dev/null
+++ b/DTLib.Logging/LogSeverity.cs
@@ -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")
+ };
+}
\ No newline at end of file
diff --git a/DTLib.Logging/Loggers/CompositeLogger.cs b/DTLib.Logging/Loggers/CompositeLogger.cs
new file mode 100644
index 0000000..256bc6a
--- /dev/null
+++ b/DTLib.Logging/Loggers/CompositeLogger.cs
@@ -0,0 +1,42 @@
+namespace DTLib.Logging.New;
+
+///
+/// This class can be used for unite many loggers into one
+///
+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();
+ }
+ }
+}
\ No newline at end of file
diff --git a/DTLib.Logging/Loggers/ConsoleLogger.cs b/DTLib.Logging/Loggers/ConsoleLogger.cs
new file mode 100644
index 0000000..3ffe8dd
--- /dev/null
+++ b/DTLib.Logging/Loggers/ConsoleLogger.cs
@@ -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();
+}
diff --git a/DTLib.Logging/Loggers/FileLogger.cs b/DTLib.Logging/Loggers/FileLogger.cs
new file mode 100644
index 0000000..459d3c6
--- /dev/null
+++ b/DTLib.Logging/Loggers/FileLogger.cs
@@ -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();
+}
diff --git a/DTLib.Logging/Loggers/ILogger.cs b/DTLib.Logging/Loggers/ILogger.cs
new file mode 100644
index 0000000..ab6eedf
--- /dev/null
+++ b/DTLib.Logging/Loggers/ILogger.cs
@@ -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);
+
+}
\ No newline at end of file
diff --git a/DTLib.Logging/Loggers/LoggerExtensions.cs b/DTLib.Logging/Loggers/LoggerExtensions.cs
new file mode 100644
index 0000000..3fee831
--- /dev/null
+++ b/DTLib.Logging/Loggers/LoggerExtensions.cs
@@ -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());
+}
\ No newline at end of file
diff --git a/DTLib.Network/FSP.cs b/DTLib.Network/FSP.cs
index fae6fa2..d418497 100644
--- a/DTLib.Network/FSP.cs
+++ b/DTLib.Network/FSP.cs
@@ -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)
diff --git a/DTLib.Network/Package.cs b/DTLib.Network/Package.cs
index 7c94e6e..45a0d4b 100644
--- a/DTLib.Network/Package.cs
+++ b/DTLib.Network/Package.cs
@@ -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[] 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));
}
diff --git a/DTLib.Tests/DTLib.Tests.csproj b/DTLib.Tests/DTLib.Tests.csproj
index cce9ae1..240d82e 100644
--- a/DTLib.Tests/DTLib.Tests.csproj
+++ b/DTLib.Tests/DTLib.Tests.csproj
@@ -21,6 +21,7 @@
+
diff --git a/DTLib.Tests/Dtsod/TestAutoarr.cs b/DTLib.Tests/Dtsod/TestAutoarr.cs
index cbeaa9d..0605159 100644
--- a/DTLib.Tests/Dtsod/TestAutoarr.cs
+++ b/DTLib.Tests/Dtsod/TestAutoarr.cs
@@ -15,24 +15,24 @@ public static class TestAutoarr
public static void Fill(Autoarr ar)
{
- Info.Log("c", "----------[TestAutoarr/Fill]----------");
+ OldLogger.Log("c", "----------[TestAutoarr/Fill]----------");
for(uint i=0;i 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 ar)
{
- Info.Log("c", "----------[TestAutoarr/Free]----------");
+ OldLogger.Log("c", "----------[TestAutoarr/Free]----------");
ar.Dispose();
- Info.Log("g", "test completed");
+ OldLogger.Log("g", "test completed");
}
}
\ No newline at end of file
diff --git a/DTLib.Tests/Dtsod/TestDtsodV23.cs b/DTLib.Tests/Dtsod/TestDtsodV23.cs
index c397943..5f7ac9a 100644
--- a/DTLib.Tests/Dtsod/TestDtsodV23.cs
+++ b/DTLib.Tests/Dtsod/TestDtsodV23.cs
@@ -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");
}
}
diff --git a/DTLib.Tests/Dtsod/TestDtsodV24.cs b/DTLib.Tests/Dtsod/TestDtsodV24.cs
index f5d829b..5e840bb 100644
--- a/DTLib.Tests/Dtsod/TestDtsodV24.cs
+++ b/DTLib.Tests/Dtsod/TestDtsodV24.cs
@@ -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(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(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");
}
}
\ No newline at end of file
diff --git a/DTLib.Tests/Dtsod/TestPInvoke.cs b/DTLib.Tests/Dtsod/TestPInvoke.cs
index f95b199..8c8caa8 100644
--- a/DTLib.Tests/Dtsod/TestPInvoke.cs
+++ b/DTLib.Tests/Dtsod/TestPInvoke.cs
@@ -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");
}
}
\ No newline at end of file
diff --git a/DTLib.Tests/Program.cs b/DTLib.Tests/Program.cs
index de48fb1..a5f58f3 100644
--- a/DTLib.Tests/Program.cs
+++ b/DTLib.Tests/Program.cs
@@ -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();
}
}
\ No newline at end of file
diff --git a/DTLib/Logging/Tester.cs b/DTLib.Tests/Tester.cs
similarity index 62%
rename from DTLib/Logging/Tester.cs
rename to DTLib.Tests/Tester.cs
index 36709e9..d868e1a 100644
--- a/DTLib/Logging/Tester.cs
+++ b/DTLib.Tests/Tester.cs
@@ -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");
}
}
\ No newline at end of file
diff --git a/DTLib.sln b/DTLib.sln
index d8569c9..15aec6c 100644
--- a/DTLib.sln
+++ b/DTLib.sln
@@ -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
diff --git a/DTLib/ColoredConsole.cs b/DTLib/ColoredConsole.cs
index b23f61b..44209e6 100644
--- a/DTLib/ColoredConsole.cs
+++ b/DTLib/ColoredConsole.cs
@@ -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 (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++)
{
- if (Console.ForegroundColor != ConsoleColor.Gray)
- Console.ForegroundColor = ConsoleColor.Gray;
- Console.Write(input[0]);
+ Console.ForegroundColor = ParseColor(input[i++]);
+ Console.Write(input[i]);
}
- else if (input.Length % 2 == 0)
- {
- StringBuilder strB = new();
- 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();
- }
- 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));
}
diff --git a/DTLib/Extensions/BaseConverter.cs b/DTLib/Extensions/BaseConverter.cs
index 5ce7712..74ec1d4 100644
--- a/DTLib/Extensions/BaseConverter.cs
+++ b/DTLib/Extensions/BaseConverter.cs
@@ -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 output = new();
while (num != 0)
diff --git a/DTLib/Extensions/StringConverter.cs b/DTLib/Extensions/StringConverter.cs
index a3ce624..6dc3032 100644
--- a/DTLib/Extensions/StringConverter.cs
+++ b/DTLib/Extensions/StringConverter.cs
@@ -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(this IEnumerable collection, string separator)
{
StringBuilder builder = new();
diff --git a/DTLib/Extensions/Unmanaged.cs b/DTLib/Extensions/Unmanaged.cs
index 2eaff37..39ec9b0 100644
--- a/DTLib/Extensions/Unmanaged.cs
+++ b/DTLib/Extensions/Unmanaged.cs
@@ -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++)
diff --git a/DTLib/Filesystem/File.cs b/DTLib/Filesystem/File.cs
index 8ed8912..756b5da 100644
--- a/DTLib/Filesystem/File.cs
+++ b/DTLib/Filesystem/File.cs
@@ -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)
diff --git a/DTLib/Logging/FileLogger.cs b/DTLib/Logging/FileLogger.cs
index 3d65ee8..eb674aa 100644
--- a/DTLib/Logging/FileLogger.cs
+++ b/DTLib/Logging/FileLogger.cs
@@ -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();