.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 优秀框架 ABP全面详解
microsoft·.net·web·blazor·abp·razor
勿芮介2 小时前
【开发技术】.Net使用FFmpeg视频特定帧上绘制内容
ffmpeg·.net·音视频
追逐时光者8 小时前
C#/.NET/.NET Core技术前沿周刊 | 第 41 期(2025年6.1-6.8)
后端·.net
追逐时光者8 小时前
不写一行代码 .NET 使用 FluentCMS 快速构建现代化内容管理系统(CMS)
后端·.net·cms
百锦再16 小时前
Razor编程中@Helper的用法大全
.net·web·blazor·tag·core·razor·helper
安木夕18 小时前
C#-Visual Studio宇宙第一IDE使用实践
前端·c#·.net
o0向阳而生0o1 天前
65、.NET 中DllImport的用途
.net·非托管·dllimport
喵叔哟1 天前
25.【.NET8 实战--孢子记账--从单体到微服务--转向微服务】--单体转微服务--用户服务接口
微服务·架构·.net
~山有木兮1 天前
C++设计模式 - 单例模式
c++·单例模式·设计模式