C#写文本日志帮助类(支持多线程)改进版(不适用于ASP.NET程序)
由于iis的自动回收机制,不适用于ASP.NET程序
代码:
using System;
using System.Collections.Concurrent;
using System.Configuration;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks; namespace CommonDll
{
/// <summary>
/// 写日志类
/// </summary>
public class LogUtil
{
#region 字段
public static string path = ConfigurationManager.AppSettings["LogPath"];
public static int fileSize = * * ; //日志分隔文件大小
private static ConcurrentQueue<Tuple<string, DateTime>> queue = new ConcurrentQueue<Tuple<string, DateTime>>();
#endregion #region 构造函数
static LogUtil()
{
Task.Factory.StartNew(new Action(delegate()
{
StringBuilder log;
string path;
Tuple<string, DateTime> tuple;
string item; while (true)
{
log = new StringBuilder();
path = CreateLogPath(); while (queue.TryDequeue(out tuple))
{
item = string.Format(@"{0} {1}", tuple.Item2.ToString("yyyy-MM-dd HH:mm:ss.fff"), tuple.Item1);
log.AppendFormat("\r\n{0}", item);
} if (log.Length > ) WriteFile(log.ToString(, log.Length - ), path);
Thread.Sleep();
}
}));
}
#endregion #region 写文件
/// <summary>
/// 写文件
/// </summary>
public static void WriteFile(string log, string path)
{
try
{
if (!Directory.Exists(Path.GetDirectoryName(path)))
{
Directory.CreateDirectory(Path.GetDirectoryName(path));
} if (!File.Exists(path))
{
using (FileStream fs = new FileStream(path, FileMode.Create)) { fs.Close(); }
} using (FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write))
{
using (StreamWriter sw = new StreamWriter(fs))
{
sw.WriteLine(log);
sw.Flush();
}
fs.Close();
}
}
catch { }
}
#endregion #region 生成日志文件路径
/// <summary>
/// 生成日志文件路径
/// </summary>
public static string CreateLogPath()
{
int index = ;
string logPath;
bool bl = true;
do
{
index++;
logPath = Path.Combine(path, "Log" + DateTime.Now.ToString("yyyyMMdd") + (index == ? "" : "_" + index.ToString()) + ".txt");
if (File.Exists(logPath))
{
FileInfo fileInfo = new FileInfo(logPath);
if (fileInfo.Length < fileSize)
{
bl = false;
}
}
else
{
bl = false;
}
} while (bl); return logPath;
}
#endregion #region 写错误日志
/// <summary>
/// 写错误日志
/// </summary>
public static void LogError(string log)
{
queue.Enqueue(new Tuple<string, DateTime>("[Error] " + log, DateTime.Now));
}
#endregion #region 写操作日志
/// <summary>
/// 写操作日志
/// </summary>
public static void Log(string log)
{
queue.Enqueue(new Tuple<string, DateTime>("[Info] " + log, DateTime.Now));
}
#endregion }
}
测试代码:
private void button1_Click(object sender, EventArgs e)
{
int n = ;
DateTime dtStart = DateTime.Now;
for (int i = ; i <= n; i++)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(object obj)
{
int j = (int)obj;
LogUtil.Log("测试" + j.ToString("")); if (j == n)
{
double sec = DateTime.Now.Subtract(dtStart).TotalSeconds;
MessageBox.Show(n + "条日志完成,耗时" + sec.ToString("0.000") + "秒");
}
}), i);
}
}
效果图:

C#写文本日志帮助类(支持多线程)改进版(不适用于ASP.NET程序)的更多相关文章
- C#写文本日志帮助类(支持多线程)
代码: using System; using System.Configuration; using System.IO; using System.Threading.Tasks; namespa ...
- Android开发调试日志工具类[支持保存到SD卡]
直接上代码: package com.example.callstatus; import java.io.File; import java.io.FileWriter; import java.i ...
- glog另启动线程写文本日志
glog本身是很高效的,google的大牛肯定知道大规模的写日志用glog的话肯定会影响业务线程的处理,带负荷的磁盘IO谁都桑不起.比方levelDB就是默认异步写,更不用说google的三驾马车都是 ...
- Asp.Net写文本日志
底层代码: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespac ...
- C#写日志工具类
代码: using System; using System.Collections.Generic; using System.IO; using System.Linq; using System ...
- 支持异步写入的日志类,支持Framework2.0
因为工作需要需要在XP上运行一个C#编写的Winform插件,我就用Framework2.0,因为存在接口交互所以想保留交易过程的入参出参. 考虑到插件本身实施的因素,就没有使用Log4.NLog等成 ...
- 如何将Unicode文本写到日志文件中
有时为了定位问题,我们需要结合打印日志来处理.特别是较难复现的,一般都需要查看上下文日志才能找出可能存在的问题.考虑到程序要在不同语言的操作系统上运行,程序界面显示要支持Unicode,打印出来的日志 ...
- c#中@标志的作用 C#通过序列化实现深表复制 细说并发编程-TPL 大数据量下DataTable To List效率对比 【转载】C#工具类:实现文件操作File的工具类 异步多线程 Async .net 多线程 Thread ThreadPool Task .Net 反射学习
c#中@标志的作用 参考微软官方文档-特殊字符@,地址 https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/toke ...
- Linux是一个基于POSIX和Unix的多用户、多任务、支持多线程和多CPU的性能稳定的操作系统,可免费使用并自由传播。
Linux是一个基于POSIX和Unix的多用户.多任务.支持多线程和多CPU的性能稳定的操作系统,可免费使用并自由传播. Linux是众多操作系统之一 , 目前流行的服务器和 PC 端操作系统有 L ...
随机推荐
- python 3.5 成功安装 scrapy 的步骤
http://www.cnblogs.com/hhh5460/p/5814275.html
- iOS -- CocoaPods
CocoaPods 是什么? CocoaPods 是一个负责管理 iOS 项目中第三方开源库的工具.CocoaPods 的项目源码在 GitHub( https://github.com/CocoaP ...
- chattr用法
[root@localhost tmp]# umask 0022 一.chattr用法 1.创建空文件attrtest,然后删除,提示无法删除,因为有隐藏文件 [root@localhost tmp] ...
- charles工具抓包教程(http跟https)
1.下载charles 可以去charles官网下载,下载地址:http://www.charlesproxy.com/download/ 根据自己的操作系统下载对应的版本,然后进行安装,然后打 ...
- LeetCode All in One 题目讲解汇总(持续更新中...)
终于将LeetCode的免费题刷完了,真是漫长的第一遍啊,估计很多题都忘的差不多了,这次开个题目汇总贴,并附上每道题目的解题连接,方便之后查阅吧~ 477 Total Hamming Distance ...
- .NET跨平台之旅:数据库连接字符串写法引发的问题
最近在一个ASP.NET Core站点中遇到一个奇怪问题.当用dotnet run命令启动站点后,开始的一段时间请求执行速度超慢,有时要超过20秒,有时甚至超过1分钟,日志中会记录这样的错误: Sys ...
- Cocos2d-x不要随便在onEnter里面addChild
使用任何版本的Cocos2d-x(1.x,2.x,3.0),在onEnter中调用addChild,都要小心谨慎,因为它有可能导致两种莫名其妙的BUG,莫名其妙的BUG当然难以定位了!更何况这个BUG ...
- 使用 Code Snippet 简化 Coding
在开发的项目的时候,你是否经常遇到需要重复编写一些类似的代码,比如是否经常会使用 for.foreach ? 在编写这两个循环语句的时候,你是一个字符一个字符敲还是使用 Visual Studio 提 ...
- CSharpGL(37)创建和使用VBO的最佳方式
CSharpGL(37)创建和使用VBO的最佳方式 开始 近日在OpenGL红宝书上看到这样的讲解. 其核心意思是,在创建VBO时用 glBufferData(GL_ARRAY_BUFFER, len ...
- salesforce 零基础学习(五十七)Test 类中创建TestUser帮助类
我们写Test Class的时候往往都需要指定一个uesr去run test method. TestUserHelper类如下: public class TestUserHelper { publ ...