C#实现异步日志记录类的示例代码

 更新时间:2023年11月10日 16:16:48   作者:爱吃奶酪的松鼠丶  
这篇文章主要为大家详细介绍了C#如何实现异步日志记录类,从而方便下次使用,不用重复造轮子,文中的示例代码讲解详细,感兴趣的小伙伴可以了解下

先定义接口类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 异常
{
    internal interface ILog
    {
        Task WriteErrorLog(string message);

        Task WriteInfoLog(string message);

        Task WriteLog(string logType, string message);
    }
}

在去实现:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace 异常
{
    internal class Log : ILog
    {
        public string LogDirectory { get; set; }
        public string TimeDirName { get; set; }

        private  string LogFileName { get; set; }

        private const long maxLogSize = 2*1024*1024; // 2 MB

        private string FirstLogFileName { get; set; }
        public Log() 
        {
            //在根目录创建Log文件夹
            IOTools.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;
            IOTools.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";
                    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");
                    }
                }
            }
        }


    }
}

工具类:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace 异常
{
    internal  class IOTools
    {
        public static void CreatLogDir(string name)
        {
            string rootDirectory = Directory.GetCurrentDirectory();
            CreatDir(name, rootDirectory);
        }

        public static void 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);
            }

        }
    }
}

最后实现的效果,简洁明了

如图:

以上就是C#实现异步日志记录类的示例代码的详细内容,更多关于C#异步日志记录类的资料请关注脚本之家其它相关文章!

相关文章

  • C# Onnx实现DIS高精度图像二类分割

    C# Onnx实现DIS高精度图像二类分割

    这篇文章主要为大家详细介绍了C# Onnx实现DIS高精度图像二类分割的相关知识,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下
    2023-11-11
  • C#中string用法实例详解

    C#中string用法实例详解

    这篇文章主要介绍了C#中string用法,非常详细的总结了比较常见的关于C#中string的几个常用方法,需要的朋友可以参考下
    2014-08-08
  • 一文掌握C# JSON(2023最新整理)

    一文掌握C# JSON(2023最新整理)

    JSON的全称是JavaScript Object Notation,意思是JavaScript对象表示法,它是一种基于文本,独立于语言的轻量级数据交换格式,这篇文章主要介绍了C#中的JSON(2023最新整理),需要的朋友可以参考下
    2023-05-05
  • C#微信分享代码

    C#微信分享代码

    这篇文章主要为大家详细介绍了C#微信分享的实现代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-10-10
  • C#通过配置文件动态修改web.config内容的操作步骤

    C#通过配置文件动态修改web.config内容的操作步骤

    这篇文章主要介绍了C#通过配置文件动态修改web.config内容的操作步骤,文中通过图文结合的方式介绍的非常详细,对大家的学习或工作有一定的帮助,需要的朋友可以参考下
    2024-03-03
  • C#中的let字句应用示例

    C#中的let字句应用示例

    这篇文章主要给大家介绍了C#中的let字句,文中通过应用实例介绍的很详细,相信对大家具有一定的参考价值,有需要的朋友们下面来一起看看吧。
    2017-02-02
  • C# 使用PrintDocument类打印标签的方法

    C# 使用PrintDocument类打印标签的方法

    本文介绍打印机初步配置,以及实现方法,标签主要展示资产基本信息以及二维码,对C# 使用PrintDocument类打印标签的详细过程感兴趣的朋友一起看看吧
    2022-04-04
  • C#之CLR内存字符串常量池(string)

    C#之CLR内存字符串常量池(string)

    这篇文章主要介绍了C#之CLR内存字符串常量池(string),对于学习和理解C#内存原理很有帮助,需要的朋友可以参考下
    2014-08-08
  • C# 字符串、数组和List的截取和转换实例

    C# 字符串、数组和List的截取和转换实例

    下面小编就为大家分享一篇C# 字符串、数组和List的截取和转换实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2017-11-11
  • C#中Linq延迟查询的例子

    C#中Linq延迟查询的例子

    这篇文章主要介绍了C#中Linq延迟查询的例子,本文用一个实例来讲解延迟查询的使用,需要的朋友可以参考下
    2015-06-06

最新评论