Add Logger

This commit is contained in:
jozsef.b@aycode.com 2024-05-14 13:04:01 +02:00
parent c1b0fcd0d7
commit 602975ab29
28 changed files with 693 additions and 103 deletions

View File

@ -6,4 +6,8 @@
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\AyCode.Core\AyCode.Core.csproj" />
</ItemGroup>
</Project> </Project>

View File

@ -0,0 +1,67 @@
using System.Runtime.CompilerServices;
using AyCode.Core.Enums;
using AyCode.Core.Loggers;
namespace AyCode.Core.Server.Loggers
{
public sealed class AcGlobalLoggerBase : AcLoggerBase
{ }
public sealed class GlobalLogger //: IAcLogWriterBase
{
private readonly AcGlobalLoggerBase _logger = new();
private static readonly GlobalLogger Instance = new();
public static LogLevel LogLevel => Instance._logger.LogLevel;
public static AppType AppType => Instance._logger.AppType;
private const string DefaultCategoryName = "GLOBAL_LOGGER";
static GlobalLogger()
{ }
private GlobalLogger()
{ }
public static List<IAcLogWriterBase> GetWriters => Instance._logger.GetWriters;
public static TLogWriter Writer<TLogWriter>() where TLogWriter : IAcLogWriterBase => Instance._logger.Writer<TLogWriter>();
public static void Detail(string? text, string? categoryName = null, [CallerMemberName] string? memberName = null)
=> Instance._logger.Detail(text, categoryName ?? DefaultCategoryName, memberName);
//public static void Detail<TCallerClassType>(string? text, [CallerMemberName] string? memberName = null) where TCallerClassType : class
// => Detail(text, typeof(TCallerClassType).Name, memberName);
public static void Debug(string? text, string? categoryName = null, [CallerMemberName] string? memberName = null)
=> Instance._logger.Debug(text, categoryName ?? DefaultCategoryName, memberName);
//public static void Debug<TCallerClassType>(string? text, [CallerMemberName] string? memberName = null) where TCallerClassType : class
// => Debug(text, typeof(TCallerClassType).Name, memberName);
public static void Info(string? text, string? categoryName = null, [CallerMemberName] string? memberName = null)
=> Instance._logger.Info(text, categoryName ?? DefaultCategoryName, memberName);
//public static void Info<TCallerClassType>(string? text, [CallerMemberName] string? memberName = null) where TCallerClassType : class
// => Info(text, typeof(TCallerClassType).Name, memberName);
public static void Warning(string? text, string? categoryName = null, [CallerMemberName] string? memberName = null)
=> Instance._logger.Warning(text, categoryName ?? DefaultCategoryName, memberName);
//public static void Warning<TCallerClassType>(string? text, [CallerMemberName] string? memberName = null) where TCallerClassType : class
// => Warning(text, typeof(TCallerClassType).Name, memberName);
public static void Suggest(string? text, string? categoryName = null, [CallerMemberName] string? memberName = null)
=> Instance._logger.Suggest(text, categoryName ?? DefaultCategoryName, memberName);
//public static void Suggest<TCallerClassType>(string? text, [CallerMemberName] string? memberName = null) where TCallerClassType : class
// => Suggest(text, typeof(TCallerClassType).Name, memberName);
//public static void Error<TCallerClassType>(string? text, Exception? ex = null, [CallerMemberName] string? memberName = null) where TCallerClassType : class
// => Error(text, ex, typeof(TCallerClassType).Name, memberName);
public static void Error(string? text, Exception? ex = null, string? categoryName = null, [CallerMemberName] string? memberName = null)
=> Instance._logger.Error(text, ex, categoryName ?? DefaultCategoryName, memberName);
}
}

File diff suppressed because one or more lines are too long

View File

@ -1,5 +1,6 @@
//using Anata.Logger; //using Anata.Logger;
using AyCode.Core.Enums;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
namespace AyCode.Core.Consts namespace AyCode.Core.Consts
@ -24,7 +25,13 @@ namespace AyCode.Core.Consts
private static IConfiguration? _appConfiguration = null; private static IConfiguration? _appConfiguration = null;
public static IConfiguration AppConfiguration => _appConfiguration ??= GetAppSettingsConfiguration(); public static IConfiguration AppConfiguration => _appConfiguration ??= GetAppSettingsConfiguration();
public static IConfiguration GetAppSettingsConfiguration(string appSettingsFileName = "appsettings.json") public static TEnum GetEnum<TEnum>(this IConfiguration configuration, string configPath) where TEnum : struct
=> (TEnum)Enum.Parse(typeof(TEnum), configuration[configPath]);
public static TEnum GetEnum<TEnum>(this IConfigurationSection section, string configPath) where TEnum : struct
=> (TEnum)Enum.Parse(typeof(TEnum), section[configPath]);
private static IConfiguration GetAppSettingsConfiguration(string appSettingsFileName = "appsettings.json")
{ {
var config = new ConfigurationBuilder() var config = new ConfigurationBuilder()
.AddJsonFile(appSettingsFileName) .AddJsonFile(appSettingsFileName)

View File

@ -1,85 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using AyCode.Core.Consts;
using AyCode.Core.Enums;
namespace AyCode.Core.Logger
{
public static class Logger
{
public static LogLevel LogLevel { get; set; } = LogLevel.Detail;
public static AppType AppType { get; set; } = AppType.Server;
public static void Detail(string text, [CallerMemberName] string? memberName = null)
=> WriteToConsole(LogLevel.Detail, GetDiagnosticText(LogLevel.Detail, text, memberName, null));
public static void Debug(string text, [CallerMemberName] string? memberName = null)
=> WriteToConsole(LogLevel.Debug, GetDiagnosticText(LogLevel.Debug, text, memberName, null));
public static void Info(string text, [CallerMemberName] string? memberName = null)
=> WriteToConsole(LogLevel.Info, GetDiagnosticText(LogLevel.Info, text, memberName, null));
public static void Warning(string text, [CallerMemberName] string? memberName = null)
=> WriteToConsole(LogLevel.Warning, GetDiagnosticText(LogLevel.Warning, text, memberName, null));
public static void Suggest(string text, [CallerMemberName] string? memberName = null)
=> WriteToConsole(LogLevel.Suggest, GetDiagnosticText(LogLevel.Suggest, text, memberName, null));
public static void Error(string text, [CallerMemberName] string? memberName = null)
=> WriteToConsole(LogLevel.Error, GetDiagnosticText(LogLevel.Error, text, memberName, null));
public static void Error(string text, Exception ex, [CallerMemberName] string? memberName = null)
=> WriteToConsole(LogLevel.Error, GetDiagnosticText(LogLevel.Error, text, memberName, ex));
private static void WriteToConsole(LogLevel logLevel, string text)
{
if (logLevel < LogLevel) return;
//lock (ForWriterLock)
{
//if (logLevel > LogLevel.Trace && logLevel < LogLevel.Suggest)
{
Console.WriteLine(text);
return;
}
if (logLevel <= LogLevel.Trace)
{
Console.ForegroundColor = ConsoleColor.Gray;
Console.WriteLine(text);
}
else if (logLevel == LogLevel.Suggest)
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine(text);
}
else
{
Console.ForegroundColor = logLevel == LogLevel.Warning ? ConsoleColor.Yellow : ConsoleColor.Red;
Console.WriteLine($"{AcEnv.NL}{text}{AcEnv.NL}");
}
Console.ForegroundColor = ConsoleColor.White;
}
}
private static string GetDiagnosticText(LogLevel logLevel, string logText, string? callerName, Exception? ex)
{
var threadId = Environment.CurrentManagedThreadId;
return $"[{DateTime.Now:HH:mm:ss.fff}] [{AppType.ToString()[0]}] {"[" + logLevel + "]",-9} {"[...->" + callerName + "]",-54} {"[" + threadId + "]",5} {logText}{ErrorText(ex)}";
}
private static string ErrorText(Exception? ex)
{
if (ex == null) return string.Empty;
var errorType = ex.GetType().Name;
return string.IsNullOrWhiteSpace(errorType) ? string.Empty : $"{Environment.NewLine}[{errorType.ToUpper()}]: {ex}";
}
}
}

View File

@ -0,0 +1,49 @@
using AyCode.Core.Consts;
using AyCode.Core.Enums;
using AyCode.Utils.Extensions;
namespace AyCode.Core.Loggers;
public class AcConsoleLogWriter : AcTextLogWriterBase
{
protected AcConsoleLogWriter() : this(null)
{ }
protected AcConsoleLogWriter(string? categoryName = null) : base(categoryName)
{ }
public AcConsoleLogWriter(AppType appType, LogLevel logLevel, string? categoryName = null) : base(appType, logLevel, categoryName)
{ }
protected override void WriteText(string? logText)
{
if (logText.IsNullOrWhiteSpace()) return;
//lock (ForWriterLock)
{
//if (logLevel > LogLevel.Trace && logLevel < LogLevel.Suggest)
{
Console.WriteLine(logText);
return;
}
if (LogLevel <= LogLevel.Trace)
{
Console.ForegroundColor = ConsoleColor.Gray;
Console.WriteLine(logText);
}
else if (LogLevel == LogLevel.Suggest)
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine(logText);
}
else
{
Console.ForegroundColor = LogLevel == LogLevel.Warning ? ConsoleColor.Yellow : ConsoleColor.Red;
Console.WriteLine($"{AcEnv.NL}{logText}{AcEnv.NL}");
}
Console.ForegroundColor = ConsoleColor.White;
}
}
}

View File

@ -0,0 +1,81 @@
using System.Runtime.CompilerServices;
using AyCode.Core.Consts;
using AyCode.Core.Enums;
namespace AyCode.Core.Loggers;
public abstract class AcLogWriterBase : IAcLogWriterBase
{
public string? CategoryName { get; }
protected AppType AppType { get; set; } = AppType.Server;
protected LogLevel LogLevel { get; set; } = LogLevel.Error;
protected AcLogWriterBase() : this(null)
{}
protected AcLogWriterBase(string? categoryName = null)
{
CategoryName = categoryName;
AppType = AcEnv.AppConfiguration.GetEnum<AppType>("AyCode:Logger:AppType");
//AppType = (AppType)Enum.Parse(typeof(AppType), AcEnv.AppConfiguration["AyCode:Logger:AppType"], true);
var writerSettings = AcEnv.AppConfiguration.GetSection("AyCode:Logger:LogWriters")
.GetChildren()
.FirstOrDefault(logWriter=> (logWriter["LogWriterType"].ToLower()).Equals(this.GetType().AssemblyQualifiedName, StringComparison.CurrentCultureIgnoreCase));
LogLevel = writerSettings.GetEnum<LogLevel>("LogLevel");
}
protected AcLogWriterBase(AppType appType, LogLevel logLevel, string? categoryName = null)
{
AppType = appType;
LogLevel = logLevel;
CategoryName = categoryName;
}
public void Detail(string? text, string? categoryName = null, [CallerMemberName] string? memberName = null)
=> PrepareToWrite(LogLevel.Detail, text, memberName, categoryName ?? CategoryName);
//public void Detail<TCallerClassType>(string? text, [CallerMemberName] string? memberName = null) where TCallerClassType : class
// => Detail(text, typeof(TCallerClassType).Name, memberName);
public void Debug(string? text, string? categoryName = null, [CallerMemberName] string? memberName = null)
=> PrepareToWrite(LogLevel.Debug, text, memberName, categoryName ?? CategoryName);
//public void Debug<TCallerClassType>(string? text, [CallerMemberName] string? memberName = null) where TCallerClassType : class
// => Debug(text, typeof(TCallerClassType).Name, memberName);
public void Info(string? text, string? categoryName = null, [CallerMemberName] string? memberName = null)
=> PrepareToWrite(LogLevel.Info, text, memberName, categoryName ?? CategoryName);
//public void Info<TCallerClassType>(string? text, [CallerMemberName] string? memberName = null) where TCallerClassType : class
// => Info(text, typeof(TCallerClassType).Name, memberName);
public void Warning(string? text, string? categoryName = null, [CallerMemberName] string? memberName = null)
=> PrepareToWrite(LogLevel.Warning, text, memberName, categoryName ?? CategoryName);
//public void Warning<TCallerClassType>(string? text, [CallerMemberName] string? memberName = null) where TCallerClassType : class
// => Warning(text, typeof(TCallerClassType).Name, memberName);
public void Suggest(string? text, string? categoryName = null, [CallerMemberName] string? memberName = null)
=> PrepareToWrite(LogLevel.Suggest, text, memberName, categoryName ?? CategoryName);
//public void Suggest<TCallerClassType>(string? text, [CallerMemberName] string? memberName = null) where TCallerClassType : class
// => Suggest(text, typeof(TCallerClassType).Name, memberName);
//public void Error<TCallerClassType>(string? text, Exception? ex = null, [CallerMemberName] string? memberName = null) where TCallerClassType : class
// => Error(text, ex, typeof(TCallerClassType).Name, memberName);
public void Error(string? text, Exception? ex = null, string? categoryName = null, [CallerMemberName] string? memberName = null)
=> PrepareToWrite(LogLevel.Error, text, memberName, categoryName ?? CategoryName, ex);
protected virtual void PrepareToWrite(LogLevel logLevel, string? logText, string? callerMemberName, string? categoryName = null, Exception? ex = null)
{
throw new NotImplementedException();
}
}

View File

@ -0,0 +1,101 @@
using System.Runtime.CompilerServices;
using AyCode.Core.Consts;
using AyCode.Core.Enums;
namespace AyCode.Core.Loggers;
public abstract class AcLoggerBase : IAcLoggerBase
{
protected readonly List<IAcLogWriterBase> LogWriters = [];
public LogLevel LogLevel { get; set; } = LogLevel.Error;
public AppType AppType { get; set; } = AppType.Server;
public string? CategoryName { get; set; }
protected AcLoggerBase() : this(null)
{ }
protected AcLoggerBase(string? categoryName)
{
CategoryName = categoryName;
AppType = AcEnv.AppConfiguration.GetEnum<AppType>("AyCode:Logger:AppType");
LogLevel = AcEnv.AppConfiguration.GetEnum<LogLevel>("AyCode:Logger:LogLevel");
foreach (var logWriter in AcEnv.AppConfiguration.GetSection("AyCode:Logger:LogWriters").GetChildren())
{
var logWriterType = Type.GetType(logWriter["LogWriterType"]);
var logWriterLogLevel = logWriter.GetEnum<LogLevel>("LogLevel");
LogWriters.Add(Activator.CreateInstance(logWriterType, AppType, logWriterLogLevel, CategoryName) as IAcLogWriterBase);
}
}
protected AcLoggerBase(string? categoryName, params IAcLogWriterBase[] logWriters) :
this(AcEnv.AppConfiguration.GetEnum<AppType>("AyCode:Logger:AppType"), AcEnv.AppConfiguration.GetEnum<LogLevel>("AyCode:Logger:LogLevel"), categoryName, logWriters)
{ }
protected AcLoggerBase(AppType appType, LogLevel logLevel, string? categoryName, params IAcLogWriterBase[] logWriters)
{
AppType = appType;
LogLevel = logLevel;
CategoryName = categoryName;
foreach (var acLogWriterBase in logWriters)
LogWriters.Add(acLogWriterBase);
}
public List<IAcLogWriterBase> GetWriters => [.. LogWriters];
public TLogWriter Writer<TLogWriter>() where TLogWriter : IAcLogWriterBase => LogWriters.OfType<TLogWriter>().First();
public virtual void Detail(string? text, string? categoryName = null, [CallerMemberName] string? memberName = null)
{
if (LogLevel <= LogLevel.Detail) LogWriters.ForEach(x => x.Detail(text, categoryName ?? CategoryName, memberName));
}
//public virtual void Detail<TCallerClassType>(string? text, [CallerMemberName] string? memberName = null) where TCallerClassType : class
// => Detail(text, typeof(TCallerClassType).Name, memberName);
public virtual void Debug(string? text, string? categoryName = null, [CallerMemberName] string? memberName = null)
{
if (LogLevel <= LogLevel.Debug) LogWriters.ForEach(x => x.Debug(text, categoryName ?? CategoryName, memberName));
}
//public virtual void Debug<TCallerClassType>(string? text, [CallerMemberName] string? memberName = null) where TCallerClassType : class
// => Debug(text, typeof(TCallerClassType).Name, memberName);
public virtual void Info(string? text, string? categoryName = null, [CallerMemberName] string? memberName = null)
{
if (LogLevel <= LogLevel.Info) LogWriters.ForEach(x => x.Info(text, categoryName ?? CategoryName, memberName));
}
//public virtual void Info<TCallerClassType>(string? text, [CallerMemberName] string? memberName = null) where TCallerClassType : class
// => Info(text, typeof(TCallerClassType).Name, memberName);
public virtual void Warning(string? text, string? categoryName = null, [CallerMemberName] string? memberName = null)
{
if (LogLevel <= LogLevel.Warning) LogWriters.ForEach(x => x.Warning(text, categoryName ?? CategoryName, memberName));
}
//public virtual void Warning<TCallerClassType>(string? text, [CallerMemberName] string? memberName = null) where TCallerClassType : class
// => Warning(text, typeof(TCallerClassType).Name, memberName);
public virtual void Suggest(string? text, string? categoryName = null, [CallerMemberName] string? memberName = null)
{
if (LogLevel <= LogLevel.Suggest) LogWriters.ForEach(x => x.Suggest(text, categoryName ?? CategoryName, memberName));
}
//public virtual void Suggest<TCallerClassType>(string? text, [CallerMemberName] string? memberName = null) where TCallerClassType : class
// => Suggest(text, typeof(TCallerClassType).Name, memberName);
public virtual void Error(string? text, Exception? ex = null, string? categoryName = null, [CallerMemberName] string? memberName = null)
{
if (LogLevel <= LogLevel.Error) LogWriters.ForEach(x => x.Error(text, ex, categoryName ?? CategoryName, memberName));
}
//public virtual void Error<TCallerClassType>(string? text, Exception? ex = null, [CallerMemberName] string? memberName = null) where TCallerClassType : class
// => Error(text, ex, typeof(TCallerClassType).Name, memberName);
}

View File

@ -0,0 +1,49 @@
using AyCode.Core.Enums;
using AyCode.Utils.Extensions;
namespace AyCode.Core.Loggers;
public abstract class AcTextLogWriterBase : AcLogWriterBase
{
protected AcTextLogWriterBase() : this(null)
{ }
protected AcTextLogWriterBase(string? categoryName = null) : base(categoryName)
{ }
protected AcTextLogWriterBase(AppType appType, LogLevel logLevel, string? categoryName = null) : base(appType, logLevel, categoryName)
{ }
protected override void PrepareToWrite(LogLevel logLevel, string? logText, string? callerMemberName, string? categoryName = null, Exception? ex = null)
{
if (logLevel < LogLevel) return;
WriteText(GetDiagnosticText(logLevel, logText, callerMemberName, categoryName));
}
protected virtual void WriteText(string? logText)
{
throw new NotImplementedException();
}
protected virtual string GetDiagnosticText(LogLevel logLevel, string? logText, string? callerMemberName, string? categoryName = null, Exception? ex = null)
{
if (LogLevel > logLevel) return string.Empty;
var threadId = Environment.CurrentManagedThreadId;
if(categoryName.IsNullOrWhiteSpace()) categoryName = "...";
return $"[{DateTime.Now:HH:mm:ss.fff}] [{AppType.ToString()[0]}] {"[" + logLevel + "]",-9} {"[" + categoryName + "->" + callerMemberName + "]",-54} {"[" + threadId + "]",5} {logText}{ErrorText(ex)}";
}
protected virtual string ErrorText(Exception? ex)
{
if (ex == null) return string.Empty;
var errorType = ex.GetType().Name;
return string.IsNullOrWhiteSpace(errorType) ? string.Empty : $"{Environment.NewLine}[{errorType.ToUpper()}]: {ex}";
}
}

View File

@ -0,0 +1,26 @@
using System.Runtime.CompilerServices;
namespace AyCode.Core.Loggers;
public interface IAcLogWriterBase
{
public string? CategoryName { get; }
public void Detail(string? text, string? categoryName = null, [CallerMemberName] string? memberName = null);
//public void Detail<TCallerClassType>(string? text, [CallerMemberName] string? memberName = null) where TCallerClassType : class;
public void Debug(string? text, string? categoryName = null, [CallerMemberName] string? memberName = null);
//public void Debug<TCallerClassType>(string? text, [CallerMemberName] string? memberName = null) where TCallerClassType : class;
public void Info(string? text, string? categoryName = null, [CallerMemberName] string? memberName = null);
//public void Info<TCallerClassType>(string? text, [CallerMemberName] string? memberName = null) where TCallerClassType : class;
public void Warning(string? text, string? categoryName = null, [CallerMemberName] string? memberName = null);
//public void Warning<TCallerClassType>(string? text, [CallerMemberName] string? memberName = null) where TCallerClassType : class;
public void Suggest(string? text, string? categoryName = null, [CallerMemberName] string? memberName = null);
//public void Suggest<TCallerClassType>(string? text, [CallerMemberName] string? memberName = null) where TCallerClassType : class;
public void Error(string? text, Exception? ex = null, string? categoryName = null, [CallerMemberName] string? memberName = null);
//public void Error<TCallerClassType>(string? text, Exception? ex = null, [CallerMemberName] string? memberName = null) where TCallerClassType : class;
}

View File

@ -0,0 +1,7 @@
namespace AyCode.Core.Loggers;
public interface IAcLoggerBase : IAcLogWriterBase
{
public List<IAcLogWriterBase> GetWriters { get; }
public TLogWriter Writer<TLogWriter>() where TLogWriter : IAcLogWriterBase;
}

View File

@ -1,4 +1,4 @@
namespace AyCode.Core.Logger namespace AyCode.Core.Loggers
{ {
/// <summary> /// <summary>
/// Az adatbásisban van egy LogLevel tábla, ha változtatunk az enum-ok értékén, akkor ott is igazítsuk hozzá! /// Az adatbásisban van egy LogLevel tábla, ha változtatunk az enum-ok értékén, akkor ott is igazítsuk hozzá!

View File

@ -0,0 +1,57 @@
using AyCode.Core.Consts;
using AyCode.Core.Enums;
using AyCode.Core.Helpers;
using AyCode.Core.Loggers;
using AyCode.Database.DbContexts.Loggers;
using AyCode.Entities;
using AyCode.Entities.LogItems;
using AyCode.Interfaces.Entities;
namespace AyCode.Database;
public class AcDbLogItemWriter<TLoggerDbContext, TLogItem> : AcLogItemWriterBase<TLogItem> where TLoggerDbContext : AcLoggerDbContextBase<TLogItem>
where TLogItem : class, IAcLogItem
{
private TLoggerDbContext _ctx = Activator.CreateInstance<TLoggerDbContext>();
protected AcDbLogItemWriter() : this(null)
{ }
protected AcDbLogItemWriter(string? categoryName = null) : base(categoryName)
{ }
public AcDbLogItemWriter(AppType appType, LogLevel logLevel, string? categoryName = null) : base(appType, logLevel, categoryName)
{ }
protected override void WriteLogItem(TLogItem logItem, Action? callback = null)
{
try
{
base.WriteLogItem(logItem, () =>
{
_ctx.LogItems.Add(logItem);
_ctx.SaveChanges();
});
}
catch (Exception ex)
{
Console.WriteLine("ERRORORROROR! " + AcEnv.NL + ex.Message);
}
}
//protected override void WriteLogItem(TLogItem logItem, Action<IEnumerable<TLogItem>>? callback = null)
//{
// try
// {
// base.WriteLogItem(logItem, logItems =>
// {
// _ctx.LogItems.AddRange(logItems);
// _ctx.SaveChanges();
// });
// }
// catch (Exception ex)
// {
// Console.WriteLine("ERRORORRORO");
// }
//}
}

View File

@ -26,6 +26,7 @@
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Folder Include="DbSets\Loggers\" />
<Folder Include="SqlScripts\" /> <Folder Include="SqlScripts\" />
</ItemGroup> </ItemGroup>

View File

@ -11,6 +11,8 @@ using Microsoft.EntityFrameworkCore;
using AyCode.Database.Extensions; using AyCode.Database.Extensions;
using AyCode.Core.Consts; using AyCode.Core.Consts;
using AyCode.Core.Helpers; using AyCode.Core.Helpers;
using AyCode.Core.Loggers;
using AyCode.Core.Server.Loggers;
using AyCode.Database.DbSets.Users; using AyCode.Database.DbSets.Users;
using AyCode.Interfaces.Addresses; using AyCode.Interfaces.Addresses;
using AyCode.Interfaces.Messages; using AyCode.Interfaces.Messages;
@ -141,6 +143,7 @@ namespace AyCode.Database.DataLayers.Users
} }
catch (Exception ex) catch (Exception ex)
{ {
GlobalLogger.Error(ex.Message, ex);
errorCodeInner = AcErrorCode.UnknownError; errorCodeInner = AcErrorCode.UnknownError;
} }

View File

@ -0,0 +1,11 @@
using AyCode.Database.DbSets.Loggers;
using AyCode.Entities.LogItems;
using AyCode.Interfaces.Entities;
using Microsoft.EntityFrameworkCore;
namespace AyCode.Database.DbContexts.Loggers;
public class AcLoggerDbContextBase<TLogItem> : AcDbContextBase, IAcLoggerDbContextBase<TLogItem> where TLogItem : class, IAcLogItem
{
public DbSet<TLogItem> LogItems { get; set; }
}

View File

@ -0,0 +1,10 @@
using AyCode.Database.DbSets.Loggers;
using AyCode.Entities.LogItems;
using AyCode.Interfaces.Entities;
namespace AyCode.Database.DbContexts.Loggers;
public interface IAcLoggerDbContextBase<TLogItem> : IAcLogItemDbSetBase<TLogItem> where TLogItem : class, IAcLogItem
{
}

View File

@ -0,0 +1,11 @@
using AyCode.Entities.LogItems;
using AyCode.Interfaces.Entities;
using AyCode.Interfaces.Users;
using Microsoft.EntityFrameworkCore;
namespace AyCode.Database.DbSets.Loggers;
public interface IAcLogItemDbSetBase<TLogItem> where TLogItem : class, IAcLogItem
{
DbSet<TLogItem> LogItems { get; set; }
}

View File

@ -1,5 +1,6 @@
using AyCode.Core.Extensions; using AyCode.Core.Extensions;
using AyCode.Core.Logger; using AyCode.Core.Loggers;
using AyCode.Core.Server.Loggers;
using AyCode.Database.Extensions; using AyCode.Database.Extensions;
using AyCode.Entities; using AyCode.Entities;
using AyCode.Entities.Users; using AyCode.Entities.Users;
@ -45,7 +46,7 @@ public static class AcUserDbSetExtensions
public static IQueryable<TUser>? GetQueryableUserByEmail<TUser>(this IAcUserDbSetBase<TUser> ctx, string? email, bool onlyConfirmed) where TUser : class, IAcUserBase public static IQueryable<TUser>? GetQueryableUserByEmail<TUser>(this IAcUserDbSetBase<TUser> ctx, string? email, bool onlyConfirmed) where TUser : class, IAcUserBase
{ {
Logger.Info($"GetUserByEmail: {email}"); GlobalLogger.Info($"GetUserByEmail: {email}");
if (string.IsNullOrWhiteSpace(email)) return null; if (string.IsNullOrWhiteSpace(email)) return null;
@ -57,7 +58,7 @@ public static class AcUserDbSetExtensions
{ {
var emailLower = user.EmailAddress.ToLower(); var emailLower = user.EmailAddress.ToLower();
Logger.Info($"GetUserByEmail: {emailLower}"); GlobalLogger.Info($"GetUserByEmail: {emailLower}");
return ctx.Users.Add(user).State == Microsoft.EntityFrameworkCore.EntityState.Added; return ctx.Users.Add(user).State == Microsoft.EntityFrameworkCore.EntityState.Added;
} }
@ -86,7 +87,7 @@ public static class AcUserDbSetExtensions
public static TUser? UpdateJwtRefreshToken<TUser>(this IAcUserDbSetBase<TUser> ctx, string email, string refreshToken) where TUser : class, IAcUserBase public static TUser? UpdateJwtRefreshToken<TUser>(this IAcUserDbSetBase<TUser> ctx, string email, string refreshToken) where TUser : class, IAcUserBase
{ {
Console.WriteLine(@"UserDal Update refresh token"); GlobalLogger.Info(@"UserDal Update refresh token");
if (string.IsNullOrWhiteSpace(refreshToken)) return null; if (string.IsNullOrWhiteSpace(refreshToken)) return null;

View File

@ -1,6 +1,7 @@
using AyCode.Core.Consts; using AyCode.Core.Consts;
using AyCode.Core.Helpers; using AyCode.Core.Helpers;
using AyCode.Core.Logger; using AyCode.Core.Loggers;
using AyCode.Core.Server.Loggers;
using AyCode.Database.DbContexts; using AyCode.Database.DbContexts;
using AyCode.Interfaces.Entities; using AyCode.Interfaces.Entities;
@ -22,7 +23,7 @@ public static class AcDbSessionExtension
catch (Exception ex) catch (Exception ex)
{ {
var errorText = $"Session({ctx}) callback error...{AcEnv.NL}"; var errorText = $"Session({ctx}) callback error...{AcEnv.NL}";
Logger.Error($"{errorText}", ex); GlobalLogger.Error($"{errorText}", ex);
throw new Exception($"{errorText}{ex}"); throw new Exception($"{errorText}{ex}");
} }

View File

@ -2,8 +2,9 @@
using Microsoft.EntityFrameworkCore.Storage; using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using AyCode.Database.DbContexts; using AyCode.Database.DbContexts;
using AyCode.Core.Logger;
using AyCode.Core.Consts; using AyCode.Core.Consts;
using AyCode.Core.Loggers;
using AyCode.Core.Server.Loggers;
namespace AyCode.Database.Extensions; namespace AyCode.Database.Extensions;
@ -45,7 +46,7 @@ public static class AcDbTransactionExtension
transaction.Rollback(); transaction.Rollback();
if (throwException) throw new Exception(errorText, ex); if (throwException) throw new Exception(errorText, ex);
Logger.Error($"{errorText}", ex); GlobalLogger.Error($"{errorText}", ex);
} }
return result; return result;
} }
@ -65,7 +66,7 @@ public static class AcDbTransactionExtension
else else
{ {
transaction.Rollback(); transaction.Rollback();
Logger.Warning($"Transaction({ctx}) transaction ROLLBACK!"); GlobalLogger.Warning($"Transaction({ctx}) transaction ROLLBACK!");
} }
} }
catch (Exception ex) catch (Exception ex)
@ -73,7 +74,7 @@ public static class AcDbTransactionExtension
if (throwException) throw; if (throwException) throw;
result = false; result = false;
Logger.Error($"Transaction({ctx}) transaction error...{AcEnv.NL}", ex); GlobalLogger.Error($"Transaction({ctx}) transaction error...{AcEnv.NL}", ex);
} }
finally finally
{ {

View File

@ -0,0 +1,89 @@
using AyCode.Core.Enums;
using AyCode.Core.Helpers;
using AyCode.Core.Loggers;
using AyCode.Entities.LogItems;
using AyCode.Interfaces.Entities;
using AyCode.Utils.Extensions;
using System.Collections.Concurrent;
namespace AyCode.Entities;
public abstract class AcLogItemWriterBase<TLogItem> : AcLogWriterBase where TLogItem : class, IAcLogItem
{
protected readonly Mutex MutexLock = new();//new(false, "GLOBAL");
protected AcLogItemWriterBase() : this(null)
{ }
protected AcLogItemWriterBase(string? categoryName = null) : base(categoryName)
{ }
protected AcLogItemWriterBase(AppType appType, LogLevel logLevel, string? categoryName = null) : base(appType, logLevel, categoryName)
{
}
protected TLogItem CreateLogItem(int threadId, DateTime utcNow, LogLevel logLevel, string? logText, string? callerMemberName, string? categoryName = null, Exception? ex = null)
{
var logItem = Activator.CreateInstance<TLogItem>();
logItem.TimeStampUtc = utcNow;
logItem.AppType = AppType;
logItem.LogLevel = logLevel;
logItem.CategoryName = categoryName;
logItem.CallerName = callerMemberName;
logItem.Text = logText;
logItem.Exception = ex?.Message;
logItem.ThreadId = threadId;
return logItem;
}
protected override void PrepareToWrite(LogLevel logLevel, string? logText, string? callerMemberName, string? categoryName = null, Exception? ex = null)
{
if (logLevel < LogLevel) return;
var utcNow = DateTime.UtcNow;
var threadId = Environment.CurrentManagedThreadId;
TaskHelper.RunOnThreadPool(() => WriteLogItem(CreateLogItem(threadId, utcNow, logLevel, logText, callerMemberName, categoryName)));
}
protected virtual void WriteLogItem(TLogItem logItem, Action? callback = null)
{
using (MutexLock.UseWaitOne())
{
callback?.Invoke();
}
}
//private volatile bool _isLocked = false;
//private readonly object _forLock = new();
//private readonly List<TLogItem> _logItemsCahce = new();
//private readonly List<TLogItem> _logItemsCahce2 = new();
//protected virtual void WriteLogItem(TLogItem logItem, Action<IEnumerable<TLogItem>>? callback = null)
//{
// lock (_forLock) _logItemsCahce.Add(logItem);
// if (_isLocked) return;
// using (MutexLock.UseWaitOne())
// {
// _isLocked = true;
// _logItemsCahce2.Clear();
// lock (_forLock)
// {
// _logItemsCahce2.AddRange(_logItemsCahce);
// _logItemsCahce.Clear();
// }
// callback?.Invoke(_logItemsCahce2);
// }
// _isLocked = false;
//}
}

View File

@ -12,6 +12,7 @@
<ItemGroup> <ItemGroup>
<Folder Include="Messages\" /> <Folder Include="Messages\" />
<Folder Include="LogItems\" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -0,0 +1,24 @@
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using AyCode.Core.Enums;
using AyCode.Core.Interfaces;
using AyCode.Core.Loggers;
namespace AyCode.Entities.LogItems;
[Table("LogItem")]
public class AcLogItem : IAcLogItem
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public int LogHeaderId { get; set; }
public DateTime TimeStampUtc { get; set; }
public AppType AppType { get; set; }
public LogLevel LogLevel { get; set; }
public int ThreadId { get; set; }
public string? CategoryName { get; set; }
public string? CallerName { get; set; }
public string? Text { get; set; }
public string? Exception { get; set; }
}

View File

@ -0,0 +1,18 @@
using AyCode.Core.Enums;
using AyCode.Core.Loggers;
using AyCode.Interfaces.Entities;
namespace AyCode.Entities.LogItems;
public interface IAcLogItem : IEntityInt
{
public int LogHeaderId { get; set; }
public DateTime TimeStampUtc { get; set; }
public AppType AppType { get; set; }
public LogLevel LogLevel { get; set; }
public int ThreadId { get; set; }
public string? CategoryName { get; set; }
public string? CallerName { get; set; }
public string? Text { get; set; }
public string? Exception { get; set; }
}

View File

@ -19,7 +19,7 @@ public class AcEmailServiceServer() : IAcEmailServiceServer
_sendGridClient = new SendGridClient(configuration["SendGrid:Key"]); _sendGridClient = new SendGridClient(configuration["SendGrid:Key"]);
_fromEmailAddress = new EmailAddress(configuration["SendGrid:FromEmail"], configuration["SendGrid:FromName"]); _fromEmailAddress = new EmailAddress(configuration["SendGrid:FromEmail"], configuration["SendGrid:FromName"]);
//Console.WriteLine($"{config.ServerUserName}; {config.FromEmail}; {config.FromName}"); //Logger.Info($"{config.ServerUserName}; {config.FromEmail}; {config.FromName}");
} }
public async Task<Response> SendLostPasswordEmailAsync(string addressEmail, string verificationToken) public async Task<Response> SendLostPasswordEmailAsync(string addressEmail, string verificationToken)

View File

@ -18,6 +18,8 @@ using Microsoft.EntityFrameworkCore;
using AyCode.Database.DbContexts; using AyCode.Database.DbContexts;
using AyCode.Core.Consts; using AyCode.Core.Consts;
using AyCode.Core.Extensions; using AyCode.Core.Extensions;
using AyCode.Core.Loggers;
using AyCode.Core.Server.Loggers;
using AyCode.Database.DataLayers.Users; using AyCode.Database.DataLayers.Users;
using AyCode.Database.DbContexts.Users; using AyCode.Database.DbContexts.Users;
using AyCode.Interfaces.Messages; using AyCode.Interfaces.Messages;
@ -124,13 +126,13 @@ public class AcLoginServiceServer<TResultLoggedInModel, TDal, TDbContext, TUser,
public string GenerateAccessToken(TUser user) public string GenerateAccessToken(TUser user)
{ {
var tokenHandler = new JwtSecurityTokenHandler(); var tokenHandler = new JwtSecurityTokenHandler();
Console.WriteLine("----------------------------------------------------------"); GlobalLogger.Info("----------------------------------------------------------");
if (configuration["JWT:Key"] == null) if (configuration["JWT:Key"] == null)
throw new SecurityTokenException("Token is null"); throw new SecurityTokenException("Token is null");
var keyDetail = Encoding.UTF8.GetBytes(configuration["JWT:Key"] ?? string.Empty); var keyDetail = Encoding.UTF8.GetBytes(configuration["JWT:Key"] ?? string.Empty);
Console.WriteLine(configuration["JWT:Key"]); GlobalLogger.Info(configuration["JWT:Key"]);
var claims = new List<Claim> var claims = new List<Claim>
{ {
@ -149,7 +151,7 @@ public class AcLoginServiceServer<TResultLoggedInModel, TDal, TDbContext, TUser,
var token = tokenHandler.CreateToken(tokenDescriptor) as JwtSecurityToken; var token = tokenHandler.CreateToken(tokenDescriptor) as JwtSecurityToken;
var writtenToken = tokenHandler.WriteToken(token); var writtenToken = tokenHandler.WriteToken(token);
Console.WriteLine(writtenToken); GlobalLogger.Info(writtenToken);
return writtenToken; return writtenToken;
} }

View File

@ -0,0 +1,54 @@
using AyCode.Core.Enums;
using AyCode.Core.Loggers;
using AyCode.Entities;
using AyCode.Entities.LogItems;
using AyCode.Interfaces.Entities;
using static System.Net.WebRequestMethods;
using System;
namespace AyCode.Services.Loggers;
public abstract class AcHttpClientLogItemWriter<TLogItem> : AcLogItemWriterBase<TLogItem> where TLogItem : class, IAcLogItem
{
protected HttpClient _httpClient;
protected readonly HttpClientHandler _httpClientHandler;
protected AcHttpClientLogItemWriter(HttpClient httpClient) : base(AppType.Web, LogLevel.Detail)
{
_httpClient = httpClient;
}
protected AcHttpClientLogItemWriter(string? categoryName = null) : base(categoryName)
{
_httpClientHandler = new HttpClientHandler();
_httpClient = new HttpClient(_httpClientHandler, false);
}
protected AcHttpClientLogItemWriter(AppType appType, LogLevel logLevel, string? categoryName = null) : base(appType, logLevel, categoryName)
{
_httpClientHandler = new HttpClientHandler();
_httpClient = new HttpClient(_httpClientHandler, false);
}
//protected override void WriteLogItem(TLogItem logItem, Action? callback = null)
//{
// //throw new NotImplementedException();
// base.WriteLogItem(logItem, () =>
// {
// //http.PostAsJson(url, Param);
// //_httpClient.Send()
// });
//}
//protected override void WriteLogItem(TLogItem logItem, Action<IEnumerable<TLogItem>>? callback = null)
//{
// throw new NotImplementedException();
// base.WriteLogItem(logItem, logItems =>
// {
// //_httpClient.Send()
// });
//}
}