利用委托设计可以应用于不同情境下的日志记录器

本文探讨了使用C#实现的日志记录系统,通过自定义的Logger类来处理不同级别的日志消息,并介绍了如何将日志输出到控制台或文件中。此外,还讨论了委托在日志记录过程中的应用。
There's no need for greater accessibility because the delegate infrastructure can connect the delegates
namespace Logger
{
    class Program
    {

        //We need to write the single implementation for the method that writes messages to the console:

        public static void LogToConsole(string msg)
        {
            Console.Error.WriteLine(msg);
        }
        static void Main(string[] args)
        {
            var fileOutput = new FileLogger(@"log.txt");

            // Logger.WriteMessages += LogToConsole;
            string file=null;

            Logger.LogMessages(Severity.Warning, file, "T");
       }
   }

    public enum Severity
    {
        Verbose,
        Trace,
        Information,
        Warning,
        Error,
        Critical
    }
    public static class Logger
    {
       
        public static Action<string> WriteMessages;  // 

        public static Severity LogLevel { get; set; } = Severity.Warning;
        public static void LogMessages(Severity s, string component,string msg)
        {
            if (s < LogLevel) //如果小于警告级别直接返回
                return;
            var outputMsg = $"{DateTime.Now}\t{s}\t{component}\t{msg}";
            //You may prefer a design that silently continues when no methods have been attached
            WriteMessages?.Invoke(outputMsg);
        }
        
    }
}


namespace Logger
{
    public class FileLogger  //
    {
        public readonly string logPath;
        public FileLogger(string path)
        {
            logPath = path;
            Logger.WriteMessages += LogMessage;
        }

        public void DetachLog() => Logger.WriteMessages -= LogMessage; // cancel relate
        private void LogMessage(string msg)
        {
            try
            {
                using(var log = File.AppendText(logPath))
                {
                    log.WriteLine(msg);
                    log.Flush();
                }
            }
            catch
            {
                
                //Logging is failing....
            }
        }
    }
}

You won't find the Invoke() method listed in the documentation for System.Delegate or System.MulticastDelegate. 
The compiler generates a type safe Invoke method for any delegate type declared.
 In this example, that means Invoke takes a single string argument, and has a void return type.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值