多线程方式下写入系统日志

本章节将介绍如何以多线程方式下系统日志,并确保每条日志写入不发生冲突,全部写入日志文件。基本原理,将日志写入日志文件error.log,写入前先判断error.log是否可写,如果不可写则等待,直到成功写入为止。error.log其实就是一个文本文件,当有大量日志同时写入时,日志的先后顺序会受影响,但并不会遗漏日志。

判断日志文件是否可用:

 C# Code
1.public static bool IsFileInUse(string fileName)
2.{
3.    bool inUse = true;
4.    System.IO.FileStream fs = null;
5.    try
6.    {
7.        fs = new System.IO.FileStream(fileName,  System.IO.FileMode.Open,  System.IO.FileAccess.Read,  System.IO.FileShare.None);
8.        inUse = false;
9.    }
10.    catch
11.    {
12.        inUse = true;
13.    }
14.    finally
15.    {
16.        if (fs != null)
17.            fs.Close();
18.    }
19.    return inUse;
20.}

多线程方式写入日志:

 C# Code
1.public static void Log(string str)
2.{
3.    string filePath = @appPath + 'error.log';
4.    string content = DateTime.Now.ToString('yyyyMMddHHmmss:') + str;
5.    if (!System.IO.File.Exists(filePath))
6.    {
7.        System.IO.File.AppendAllText(filePath, content);
8.        return;
9.    }
10.    ParameterizedThreadStart threadStart = new ParameterizedThreadStart(WriteLog);
11.    Thread thread = new Thread(threadStart);
12.    thread.Name = 'WebApp.WriteLog';
13.    thread.Start(str);
14.}

向日志文件写入日志,其中WriteLog的参数str必须是object类型。

 C# Code
1.public static void WriteLog(object str)
2.{
3.    string filePath = @appPath + 'error.log';
4.    string content = '\r\n' + DateTime.Now.ToString('yyyyMMddHHmmss:') + str.ToString();
5.    System.IO.FileInfo info = new System.IO.FileInfo(filePath);
6.    if (info.Length > 1024 * 1024 * 5)
7.    {
8.        while (IsFileInUse(filePath))
9.            Thread.Sleep(100);
10.        System.IO.File.Move(filePath, @appPath + 'error' + DateTime.Now.ToString('yyyyMMdd') + '.log');
11.        System.IO.File.Delete(filePath);
12.    }
13.    while (IsFileInUse(filePath))
14.        Thread.Sleep(100);
15.    if (!IsFileInUse(filePath))
16.    {
17.        #region write file
18.        System.IO.FileStream fs = null;
19.        try
20.        {
21.            fs = new System.IO.FileStream(filePath,  System.IO.FileMode.Append, System.IO.FileAccess.Write,  System.IO.FileShare.None);
22.            fs.Write(Encoding.UTF8.GetBytes(content), 0, Encoding.UTF8.GetByteCount(content));
23.        }
24.        catch
25.        {
26.            ;
27.        }
28.        finally
29.        {
30.            if (fs != null)
31.                fs.Close();
32.        }
33.        #endregion
34.    }
35.}
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值