首页 > 编程语言 >C# 简易日志类

C# 简易日志类

时间:2023-01-25 12:44:11浏览次数:42  
标签:log LogType C# fileName 简易 Test 日志 LogMethod

C#的实现

using System;
using System.IO;
using System.Text;

namespace Vicky.Helpers
{
    public class Log
    {
        /// <summary>
        /// 日志保存级别,小于此级别的日志不会被保存,默认值是LogMethod.Immediate
        /// </summary>
        public LogType Type { get; private set; } = LogType.Info;

        /// <summary>
        /// 日志保存方法,默认值是LogMethod.Immediate
        /// </summary>
        public LogMethod Method { get; private set; } = LogMethod.Immediate;

        /// <summary>
        /// 日志文件保存的路径,默认值是null
        /// </summary>
        public string FileName { get; private set; } = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), ".log");

        /// <summary>
        /// 用于临时存储日志内容
        /// </summary>
        private static StringBuilder stringBuilder = new StringBuilder();

        /// <summary>
        /// 初始化日志设置
        /// </summary>
        /// <param name="fileName"></param>
        public void Initialize(string fileName, LogMethod method = LogMethod.Immediate, LogType type = LogType.Info)
        {
            FileName = fileName;
            Method = method;
            Type = type;

            Write($"Log.Initialize({fileName}, {method}, {type})", 0, "Log initialized.", LogType.All);
        }

        /// <summary>
        /// 撰写一条日志内容
        /// </summary>
        /// <param name="sender">日志发送函数或类</param>
        /// <param name="code">日志编号</param>
        /// <param name="content">日志具体内容</param>
        /// <param name="type">此条日志内容的日志类型,如果小于设置的日志保存级别,则不保存,否则保存。</param>
        public void Write(object sender, int code, string content, LogType type = LogType.Info)
        {
            if (type >= Type)
            {
                string message = $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}\t{type}\t<{(int)type * 10000 + code}>\t[{sender}] {content}";

                if (Method == LogMethod.Immediate)
                {
                    File.AppendAllText(FileName, $"{message}\r\n");
                }                
                else if (Method == LogMethod.Waiting)
                {
                    stringBuilder.AppendLine(message);
                }
            }
        }

        /// <summary>
        /// 保存临时存储的日志内容至指定的日志文件
        /// </summary>
        /// <param name="fileName">日志文件路径</param>
        public void Save(string fileName = null)
        {
            if(string.IsNullOrWhiteSpace(fileName) || !Directory.Exists(Path.GetDirectoryName(fileName)))
            {
                fileName = FileName;
            }

            Write($"Log.Save({fileName})", 0, "Saving log..", LogType.All);

            File.AppendAllText(fileName, stringBuilder.ToString());

            stringBuilder.Length = 0; // 清空临时存储的日志内容
        }


    }

    /// <summary>
    /// 日志类型
    /// </summary>
    public enum LogType
    {
        /// <summary>
        /// 日志类型为Debug
        /// </summary>
        Debug = 1,

        /// <summary>
        /// 日志类型为Info
        /// </summary>
        Info = 2,

        /// <summary>
        /// 日志类型为Warning
        /// </summary>
        Warning = 3,

        /// <summary>
        /// 日志类型为Error
        /// </summary>
        Error = 4,

        /// <summary>
        /// 日志类型为Fatal
        /// </summary>
        Fatal = 5,

        /// <summary>
        /// 日志类型为All,日志最高等级。
        /// </summary>
        All = 9         
    }

    /// <summary>
    /// 日志保存方法
    /// </summary>
    public enum LogMethod
    {
        /// <summary>
        /// 当有新日志信息时,立即写入文件,不需要使用Log.Save()。
        /// </summary>
        Immediate = 0,

        /// <summary>
        /// 当有新日志信息时,立即写入缓存,需要使用Log.Save(),才写入文件。
        /// </summary>
        Waiting = 1,  
    }
}

C#的测试方法

using System;

namespace Vicky.Helpers.TestBenches
{
    internal class LogTestBench : TestBench
    {
        Log log = new Log();
        string fileName = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + $"\\log_testbench_{DateTime.Now.ToString("yyyy-MM-dd")}.log";

        internal override void Test()
        {
            Test(fileName, LogMethod.Immediate, LogType.Debug);
            Test(fileName, LogMethod.Immediate, LogType.Info);
            Test(fileName, LogMethod.Immediate, LogType.Warning);
            Test(fileName, LogMethod.Immediate, LogType.Error);
            Test(fileName, LogMethod.Immediate, LogType.Fatal);

            Test(fileName, LogMethod.Waiting, LogType.Debug);
            Test(fileName, LogMethod.Waiting, LogType.Info);
            Test(fileName, LogMethod.Waiting, LogType.Warning);
            Test(fileName, LogMethod.Waiting, LogType.Error);
            Test(fileName, LogMethod.Waiting, LogType.Fatal);
        }

        private void Test(string fileName, LogMethod method, LogType type)
        {
            log.Initialize(fileName, method, type);

            log.Write(this, 0, "this is a debug log.", LogType.Debug);
            log.Write(this, 0, "this is a info log.", LogType.Info);
            log.Write(this, 0, "this is a warning log.", LogType.Warning);
            log.Write(this, 0, "this is a error log.", LogType.Error);
            log.Write(this, 0, "this is a fatal log.", LogType.Fatal);

            if(method== LogMethod.Waiting)
            {
                log.Save(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + $"\\log_testbench_{DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss")}.log");
            }
        }        
    }
}

 

标签:log,LogType,C#,fileName,简易,Test,日志,LogMethod
From: https://www.cnblogs.com/vicky2021/p/17066854.html

相关文章