.NET封装一个简单的单例模式异步的日志类

.NET兼职社区

可以直接使用,防止重复造轮子。

csharp 复制代码
using System.IO;
using System;
using System.Threading.Tasks;

namespace Wpf.PersonnelNotice.Servers
{
    public sealed class LogService
    {
        private static readonly Lazy<LogService> lazy =
            new Lazy<LogService>(() =>
            {
                return new LogService();
            });

        public static LogService Instance { get { return lazy.Value; } }

        private string LogDirectory { get; set; }
        private string TimeDirName { get; set; }
        private string LogFileName { get; set; }
        private string FirstLogFileName { get; set; }
        private const long maxLogSize = 2 * 1024 * 1024; // 2 MB
        private string newFileName { get; set; }

        private LogService()
        {
            // 在根目录创建Log文件夹
            CreatLogDir("Log");

            // 初始化
            LogDirectory = Path.Combine(Directory.GetCurrentDirectory(), "Log");
            TimeDirName = DateTime.Now.ToString("yyyyMMdd");
            FirstLogFileName = $"log_{DateTime.Now:yyyyMMddHHmmss}.txt";
        }
        public async Task WriteErrorLog(string message)
        {
            await WriteLog("Error", message);
        }

        public async Task WriteInfoLog(string message)
        {
            await WriteLog("Info", message);
        }

        public async Task WriteLog(string logType, string message)
        {
            //创建文件夹
            string dirType = TimeDirName + "\\" + logType;
            CreatDir(dirType, LogDirectory);
            LogFileName = Path.Combine(LogDirectory, dirType, FirstLogFileName);
            if (!File.Exists(LogFileName))
            {
                using (StreamWriter sw = File.CreateText(LogFileName))
                {
                    await sw.WriteLineAsync($"【{logType}】 {DateTime.Now} \r\n {message}  \r\n \r\n");
                }
            }
            else
            {
                FileInfo fileInfo = new FileInfo(LogFileName);
                if (fileInfo.Length > maxLogSize)
                {
                    string newFileName = $"log_{DateTime.Now:yyyyMMddHHmmss}.txt";
                    FirstLogFileName = newFileName;
                    LogFileName = Path.Combine(LogDirectory, dirType, newFileName);
                    using (StreamWriter sw = File.CreateText(LogFileName))
                    {
                        await sw.WriteLineAsync($"【{logType}】 {DateTime.Now} \r\n {message}  \r\n \r\n");
                    }
                }
                else
                {
                    using (StreamWriter sw = File.AppendText(LogFileName))
                    {
                        await sw.WriteLineAsync($"【{logType}】 {DateTime.Now} \r\n {message}  \r\n \r\n");
                    }
                }
            }
        }


        public static void CreatLogDir(string name)
        {
            string rootDirectory = Directory.GetCurrentDirectory();
            Instance.CreatDir(name, rootDirectory);
        }

        // 将CreatDir方法改为非静态,因为在单例模式下由实例调用
        public bool CreatDir(string name, string path)
        {
            if (string.IsNullOrEmpty(name)) throw new ArgumentNullException("name");
            if (string.IsNullOrEmpty(path)) throw new ArgumentNullException("path");

            string logPath = Path.Combine(path, name);

            // 判断文件夹是否存在
            if (!Directory.Exists(logPath))
            {
                // 在当前项目根目录创建一个新的文件夹
                Directory.CreateDirectory(logPath);
                return true;
            }

            return false;
        }
    }
}

// 使用示例

csharp 复制代码
LogService.Instance.WriteErrorLog("This is an error message.");
LogService.Instance.WriteInfoLog("This is an info message.");
相关推荐
时光追逐者1 天前
WaterCloud:一套基于.NET 8.0 + LayUI的快速开发框架,完全开源免费!
前端·microsoft·开源·c#·.net·layui·.netcore
friklogff1 天前
【C#生态园】打造现代化跨平台应用:深度解析.NET桌面应用工具
开发语言·c#·.net
@Unity打怪升级2 天前
【C#】CacheManager:高效的 .NET 缓存管理库
开发语言·后端·机器学习·缓存·c#·.net·.netcore
GGBondlctrl2 天前
【JavaEE初阶】深入解析单例模式中的饿汉模式,懒汉模式的实现以及线程安全问题
单例模式·设计模式·饿汉模式·懒汉模式·懒汉模式线程安全问题
清风拂山感2 天前
设计模式之单例模式
javascript·单例模式·设计模式
陌上之殇2 天前
C++实现单例模式
c++·单例模式
冷白白3 天前
【C++】单例模式
开发语言·c++·单例模式·c
yufei-coder3 天前
.Net 9与AI开发
人工智能·.net
孟章豪3 天前
深入理解.NET中的委托与事件:实现灵活的事件驱动编程
.net
枪哥玩转嵌入式4 天前
大佬,简单解释下“嵌入式软件开发”和“嵌入式硬件开发”的区别
单片机·单例模式·51单片机