编写Log4Net日志文件查看工具

本文介绍了一种使用C#解析Log4Net日志的方法,通过正则表达式匹配日期、时间、线程名、日志级别及消息,并将这些信息转化为DataTable以便进一步处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Log4Net的Pattern:

%date [%thread] %-5level- %message%newline

正则表达式的格式:

(?<Date>[0-9]{4}-[0-9]{2}-[0-9]{2}) (?<Time>[0-9]{2}:[0-9]{2}:[0-9]{2})\,[0-9]{3} \[(?<Thread>[\s\S]*?)\] (?<Level>[DEBUG|WARN |FATAL|ERROR|INFO ]*?)- (?<message>[\s\S]*?\n) 

完整的代码如下:

 

ContractedBlock.gifExpandedBlockStart.gifCode
 1using System;
 2using System.Data;
 3using System.Windows.Forms;
 4using System.IO;
 5using System.Text.RegularExpressions;
 6
 7namespace MorningStar.Blade.Log4NetReader
 8ExpandedBlockStart.gifContractedBlock.gif{
 9    public partial class Log4NetShow : Form
10ExpandedSubBlockStart.gifContractedSubBlock.gif    {
11        private const string PATTERN = @"(?<Date>[0-9]{4}-[0-9]{2}-[0-9]{2}) (?<Time>[0-9]{2}:[0-9]{2}:[0-9]{2})\,[0-9]{3} \[(?<Thread>[\s\S]*?)\] (?<Level>[DEBUG|WARN |FATAL|ERROR|INFO ]*?)- (?<message>[\s\S]*?\n)";
12        private const string DATEPATTERN = "Date";
13        private const string TIMEPATTERN = "Time";
14        private const string THREADPATTERN = "Thread";
15        private const string LEVELPATTERN = "Level";
16        private const string MESSAGEPATTERN = "message";
17
18        public Log4NetShow()
19ExpandedSubBlockStart.gifContractedSubBlock.gif        {
20            InitializeComponent();
21            
22        }

23
24        private string GetTextFromFile(string filePath)
25ExpandedSubBlockStart.gifContractedSubBlock.gif        {
26            string tempFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,String.Format("temp{0}.txt",System.DateTime.Now.ToBinary()));
27            File.Copy(filePath,tempFile);
28
29            string text = FileReader.ReadFlie(tempFile);
30            File.Delete(tempFile);
31            return text;
32        }

33
34        private void btnOpenFile_Click(object sender, EventArgs e)
35ExpandedSubBlockStart.gifContractedSubBlock.gif        {
36            try
37ExpandedSubBlockStart.gifContractedSubBlock.gif            {
38                using (OpenFileDialog ofd = new OpenFileDialog())
39ExpandedSubBlockStart.gifContractedSubBlock.gif                {
40                    if (ofd.ShowDialog() == DialogResult.OK)
41ExpandedSubBlockStart.gifContractedSubBlock.gif                    {
42                        txtFileName.Text = ofd.FileName;
43                        string textFromFile = GetTextFromFile(ofd.FileName);
44                        if (!String.IsNullOrEmpty(textFromFile))
45ExpandedSubBlockStart.gifContractedSubBlock.gif                        {
46                            MatchCollection collection = RegexUtil.GetMatchCollection(textFromFile, PATTERN);
47                            DataTable logTable = GetLogData(collection);
48                            if (logTable != null && logTable.Rows.Count > 0)
49                                gdLog.DataSource = logTable;
50                        }

51                    }

52                }

53            }

54            catch (Exception ex)
55ExpandedSubBlockStart.gifContractedSubBlock.gif            {
56                MessageBox.Show(ex.Message, "Warn", MessageBoxButtons.OK, MessageBoxIcon.Warning);
57            }

58
59        }

60
61        private DataTable GetLogData(MatchCollection collection)
62ExpandedSubBlockStart.gifContractedSubBlock.gif        {
63            string date = "";
64            string time = "";
65            string thread = "";
66            string level = "";
67            string message = "";
68
69            DataTable logTable = new DataTable();
70            logTable.Columns.Add(new DataColumn("LogDate"typeof(DateTime)));
71            logTable.Columns.Add(new DataColumn("ThreadName"typeof(string)));
72            logTable.Columns.Add(new DataColumn("Level"typeof(string)));
73            logTable.Columns.Add(new DataColumn("Message"typeof(string)));
74
75            foreach (Match match in collection)
76ExpandedSubBlockStart.gifContractedSubBlock.gif            {
77                date = match.Groups[DATEPATTERN].Value;
78                time = match.Groups[TIMEPATTERN].Value;
79                thread = match.Groups[THREADPATTERN].Value;
80                level = match.Groups[LEVELPATTERN].Value;
81                message = match.Groups[MESSAGEPATTERN].Value;
82
83                DataRow dr = logTable.NewRow();
84                DateTime temp;
85                DateTime.TryParse(String.Format("{0} {1}", date, time), out temp);
86                dr["LogDate"= temp;
87                dr["ThreadName"= thread;
88                dr["Level"= level;
89
90                dr["Message"= message;
91                logTable.Rows.Add(dr);
92            }

93
94            return logTable;
95        }

96    }

97}

98

 

RegexUtil的代码:

 

ContractedBlock.gifExpandedBlockStart.gifCode
 1using System;
 2using System.Text.RegularExpressions;
 3
 4namespace MorningStar.Blade.Log4NetReader
 5ExpandedBlockStart.gifContractedBlock.gif{
 6    public static class RegexUtil
 7ExpandedSubBlockStart.gifContractedSubBlock.gif    {
 8        public static string Replace(string inputData, string pattern, string replaceData)
 9ExpandedSubBlockStart.gifContractedSubBlock.gif        {
10            try
11ExpandedSubBlockStart.gifContractedSubBlock.gif            {
12                Regex match = new Regex(pattern);
13
14                return match.Replace(inputData, replaceData);
15            }

16            catch (Exception ex)
17ExpandedSubBlockStart.gifContractedSubBlock.gif            {
18                return "";
19            }

20        }

21
22        public static string GetGroupValue(string inputData, string pattern, string groupName)
23ExpandedSubBlockStart.gifContractedSubBlock.gif        {
24            try
25ExpandedSubBlockStart.gifContractedSubBlock.gif            {
26                Regex match = new Regex(pattern);
27
28                return match.Match(inputData).Groups[groupName].Value;
29            }

30            catch (Exception ex)
31ExpandedSubBlockStart.gifContractedSubBlock.gif            {
32                return "";
33            }

34        }

35
36        public static MatchCollection GetMatchCollection(string inputData, string pattern)
37ExpandedSubBlockStart.gifContractedSubBlock.gif        {
38            Regex re = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Multiline);
39            return re.Matches(inputData);
40        }

41    }

42}

43

 

FileReader的代码:

 

ContractedBlock.gifExpandedBlockStart.gifCode
 1using System;
 2using System.IO;
 3
 4namespace MorningStar.Blade.Log4NetReader
 5ExpandedBlockStart.gifContractedBlock.gif{
 6    public class FileReader
 7ExpandedSubBlockStart.gifContractedSubBlock.gif    {
 8ExpandedSubBlockStart.gifContractedSubBlock.gif        /**//// <summary>
 9        /// 读取文本文件
10        /// </summary>
11        /// <param name="filePath"></param>

12        public static string ReadFlie(string filePath)
13ExpandedSubBlockStart.gifContractedSubBlock.gif        {
14            try
15ExpandedSubBlockStart.gifContractedSubBlock.gif            {
16                string str = "";
17                using (StreamReader sr = new StreamReader(filePath))
18ExpandedSubBlockStart.gifContractedSubBlock.gif                {
19                    str = sr.ReadToEnd();
20                    sr.Close();
21                }

22                return str;
23            }

24            catch (Exception ex)
25ExpandedSubBlockStart.gifContractedSubBlock.gif            {
26                throw ex;
27            }

28        }
 
29
30    }

31}

32

 

转载于:https://www.cnblogs.com/heblade/archive/2009/10/19/Log4Net_FileContent_Show.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值