.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.");
相关推荐
界面开发小八哥3 小时前
界面组件DevExpress WPF中文教程:Grid - 如何获取节点?
.net·wpf·界面控件·devexpress·ui开发
今晚打老虎z3 小时前
dotnet-env: .NET 开发者的环境变量加载工具
前端·chrome·.net
我是唐青枫5 小时前
C#.NET NLog 详解
开发语言·c#·.net
一线码农6 小时前
MinHook 如何对 .NET 母体 CoreCLR 进行拦截
c#·.net·代码注入
佛·追命7 小时前
.net wpf混淆
.net·wpf
编程乐趣8 小时前
自学C#,要懂得用好对象浏览器
windows·.net
不想写bug呀17 小时前
多线程案例——单例模式
java·开发语言·单例模式
bantinghy17 小时前
Linux进程单例模式运行
linux·服务器·单例模式
驱动小百科10 天前
如何在Windows上安装.NET Framework 详细教程分享
windows·.net·.net framework·.net安装·.net下载
江边垂钓者10 天前
单例模式-Python示例
javascript·python·单例模式