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; }

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


    }
}

工具类:

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);
            }

        }
    }
}

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

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#中的异步TCPClient是一种用于进行网络通信的。它允许你在进行网络连接、发送和接收数据时,使用异步操作来提高应用程序的性能和响应性。 要使用异步TCPClient,你需要使用C#异步编程模型(Async/Await)。以下是使用异步TCPClient的一些基本步骤: 1. 创建一个TCPClient对象,并指定要连接的远程主机和端口号。 2. 使用TCPClient对象的ConnectAsync方法,以异步方式连接到远程主机。 3. 一旦连接成功,你可以使用TCPClient对象的GetStream方法获取与远程主机进行通信的网络流。 4. 对于发送数据,你可以使用网络流的WriteAsync方法以异步方式发送字节数据或字符串。 5. 对于接收数据,你可以使用网络流的ReadAsync方法以异步方式接收字节数据或字符串。 下面是一个简单的示例代码,展示了如何使用异步TCPClient发送和接收数据: ```csharp using System; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; public class AsyncTcpClient { public static async Task Main() { // 远程主机的IP地址和端口号 string ipAddress = "127.0.0.1"; int port = 12345; // 创建TCPClient对象并连接到远程主机 TcpClient client = new TcpClient(); await client.ConnectAsync(IPAddress.Parse(ipAddress), port); // 获取与远程主机进行通信的网络流 NetworkStream stream = client.GetStream(); // 发送数据 string messageToSend = "Hello, server!"; byte[] sendData = Encoding.UTF8.GetBytes(messageToSend); await stream.WriteAsync(sendData, 0, sendData.Length); // 接收数据 byte[] receiveData = new byte

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值