
### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xLoggingService\Background\XLogDispatcher.cs

using System;
using System.Threading;
using System.Threading.Tasks;
using xLoggingService.Models;
using xLoggingService.Interfaces;
using System.Collections.Generic;
using System.Collections.Concurrent;

namespace xLoggingService.Background
{
    public sealed class XLogDispatcher : IDisposable
    {
        private readonly Task worker;
        private readonly BlockingCollection<XLogEntry> queue;
        private readonly IReadOnlyCollection<IXLogWriter> writers;
        private readonly CancellationTokenSource cancellation = new CancellationTokenSource();

        public XLogDispatcher(
            int capacity,
            IEnumerable<IXLogWriter> writers
        )
        {
            //
            queue = new BlockingCollection<XLogEntry>(Math.Max(100, capacity));
            this.writers = new List<IXLogWriter>(writers)
                .AsReadOnly();

            //
            worker = Task.Run(RunAsync);
        }

        public void Enqueue(XLogEntry entry)
        {
            if (!queue.IsAddingCompleted && !queue.TryAdd(entry)) { }
        }

        private async Task RunAsync()
        {
            //
            try
            {
                //
                foreach (var entry in queue.GetConsumingEnumerable(cancellation.Token))
                {
                    //
                    foreach (var writer in writers)
                    {
                        //
                        try
                        {
                            //
                            await writer.WriteAsync(entry, cancellation.Token)
                                .ConfigureAwait(false);
                        }
                        catch { }
                    }
                }
            }
            catch (OperationCanceledException) { }
        }

        public void Dispose()
        {
            //
            queue.CompleteAdding();

            //
            try
            {
                worker.Wait(TimeSpan.FromSeconds(10));
            }
            catch { }

            // 
            cancellation.Cancel();
            queue.Dispose();
            cancellation.Dispose();
        }
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xLoggingService\Configuration\XLoggingServiceConfiguration.cs

using Microsoft.Extensions.Logging;

namespace xLoggingService.Configuration
{
    public sealed class XLoggingServiceConfiguration
    {
        public bool Enabled { get; set; } = false;
        public XFileLogConfiguration File { get; set; } = new();
        public XLogQueueConfiguration Queue { get; set; } = new();
        public XEventLogConfiguration Event { get; set; } = new();
        public XDatabaseLogConfiguration Database { get; set; } = new();
        public LogLevel MinimumLevel { get; set; } = LogLevel.Information;
    }
    
    public class XLogQueueConfiguration { 
        public bool Enabled { get; set; } 
        public int Capacity { get; set; } = 10000; 
        public int ShutdownTimeoutSeconds { get; set; } = 10; 
    }

    public class XFileLogConfiguration { 
        public bool Enabled { get; set; } 
        public string Format { get; set; } = "Json"; 
        public string Directory { get; set; } = "./Logs"; 
        public int RetainedFileCountLimit { get; set; } = 30; 
        public string FileName { get; set; } = "x-logging-.log"; 
        public LogLevel MinimumLevel { get; set; } = LogLevel.Information; 
    }
    
    public class XDatabaseLogConfiguration { 
        public bool Enabled { get; set; } = false; 
        public string ConnectionString { get; set; } 
        public string TableName { get; set; } = "XLogs"; 
        public bool AutoCreateTable { get; set; } = true; 
        public LogLevel MinimumLevel { get; set; } = LogLevel.Warning; 
        public string Provider { get; set; } = "Microsoft.Data.Sqlite"; 
    }
    
    public class XEventLogConfiguration { 
        public bool Enabled { get; set; } = false; 
        public string Sender { get; set; } = "Application"; 
        public string Action { get; set; } = "XLogCreated"; 
        public LogLevel MinimumLevel { get; set; } = LogLevel.Error; 
        public string Topic { get; set; } = "x-logging-service-logs"; 
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xLoggingService\Constants\ConfigurationNodeNames.cs

namespace xLoggingService.Constants
{
    public partial struct ConfigurationNodeNames
    {
        public const string LOGGING_SERVICE_NODE = "LoggingServiceConfiguration";
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xLoggingService\Constants\XLoggingServiceConstants.cs

namespace xLoggingService.Constants
{
    public struct XLoggingServiceConstants
    {
        //
        // Service Extensions Log Tag ...
        public const string XLoggingServiceDILogTag = "XLoggingService";
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xLoggingService\DI\XDIHelperExtension.cs

using System;
using OpenTelemetry.Logs;
using OpenTelemetry.Trace;
using xCommons.Extensions;
using xExceptions.Constants;
using OpenTelemetry.Resources;
using xLoggingService.Writers;
using xEventService.Interfaces;
using xLoggingService.Providers;
using xLoggingService.Constants;
using xLoggingService.Interfaces;
using xLoggingService.MIddlewares;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Hosting;
using Microsoft.AspNetCore.Builder;
using xLoggingService.Configuration;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;

namespace xLoggingService.DI
{
    public static class XDIHelperExtension
    {
        /// <summary>
        /// Retrieve Logging Service Configuration ...
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static XLoggingServiceConfiguration GetXLoggingServiceConfiguration(
            this IConfiguration source
        )
        {
            //
            var section = source
                .GetSection(ConfigurationNodeNames.LOGGING_SERVICE_NODE);

            //
            var result = section.Get<XLoggingServiceConfiguration>();
            if (result.IsNull())
            {
                result = new();
            }

            //
            return result;
        }

        /// <summary>
        /// Extract Service Configurations and Register it ...
        /// </summary>
        /// <param name="source"></param>
        /// <param name="configuration"></param>
        public static void AddXLoggingServiceConfiguration(
            this IServiceCollection source,
            IConfiguration configuration
        )
        {
            //
            var config = configuration.GetXLoggingServiceConfiguration();
            source.AddXLoggingServiceConfiguration(config);
        }

        /// <summary>
        /// Register Service Configuration ...
        /// </summary>
        /// <param name="source"></param>
        /// <param name="configuration"></param>
        public static void AddXLoggingServiceConfiguration(
            this IServiceCollection source,
            XLoggingServiceConfiguration configuration
        )
        {
            //
            if (configuration.IsNull())
            {
                //
                Log($"Invalid Configuration ...");
                XException.InvalidConfiguration.Throw();
            }

            //
            source.AddSingleton(configuration);
            Log($"Logging Configuration Registered Successfully ...");
        }

        /// <summary>
        /// Register Logging Service ...
        /// </summary>
        /// <param name="source"></param>
        /// <param name="configuration"></param>
        public static void AddXLoggingService(
            this IServiceCollection source,
            IConfiguration configuration
        )
        {
            //
            var config = configuration.GetXLoggingServiceConfiguration();
            source.AddLoggingService(
                configuration: config,
                lifeTime: ServiceLifetime.Scoped
            );
        }

        /// <summary>
        /// Enable Telemetry Service on Logging ...
        /// </summary>
        /// <param name="builder"></param>
        public static void AddXTelemetryLogger(
            this ILoggingBuilder builder
        )
        {
            //
            AppContext.SetSwitch(
                "System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);

            //
            // Clear Providers ...
            builder.ClearProviders();
            builder.AddConsole();
            builder.AddOpenTelemetry(options =>
            {
                //
                options.SetResourceBuilder(
                    ResourceBuilder
                        .CreateDefault()
                        .AddService(nameof(xLoggingService)));

                //
                options.AddOtlpExporter();
            });            
        }

        /// <summary>
        /// Add Telemetry Service to Services ...
        /// </summary>
        /// <param name="builder"></param>
        /// <returns></returns>
        public static IHostBuilder AddXTelemetry(
            this IHostBuilder builder            
        )
        {
            //
            // Configure Services ...
            builder = builder
                .ConfigureServices((hostContext, services) =>
                {
                    //
                    services
                        .AddOpenTelemetry()
                        .ConfigureResource(resource =>
                            resource.AddService(nameof(xLoggingService)))
                        .WithTracing(tracing =>
                            tracing
                                .AddAspNetCoreInstrumentation()
                                .AddHttpClientInstrumentation()
                                .AddOtlpExporter());
                });

            //
            return builder;
        }

        /// <summary>
        /// Use Request Logging Middleware ...
        /// Log all Requests, and it's Flow to Logger ...
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseXRequestLogger(
            this IApplicationBuilder source
        )
        {
            return source.UseMiddleware<XRequestLoggingMiddleware>();
        }

        //
        #region Private 
        /// <summary>
        /// a LogTag for Service ...
        /// </summary>
        private static string XLogTag = XLoggingServiceConstants.XLoggingServiceDILogTag;

        /// <summary>
        /// print a log in Console ...
        /// </summary>
        /// <param name="message"></param>
        private static void Log(string message)
        {
            Console.WriteLine($"{XLogTag} => {message}");
        }

        /// <summary>
        /// Register Logging Service ...
        /// </summary>
        /// <param name="services"></param>
        /// <param name="configuration"></param>
        /// <param name="lifeTime"></param>
        private static void AddLoggingService(
            this IServiceCollection services,
            XLoggingServiceConfiguration configuration,
            ServiceLifetime lifeTime = ServiceLifetime.Scoped
        )
        {
            //
            // Validate ...
            if (lifeTime.IsNull())
            {
                //
                Log($"Invalid Service Lifetime ...");
                XException.InvalidArgs.Throw();
            }

            //
            // Register Service Configuration ...
            services.AddXLoggingServiceConfiguration(configuration);

            //
            // File Log Provider ...
            if (configuration.File.Enabled)
            {
                //
                services.TryAddEnumerable(
                    ServiceDescriptor.Singleton<IXLogWriter, XFileLogWriter>());

                //
                Log("FileLogWriter registered.");
            }

            //
            // Database Log Provider ...
            if (configuration.Database.Enabled)
            {
                //
                services.TryAddEnumerable(
                    ServiceDescriptor.Singleton<IXLogWriter, XDatabaseLogWriter>());

                //
                Log("DatabaseLogWriter registered.");
            }

            //
            // Event Service Provider ...
            if (configuration.Event.Enabled)
            {
                //
                var eventService = services.GetRegisteredService<IXEventServiceProvider>();
                if (eventService.IsNull())
                {
                    //
                    Log("Event Service not Provided ...");
                    XException.InvalidConfiguration.Throw();
                }

                //
                services.TryAddEnumerable(
                    ServiceDescriptor.Singleton<IXLogWriter, XEventLogWriter>());

                //
                Log("EventLogWriter registered.");
            }

            //
            services.TryAddEnumerable(
                ServiceDescriptor.Singleton<ILoggerProvider, XLoggerProvider>());

            //
            Log($"Logging Service registered successfully ...");
        }
        #endregion
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xLoggingService\Extensions\XLoggingServiceExtensions.cs

using xCommons.Extensions;
using xLoggingService.Models;
using xCommons.Configurations;

namespace xLoggingService.Extensions
{
    public static class XLoggingServiceExtensions
    {
        /// <summary>
        /// Enrich LogEntry ...
        /// </summary>
        /// <param name="source"></param>
        /// <param name="configuration"></param>
        /// <returns></returns>
        public static XLogEntry Enrich(
            this XLogEntry source,
            XAppConfiguration configuration
        )
        {
            //
            if (source.IsNull() || configuration.IsNull())
            {
                return source;
            }

            //
            source.Application = configuration.Name;

            //
            return source;
        }
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xLoggingService\Interfaces\IXLogWriter.cs

using System.Threading;
using System.Threading.Tasks;
using xLoggingService.Models;

namespace xLoggingService.Interfaces
{
    public interface IXLogWriter
    {
        /// <summary>
        /// Write Log ...
        /// </summary>
        /// <param name="entry"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        Task WriteAsync(
            XLogEntry entry,
            CancellationToken cancellationToken
        );
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xLoggingService\MIddlewares\XRequestLoggingMiddleware.cs

using System;
using System.IO;
using xCommons.Models;
using System.Diagnostics;
using xCommons.Extensions;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace xLoggingService.MIddlewares
{
    public class XRequestLoggingMiddleware
    {
        //
        private readonly RequestDelegate next;
        private readonly bool useSimpleLogging = false;
        private readonly ILogger<XRequestLoggingMiddleware> logger;

        public XRequestLoggingMiddleware(
            RequestDelegate next,
            ILogger<XRequestLoggingMiddleware> logger
        )
        {
            //
            this.next = next;
            this.logger = logger;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            //
            if (useSimpleLogging)
            {
                await InvokeAsyncSimple(context);
            }
            else
            {
                await InvokeAsyncFull(context);
            }
        }

        public async Task InvokeAsyncSimple(HttpContext context)
        {
            //
            var stopwatch = Stopwatch.StartNew();
            try
            {
                //
                // Logging Request Start ...
                logger.LogInformation(
                    "Handling request: {Method} {Path}",
                    context.Request.Method,
                    context.Request.Path
                );

                //
                // Handling Request ...
                await next(context);

                //
                // Logging Request End ...
                stopwatch.Stop();
                logger.LogInformation(
                    "Finished handling request: {Method} {Path} in {Elapsed}ms",
                    context.Request.Method,
                    context.Request.Path,
                    stopwatch.ElapsedMilliseconds
                );
            }
            catch (Exception ex)
            {
                //
                // Logging Request Error ...
                stopwatch.Stop();
                logger.LogError(ex,
                    "Request failed: {Method} {Path} after {Elapsed}ms",
                    context.Request.Method,
                    context.Request.Path,
                    stopwatch.ElapsedMilliseconds
                );

                //
                // Throw Exception Agains for Handling using Top Level Middlewares ...
                throw;
            }
        }

        public async Task InvokeAsyncFull(HttpContext context)
        {
            //
            var stopwatch = Stopwatch.StartNew();
            try
            {
                //
                // Logging Request Start ...
                logger.LogInformation(
                    "Handling request: {Method} {Path}",
                    context.Request.Method,
                    context.Request.Path
                );

                //
                var logModel = new XLoggerModel();

                //
                logModel.Path = context.Request.Path;
                logModel.Schema = context.Request.Scheme;
                logModel.Method = context.Request.Method;
                logModel.Headers = context.Request.Headers;
                logModel.Host = context.Request.Host.ToString();
                logModel.QueryString = context.Request.QueryString.ToString();
                logModel.UserID = context.User.Identity.IsAuthenticated ? context.User.Identity.Name : "Not Authenticated";

                //
                logModel.Connection = new XLoggerHttpConnection
                {
                    Id = context.Connection.Id,
                    RemoteIpAddress = context.Connection.RemoteIpAddress.ToString(),
                    RemotePort = context.Connection.RemotePort.ToString(),
                    LocalIpAddress = context.Connection.LocalIpAddress.ToString(),
                    LocalPort = context.Connection.LocalPort.ToString(),
                };

                //
                // Check if a request is a Post Call so read data from Body ...
                if (context.Request.Method.ToNormalString() == "post")
                {
                    //
                    context.Request.EnableBuffering();
                    var request = await new StreamReader(context.Request.Body)
                        .ReadToEndAsync();

                    //
                    context.Request.Body.Position = 0;
                    logModel.Request = request;
                }

                //
                logModel.RequestedOn = DateTime.UtcNow;

                //
                // Do Request ...
                await next.Invoke(context);

                //
                using (Stream originalRequest = context.Response.Body)
                {
                    try
                    {
                        //
                        using (var memStream = new MemoryStream())
                        {
                            //
                            context.Response.Body = memStream;

                            //
                            // All the Request processing as described above 
                            // happens from here.
                            // Response handling starts from here
                            // set the pointer to the beginning of the 
                            // memory stream to read
                            memStream.Position = 0;

                            //
                            // read the memory stream till the end
                            var response = await new StreamReader(memStream)
                                .ReadToEndAsync();

                            //
                            logModel.Response = response;
                            logModel.RespondedOn = DateTime.UtcNow;
                            logModel.StatusCode = context.Response.StatusCode;
                            logModel.IsSucceed = context.Response.StatusCode >= 200 && context.Response.StatusCode <= 299;

                            //
                            // since we have read till the end of the stream, 
                            // reset it onto the first position
                            memStream.Position = 0;

                            //
                            // now copy the content of the temporary memory 
                            // stream we have passed to the actual response body 
                            // which will carry the response out.
                            await memStream.CopyToAsync(originalRequest);
                        }
                    }
                    catch (Exception ex)
                    {
                        //
                        // Log Exception ...
                        logModel.Exception = ex;
                        logger.LogError($"Error on Logging Request/Response ... {ex.ToJSON()}");
                    }
                    finally
                    {
                        //
                        // assign the response body to the actual context
                        logModel.RespondedOn = DateTime.UtcNow;
                        context.Response.Body = originalRequest;
                    }
                }

                //
                // Logging Request End ...
                stopwatch.Stop();
                logger.LogInformation(
                    "Finished handling request: {Method} {Path} in {Elapsed}ms",
                    context.Request.Method,
                    context.Request.Path,
                    stopwatch.ElapsedMilliseconds
                );

                //
                // Log Response ...
                logger.LogCritical($"Http Response/Response Information:{Environment.NewLine}" +
                    $"Schema:{logModel.Schema} " + Environment.NewLine +
                    $"Host: {logModel.Host} " + Environment.NewLine +
                    $"Path: {logModel.Path} " + Environment.NewLine +
                    $"Method: {logModel.Method} " + Environment.NewLine +
                    $"UserID: {logModel.UserID} " + Environment.NewLine +
                    $"QueryString: {context.Request.QueryString} " + Environment.NewLine +
                    $"Headers: {logModel.Headers.ToJSON()}" + Environment.NewLine +
                    $"" + Environment.NewLine +
                    $"Http Connection: " + Environment.NewLine +
                    $"Id: {logModel.Connection.Id}" + Environment.NewLine +
                    $"RemoteIpAddress: {logModel.Connection.RemoteIpAddress}" + Environment.NewLine +
                    $"RemotePort: {logModel.Connection.RemotePort}" + Environment.NewLine +
                    $"LocalIpAddress: {logModel.Connection.LocalIpAddress}" + Environment.NewLine +
                    $"LocalPort: {logModel.Connection.LocalPort}" + Environment.NewLine +
                    $"" + Environment.NewLine +
                    $"Request Body: {logModel.Request}" + Environment.NewLine +
                    $"RequestedOn: {logModel.RequestedOn}" + Environment.NewLine +
                    $"" + Environment.NewLine +
                    $"IsSucceed: {logModel.IsSucceed}" + Environment.NewLine +
                    $"StatucCode: {logModel.StatusCode}" + Environment.NewLine +
                    $"Response Body: {logModel.Response}" + Environment.NewLine +
                    $"RespondedOn: {logModel.RespondedOn}" + Environment.NewLine +
                    $"" + Environment.NewLine
                );
            }
            catch (Exception ex)
            {
                //
                // Logging Request Error ...
                stopwatch.Stop();
                logger.LogError(ex,
                    "Request failed: {Method} {Path} after {Elapsed}ms",
                    context.Request.Method,
                    context.Request.Path,
                    stopwatch.ElapsedMilliseconds
                );

                //
                // Throw Exception Agains for Handling using Top Level Middlewares ...
                throw;
            }
        }
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xLoggingService\Models\XLogEntry.cs

using System;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;

namespace xLoggingService.Models
{
    /// <summary>
    /// a Log which Issued ...
    /// </summary>
    public class XLogEntry
    {
        public int EventId { get; set; }
        public string State { get; set; }
        public string SpanId { get; set; }
        public LogLevel Level { get; set; }
        public string Message { get; set; }
        public string TraceId { get; set; }
        public string Category { get; set; }
        public string Exception { get; set; }
        public DateTime Timestamp { get; set; }
        public string Application { get; set; }
        public string Environment { get; set; }
        public string MachineName { get; set; }
        public string CorrelationId { get; set; }
        public IDictionary<string, string> Scope { get; set; } = new Dictionary<string, string>();
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xLoggingService\Providers\XLoggerProvider.cs

using System;
using Newtonsoft.Json;
using System.Diagnostics;
using xLoggingService.Models;
using xCommons.Configurations;
using System.Collections.Generic;
using xLoggingService.Background;
using xLoggingService.Interfaces;
using Microsoft.Extensions.Logging;
using xLoggingService.Configuration;

namespace xLoggingService.Providers
{
    public class XLoggerProvider : ILoggerProvider
    {
        //
        private readonly XLogDispatcher dispatcher;
        private readonly XAppConfiguration configuration;
        private readonly XLoggingServiceConfiguration config;
        private readonly IReadOnlyCollection<IXLogWriter> writers;

        public XLoggerProvider(
            XAppConfiguration configuration,
            XLoggingServiceConfiguration config,
            IEnumerable<IXLogWriter> writers
        )
        {
            // 
            this.config = config;
            this.configuration = configuration;
            this.writers = new List<IXLogWriter>(writers)
                .AsReadOnly();

            //
            dispatcher = new XLogDispatcher(
                config.Queue.Capacity, this.writers);
        }

        public ILogger CreateLogger(string categoryName)
        {
            //
            return new XLogger(
                config: config,
                category: categoryName,
                dispatcher: dispatcher,
                configuration: configuration
            );
        }

        public void Dispose()
        {
            dispatcher.Dispose();
        }
    }

    public class XLogger : ILogger
    {
        //
        private readonly string category;
        private readonly XLogDispatcher dispatcher;
        private readonly XAppConfiguration configuration;
        private readonly XLoggingServiceConfiguration config;

        public XLogger(
            string category,
            XLogDispatcher dispatcher,
            XAppConfiguration configuration,
            XLoggingServiceConfiguration config
        )
        {
            // 
            this.config = config;
            this.category = category;
            this.dispatcher = dispatcher;
            this.configuration = configuration;
        }

        public IDisposable BeginScope<TState>(TState state)
        {
            return NullScope.Instance;
        }

        public bool IsEnabled(LogLevel level)
        {
            //
            var result =
                config.Enabled &&
                level >= config.MinimumLevel &&
                level != LogLevel.None;

            //
            return result;
        }

        public void Log<TState>(
            LogLevel level,
            EventId eventId,
            TState state,
            Exception exception,
            Func<TState, Exception, string> formatter
        )
        {
            //
            if (!IsEnabled(level))
            {
                return;
            }

            //
            var activity = Activity.Current;
            dispatcher.Enqueue(new XLogEntry
            {
                Level = level,
                Category = category,
                EventId = eventId.Id,
                TraceId = activity?.Id,
                SpanId = activity?.RootId,
                Timestamp = DateTime.UtcNow,
                Message = formatter == null
                    ? state == null
                    ? string.Empty
                    : state.ToString()
                    : formatter(state, exception),
                Exception = exception == null
                    ? null
                    : exception.ToString(),
                State = state == null
                    ? null :
                    JsonConvert.SerializeObject(state),
                Application = configuration.Name,
                MachineName = Environment.MachineName,
                Environment = configuration.Environment,
            });
        }
        
        private sealed class NullScope : IDisposable { 
            public static readonly NullScope Instance = new(); 
            public void Dispose() { } 
        }
    }
}


### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xLoggingService\Writers\XDatabaseLogWriter.cs

using System;
using System.Threading;
using System.Data.Common;
using xCommons.Extensions;
using System.Threading.Tasks;
using xLoggingService.Models;
using xCommons.Configurations;
using xLoggingService.Interfaces;
using xLoggingService.Extensions;
using xLoggingService.Configuration;

namespace xLoggingService.Writers
{
    public sealed class XDatabaseLogWriter : IXLogWriter
    {
        //
        private bool initialized;
        private readonly object sync = new();
        private readonly XDatabaseLogConfiguration config;
        private readonly XAppConfiguration appConfiguration;

        public XDatabaseLogWriter(
            XDatabaseLogConfiguration config,
            XAppConfiguration appConfiguration
        )
        {
            //
            this.config = config;
            this.appConfiguration = appConfiguration;
        }

        public Task WriteAsync(
            XLogEntry e,
            CancellationToken token
        )
        {
            //
            if (e.IsNull())
            {
                return Task.CompletedTask;
            }

            //
            // Handle Task Enrichment ...
            e = e.Enrich(appConfiguration);

            //
            if (e.Level < config.MinimumLevel || config.ConnectionString.IsNullOrEmpty())
            {
                return Task.CompletedTask;
            }

            //
            try
            {
                // 
                lock (sync)
                {
                    //
                    using (var c = CreateConnection())
                    {
                        //
                        c.Open();
                        if (!initialized)
                        {
                            using (var cmd = c.CreateCommand())
                            {
                                //
                                cmd.CommandText = $"CREATE TABLE IF NOT EXISTS [{config.TableName}] (Id INTEGER PRIMARY KEY, Timestamp TEXT, Level TEXT, Category TEXT, EventId INTEGER, Message TEXT, Exception TEXT, State TEXT, Application TEXT, Environment TEXT, MachineName TEXT, TraceId TEXT, SpanId TEXT, CorrelationId TEXT)";
                                cmd.ExecuteNonQuery();
                            }
                            initialized = true;
                        }

                        //
                        using (var cmd = c.CreateCommand())
                        {
                            //
                            cmd.CommandText = $"INSERT INTO [{config.TableName}] (Timestamp,Level,Category,EventId,Message,Exception,State,Application,Environment,MachineName,TraceId,SpanId,CorrelationId) VALUES (@Timestamp,@Level,@Category,@EventId,@Message,@Exception,@State,@Application,@Environment,@MachineName,@TraceId,@SpanId,@CorrelationId)";

                            //
                            Add(cmd, "@State", e.State);
                            Add(cmd, "@SpanId", e.SpanId);
                            Add(cmd, "@EventId", e.EventId);
                            Add(cmd, "@Message", e.Message);
                            Add(cmd, "@TraceId", e.TraceId);
                            Add(cmd, "@Category", e.Category);
                            Add(cmd, "@Exception", e.Exception);
                            Add(cmd, "@Level", e.Level.ToString());
                            Add(cmd, "@Application", e.Application);
                            Add(cmd, "@Environment", e.Environment);
                            Add(cmd, "@MachineName", e.MachineName);
                            Add(cmd, "@CorrelationId", e.CorrelationId);
                            Add(cmd, "@Timestamp", e.Timestamp.ToString("O"));

                            //
                            cmd.ExecuteNonQuery();
                        }
                    }
                }
            }
            catch { }

            //
            return Task.CompletedTask;
        }

        private DbConnection CreateConnection()
        {
            //
            var typeName =
                config.Provider == "Microsoft.Data.Sqlite"
                ? "Microsoft.Data.Sqlite.SqliteConnection, Microsoft.Data.Sqlite"
                : config.Provider == "System.Data.SqlClient" ?
                "System.Data.SqlClient.SqlConnection, System.Data.SqlClient"
                : config.Provider;

            // 
            var type = Type.GetType(typeName, false);
            if (type.IsNull())
            {
                throw new InvalidOperationException("Database provider was not found: " + typeName);
            }

            // 
            var c = (DbConnection)Activator.CreateInstance(type);
            c.ConnectionString = config.ConnectionString;

            //
            return c;
        }

        private static void Add(
            DbCommand c, 
            string name, 
            object value
        ) { 
            //
            var p = c.CreateParameter(); 
            p.ParameterName = name; 
            p.Value = (object)value ?? DBNull.Value; 
            c.Parameters.Add(p); 
        }
    }
}




### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xLoggingService\Writers\XEventLogWriter.cs

using System;
using System.Threading;
using xCommons.Extensions;
using xEventService.Models;
using System.Threading.Tasks;
using xLoggingService.Models;
using xCommons.Configurations;
using xEventService.Interfaces;
using System.Collections.Generic;
using xLoggingService.Interfaces;
using xLoggingService.Extensions;
using xLoggingService.Configuration;

namespace xLoggingService.Writers
{
    public sealed class XEventLogWriter : IXLogWriter
    {

        //
        private readonly XAppConfiguration appConfiguration;
        private readonly XLoggingServiceConfiguration config;
        private readonly Func<IXEventServiceProvider> resolver;

        public XEventLogWriter(
            XAppConfiguration appConfiguration,
            XLoggingServiceConfiguration config,
            Func<IXEventServiceProvider> resolver
        )
        {
            //
            this.config = config;
            this.resolver = resolver;
            this.appConfiguration = appConfiguration;
        }

        public async Task WriteAsync(
            XLogEntry entry,
            CancellationToken token
        )
        {
            //
            if (entry.IsNull())
            {
                return;
            }

            //
            // Handle Task Enrichment ...
            entry = entry.Enrich(appConfiguration);

            //
            var provider = resolver();
            if (provider.IsNull() || entry.Level < config.Event.MinimumLevel)
            {
                return;
            }

            // 
            var payload = new Dictionary<string, string> {
                { nameof(XLogEntry.Category), entry.Category },
                { nameof(XLogEntry.Level), entry.Level.ToString() },
                { nameof(XLogEntry.State), entry.State ?? string.Empty },
                { nameof(XLogEntry.TraceId), entry.TraceId ?? string.Empty } ,
                { nameof(XLogEntry.Exception), entry.Exception ?? string.Empty },
            };

            // 
            await provider.SendMessageAsync(
                new XEventMessage
                {
                    Payload = payload,
                    Message = entry.Message,
                    Offset = entry.Timestamp,
                    Sender = config.Event.Sender,
                    Action = config.Event.Action,
                },
                config.Event.Topic,
                token
            ).ConfigureAwait(false);
        }
    }
}

### FILE: C:\Users\saherelm\Documents\Projects\xSaherelmWorkspace\Modules\xLoggingService\Writers\XFileLogWriter.cs

using System;
using System.IO;
using System.Text;
using Newtonsoft.Json;
using System.Threading;
using xCommons.Extensions;
using xExceptions.Constants;
using System.Threading.Tasks;
using xLoggingService.Models;
using xCommons.Configurations;
using xLoggingService.Interfaces;
using xLoggingService.Extensions;
using xLoggingService.Configuration;

namespace xLoggingService.Writers
{
    public sealed class XFileLogWriter : IXLogWriter
    {
        //
        private readonly object sync = new();
        private readonly XAppConfiguration appConfiguration;
        private readonly XLoggingServiceConfiguration configuration;

        public XFileLogWriter(
            XAppConfiguration appConfiguration,
            XLoggingServiceConfiguration configuration
        )
        {
            //
            if (configuration.IsNull() || appConfiguration.IsNull())
            {
                XException.InvalidConfiguration.Throw();
            }

            //
            this.configuration = configuration;
            this.appConfiguration = appConfiguration;

            //
            Directory.CreateDirectory(configuration.File.Directory);
        }

        public Task WriteAsync(
            XLogEntry entry,
            CancellationToken token
        )
        {
            //
            if (entry.IsNull())
            {
                return Task.CompletedTask;
            }

            //
            // Handle Task Enrichment ...
            entry = entry.Enrich(appConfiguration);

            // 
            if (entry.Level < configuration.File.MinimumLevel)
            {
                return Task.CompletedTask;
            }

            // 
            string date = DateTime.UtcNow.ToString("yyyy-MM-dd");
            var path = Path.Combine(
                configuration.File.Directory, 
                configuration.File.FileName.Replace("-", $"-{date}"));

            //
            lock (sync)
            {
                //
                File.AppendAllText(path, configuration.File.Format.Equals(
                    "Json",
                    StringComparison.OrdinalIgnoreCase)
                ? JsonConvert.SerializeObject(entry) + Environment.NewLine
                : $"{entry.Timestamp:O} [{entry.Level}] {entry.Category}: {entry.Message}{Environment.NewLine}", Encoding.UTF8);
            }

            //
            return Task.CompletedTask;
        }
    }
}
