C# 手动写入日志,过大写入新文件

server/2024/9/23 4:32:41/

老项目没有用logf4j等日志框架,使用的是手动写入文件的方式存储日志。当日志过大会出现写入缓慢问题。下面采用IO异步写入以及文件过大分片等方式解决问题。

private static readonly object _lock = new object();
private const long MaxFileSize = 10 * 1024 * 1024; // 10MBpublic void SaveTextAsync(string data, string ex, string methods)
{try{DateTime date = DateTime.Now;string logData = date.ToString("yyyy-MM-dd HH:mm:ss") + "\r\n" + data + "\r\n" + ex;string strDate = date.ToString("yyyyMMdd");string strDateTxt = strDate + ".txt";string programPath = AppDomain.CurrentDomain.BaseDirectory.Substring(0, 2);string logDir = Path.Combine(programPath + "", "\\MESBUG", strDate, methods);lock (_lock){if (!Directory.Exists(logDir)){Directory.CreateDirectory(logDir);}// 获取当前最新的日志文件string filePath = GetLatestLogFile(logDir, strDate);// 检查文件大小并切割filePath = CheckFileSizeAndRotate(filePath, logDir, strDate);byte[] logDataBytes = System.Text.Encoding.UTF8.GetBytes(logData + Environment.NewLine);FileStream fs = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.None, 4096, true);// 异步写入fs.BeginWrite(logDataBytes, 0, logDataBytes.Length, new AsyncCallback(EndWriteCallback), fs);}}catch (Exception ex2){return;}}// 获取日志目录中最新的日志文件
private string GetLatestLogFile(string logDir, string strDate)
{// 获取日志目录下所有日志文件,按文件名排序var logFiles = Directory.GetFiles(logDir, $"{strDate}_*.txt").OrderByDescending(f => f).FirstOrDefault();if (logFiles == null){// 如果没有找到分片日志文件,则返回默认的日志文件路径return Path.Combine(logDir, strDate + ".txt");}return logFiles;
}// 检查文件大小并切割日志文件
private string CheckFileSizeAndRotate(string filePath, string logDir, string strDate)
{FileInfo fileInfo = new FileInfo(filePath);// 如果文件超过指定大小,则创建新文件if (fileInfo.Exists && fileInfo.Length > MaxFileSize){string newFileName = $"{strDate}_{DateTime.Now.ToString("HHmmss")}.txt";return Path.Combine(logDir, newFileName);}return filePath;
}private void EndWriteCallback(IAsyncResult ar)
{FileStream fs = (FileStream)ar.AsyncState;fs.EndWrite(ar);fs.Close();
}

http://www.ppmy.cn/server/118374.html

相关文章

重生归来之挖掘stm32底层知识(1)——寄存器

概念理解 要使用stm32首先要知道什么是引脚和寄存器。 如下图所示,芯片通过这些金属丝与电路板连接,这些金属丝叫做引脚。一般做软件开发是不需要了解芯片是怎么焊的,只要会使用就行。我们平常通过编程来控制这些引脚的输入和输出&#xff0c…

ubuntu 22.04 ~24.04 如何修改登录背景

ubuntu 22.04 ~24.04 如何修改登录背景 背景:由于22.04 登录gdm的变更,之前的修改登录背景的方案已经无法使用。现在给大家分享新的使用方法: 1,下载如下路径的脚本: https://download.csdn.net/download/xdhyqd/89…

Android mmap分析

Android mmap分析 mmap基础概念 mmap是一种内存映射文件的方法,即将一个文件或者其它对象映射到进程的地址空间,实现文件磁盘地址和进程虚拟地址空间中一段虚拟地址的一一对映关系。实现这样的映射关系后,进程就可以采用指针的方式读写操作…

[Redis] Redis中的set和zset类型

🌸个人主页:https://blog.csdn.net/2301_80050796?spm1000.2115.3001.5343 🏵️热门专栏: 🧊 Java基本语法(97平均质量分)https://blog.csdn.net/2301_80050796/category_12615970.html?spm1001.2014.3001.5482 🍕 Collection与…

ARM驱动学习之 IOremap实现GPIO 读

ARM驱动学习之 IOremap实现GPIO 读 前面介绍了虚拟地址和物理地址。 读写GPIO,控制GPIO的寄存器都是使用系统做好的虚拟地址 本期介绍如何自己实现物理地址到虚拟地址的转化 iounmap和ioremap函数可以实现物理地址到虚拟地址的转化1.根据原理图找核心板对应的寄存器…

PostgreSQL的流复制断点续传

PostgreSQL的流复制断点续传 PostgreSQL的流复制(Streaming Replication)具有断点续传的能力,这意味着当主节点和备用节点之间的连接由于网络故障等原因中断后,备用节点会自动从中断点继续接收WAL(Write-Ahead Loggin…

python生成器原理

#2-使用生成器生成斐波那契数列(无限序列) def fibonacci(): a, b 0, 1 while True: yield a a, b b, a b gen fibonacci() for _ in range(10): print(next(gen),end,) #第一次next后,执行fibonacci函数,到yield a处停止&a…

【笔记】时间复杂度

文章目录 时间复杂度概念常见的时间复杂度时间复杂度的衡量常数时间例子线性时间例子平方时间例子对数时间例子 时间复杂度概念 时间复杂度:衡量算法随着输入量增长,执行时间的增长速度。 一般来说,肯定是希望时间复杂度小点比较好。 常见…