Log4net get root logger and add custom appender

Date: 2019-04-10
using Common.Helpers;
using log4net.Appender;
using log4net.Core;
using log4net.Repository.Hierarchy;
using Microsoft.Owin;
using Owin;
using Owin.WebSocket;
using Owin.WebSocket.Extensions;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.WebSockets;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

//[assembly: OwinStartup(typeof(WebSocketsStartup))]
namespace WebSockets.Startup
{

    public class WebSocketsStartup
    {
        public static IList OpenConnections = new List();

        public class MyWebSocket : WebSocketConnection
        {
            public override async Task OnMessageReceived(ArraySegment message, WebSocketMessageType type)
            {
                //Handle the message from the client

                //Example of JSON serialization with the client
                //var json = Encoding.UTF8.GetString(message.Array, message.Offset, message.Count);
                //Use something like Json.Net to read the json
            }

            public override void OnOpen()
            {
                OpenConnections.Add(this);
            }

            public override void OnClose(WebSocketCloseStatus? closeStatus, string closeStatusDescription)
            {
                OpenConnections.Remove(this);
            }
            //public override bool Authenticate(IOwinRequest request){return true;}
        }

        public class MyLogAppender : AppenderSkeleton
        {
            protected override void Append(LoggingEvent loggingEvent)
            {
                var message = $"{loggingEvent.Level} {loggingEvent.RenderedMessage}";
                var data = Encoding.UTF8.GetBytes(message);
                foreach (var connection in OpenConnections)
                {
                    connection.SendText(data, true);
                }
            }
        }

        public static Task GetLogViewer()
        {
            var assembly = Assembly.GetExecutingAssembly();
            //assembly.GetManifestResourceNames();
            var resourceName = "WebSockets.Pages.LogViewer.html";

            using (Stream stream = assembly.GetManifestResourceStream(resourceName))
            using (StreamReader reader = new StreamReader(stream))
            {
                return reader.ReadToEndAsync();
            }
        }

        public static void Configuration(IAppBuilder app)
        {
            var defaultLogger = LoggingHelper.Logger;
            defaultLogger.Info("Adding custom logappender");

            Hierarchy h = (Hierarchy)log4net.LogManager.GetRepository();
            Logger rootLogger = h.Root;
            ((log4net.Repository.Hierarchy.Logger)rootLogger).AddAppender(new MyLogAppender());

            app.Map("/debuglog", appBuilder =>
            {
                appBuilder.Run(async context =>
                {
                    SetCorsHeaders(context);

                    var content = await GetLogViewer();
                    await context.Response.WriteAsync(content);
                });
            });


            app.MapWebSocketRoute("/ws");
        }

        private static void SetCorsHeaders(IOwinContext context)
        {
            try
            {
                context.Response.Headers["Access-Control-Allow-Origin"] = "*";
                context.Response.Headers["Access-Control-Allow-Headers"] = context.Request.Headers.Get("Access-Control-Request-Headers");
                context.Response.Headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, DELETE, OPTIONS";
                context.Response.Headers["Access-Control-Expose-Headers"] = "Content-Disposition, X-Total-Count, X-Employer-Code";
            }
            catch (Exception)
            {
                // ignore
            }
        }

        private static void ConfigureCors(IAppBuilder app)
        {
            app.MapWhen(ctx => ctx.Request.Method.Equals("OPTIONS", System.StringComparison.OrdinalIgnoreCase), appBuilder =>
            {
                appBuilder.Run(context =>
                {
                    SetCorsHeaders(context);
                    return context.Response.WriteAsync("");
                });
            });

            app.Use(async (context, next) =>
            {
                SetCorsHeaders(context);
                await next();
                SetCorsHeaders(context);
            });
        }
    }
}
9470cookie-checkLog4net get root logger and add custom appender