.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.");
相关推荐
学以智用2 小时前
.NET Core 完整特性速查表(终极版)
后端·.net
cdbqss13 小时前
VB2026 动态生成工具栏类 BqGetToolStrip
数据库·oracle·开源·.net·学习方法·教育电商·basic
宝桥南山3 小时前
Microsoft Agent Framework(MAF) - 如何将workflow或者A2A client转换成一个AI Agent
microsoft·ai·微软·aigc·.net·.netcore
三天不学习1 天前
YOLO + .NET 10 快速入门:从零搭建实时目标检测应用
yolo·目标检测·.net
0x00072 天前
译 Anders Hejlsberg 谈 C# 与 .NET
开发语言·c#·.net
AI行业学习2 天前
.NET Framework 3.5 SP1 完整离线包(2029.5.29)
开发语言·windows·.net
AI行业学习2 天前
.NET Framework 3.5 官方离线包下载+完整安装教程【2026.5.29】
windows·.net·notepad++
HEADKON2 天前
司拉德帕失代偿期肝硬化及胆道梗阻患者禁止使用,肝酶升高需暂停药物
单例模式
我是唐青枫2 天前
C#.NET YARP 服务发现实战:接入 Consul 和 Kubernetes 动态发现后端服务
c#·服务发现·.net
一个帅气昵称啊2 天前
NetcoreKevin:.NET 企业级智能体管理框架
.net