csharp 控制台记录器

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp 控制台记录器相关的知识,希望对你有一定的参考价值。

using System;
using System.Collections.Concurrent;
using System.ComponentModel;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using System.Threading;
using Coderr.Client;

namespace HDSupportIdentifier.Functions
{
    public class ConsoleLogItem
    {
        public ConsoleLogItem()
        {
            //
        }

        public ConsoleLogItem(string msg, LogType type)
        {
            Message = msg;
            Type = type;
        }

        public string Message { get; set; } = "";
        public LogType Type { get; set; } = LogType.Info;
    }

    public enum LogType
    {
        Info = 0,
        Warning = 1,
        Error = 2,
        Exception = 3,
        Debug = 4
    }

    internal static class Log
    {
        private static ConcurrentQueue<ConsoleLogItem> LogQueue { get; } = new ConcurrentQueue<ConsoleLogItem>();
        private static readonly BackgroundWorker BgQueueProcessor = new BackgroundWorker();

        internal static void Initialise()
        {
            BgQueueProcessor.DoWork += BgQueueProcessorOnDoWork;
            BgQueueProcessor.RunWorkerCompleted += BgQueueProcessorOnRunWorkerCompleted;
            BgQueueProcessor.WorkerSupportsCancellation = true;

            BgQueueProcessor.RunWorkerAsync();
        }

        internal static void Stop()
        {
            BgQueueProcessor?.CancelAsync();
        }

        private static void BgQueueProcessorOnRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs runWorkerCompletedEventArgs)
        {
            Console.ForegroundColor = ConsoleColor.White;

            var msg = $"[{DateTime.Now:MM:dd HH:mm:ss}] [LOG] Logging afgebroken";
            Console.WriteLine(msg);
            WriteToLog(msg, LogType.Info);
        }

        private static void BgQueueProcessorOnDoWork(object sender, DoWorkEventArgs doWorkEventArgs)
        {
            while (!BgQueueProcessor.CancellationPending)
            {
                var ok = LogQueue.TryDequeue(out var logItem);
                if (!ok) Thread.Sleep(TimeSpan.FromMilliseconds(25));
                else PrintLog(logItem.Message, logItem.Type);
            }
        }

        internal static void LogDebug(string debug)
        {
            AddToLog(debug, LogType.Debug);
        }

        internal static void LogInfo(string info)
        {
            AddToLog(info, LogType.Info);
        }

        internal static void LogWarning(string warning)
        {
            AddToLog(warning, LogType.Warning);
        }

        internal static void LogError(string error, [CallerMemberName] string callerName = "")
        {
            Err.Report(new Exception(error), callerName);
            AddToLog($"[{callerName}] {error}", LogType.Error);
        }

        internal static void LogException(Exception stacktrace, object data, [CallerMemberName] string callerName = "")
        {
            Err.Report(stacktrace, data);
            AddToLog($"[{callerName}] {stacktrace.Message}", LogType.Exception);
        }

        internal static void LogException(Exception stacktrace, [CallerMemberName] string callerName = "")
        {
            Err.Report(stacktrace, callerName);
            AddToLog($"[{callerName}] {stacktrace.Message}", LogType.Exception);
        }

        internal static void AddToLog(string msg, LogType type)
        {
            var logItem = new ConsoleLogItem(msg, type);
            LogQueue.Enqueue(logItem);
        }

        /// <summary>
        /// Logt een bericht naar de console en eventueel logbestand
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="type"></param>
        private static void PrintLog(string msg, LogType type)
        {
            try
            {
                // data klaarzetten
                var datetime = $"{DateTime.Now:MM-dd HH:mm:ss}";

                // hebben we een [*] datablok?
                var regex = new Regex(@"\[.+\]");
                var match = regex.Matches(msg);
                var showMarkedNote = false;
                var markedNote = "";
                if (match.Count > 0)
                {
                    markedNote = match[0].ToString();
                    showMarkedNote = true;

                    msg = msg.Replace($"{markedNote} ", "");
                }

                ConsoleColor msgColor;

                switch (type)
                {
                    case LogType.Info:
                        msgColor = ConsoleColor.White;
                        break;

                    case LogType.Warning:
                        msgColor = ConsoleColor.Yellow;
                        break;

                    case LogType.Error:
                        msgColor = ConsoleColor.Red;
                        break;

                    case LogType.Debug:
                        msgColor = ConsoleColor.Green;
                        break;

                    default:
                        msgColor = ConsoleColor.Gray;
                        break;
                }

                // printen naar console
                Console.ForegroundColor = ConsoleColor.Gray;
                Console.Write($"[{datetime}] ");

                if (showMarkedNote)
                {
                    Console.ForegroundColor = ConsoleColor.Cyan;
                    Console.Write($"{markedNote} ");
                }

                Console.ForegroundColor = msgColor;
                Console.WriteLine(msg);
                Console.ForegroundColor = ConsoleColor.Gray;

                // wegschrijven
                WriteToLog(msg, type);
            }
            catch (Exception ex)
            {
                Err.Report(ex, msg);
            }
        }

        /// <summary>
        /// Bericht wegschrijven naar logbestand
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="type"></param>
        private static void WriteToLog(string msg, LogType type)
        {
            try
            {
                var fileTypeName = "";

                switch (type)
                {
                    case LogType.Info:
                        fileTypeName = "Log";
                        break;

                    case LogType.Warning:
                        fileTypeName = "WarningLog";
                        break;

                    case LogType.Error:
                        fileTypeName = "ErrorLog";
                        break;

                    case LogType.Exception:
                        fileTypeName = "ExceptionLog";
                        break;
                        
                    case LogType.Debug:
                        fileTypeName = "DebugLog";
                        break;
                }

                if (!Directory.Exists(Variables.LogDirectory)) Directory.CreateDirectory(Variables.LogDirectory);

                var curFile = Path.Combine(Variables.LogDirectory, $"[{DateTime.Now:yyyy-MM-dd}] {fileTypeName}.ini");

                if (!File.Exists(curFile))
                {
                    File.WriteAllText(curFile, "");
                    Thread.Sleep(10);
                }

                using (var stream = new FileStream(curFile, FileMode.Append, FileAccess.Write))
                using (var writer = new StreamWriter(stream))
                {
                    writer.WriteLine($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff}] {msg}");
                    writer.Close();
                    stream.Close();
                }
            }
            catch (Exception ex)
            {
                Err.Report(ex, msg);
            }
        }
    }
}

以上是关于csharp 控制台记录器的主要内容,如果未能解决你的问题,请参考以下文章

csharp 异常记录器

csharp 用于CLI的多线程记录器

csharp DatabaseLogger(EF默认记录器拦截器)

csharp log4net记录器扩展

csharp C#超级简单记录器类//用法示例:https://heiswayi.nrird.com/2016/creating-super-simple-logger-class-in-csharp

csharp SOAP日志记录(记录所有传入和传出的xml)