(以log4net日志库为例)
//文件数据集合
_LogMsgs = new List<LogEntity>();
//listfiles(文件名集合) foreach (string fruit in listfiles) { MatchCollection matches; using (FileStream fs = new FileStream(fruit, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { using (StreamReader sr = new StreamReader(fs, System.Text.Encoding.Default)) { //正则表达式解析日志数据(每个"()"括号相当于对象的属性,需要用表达式去匹配)
//"2021-05-26 17:36:20,800 [1]ERROR XXX系统 - 客户端异常(线程) System.NullReferenceException: 未将对象引用设置到对象的实例。 .........后面一大堆的错误详情信息" matches = Regex.Matches(sr.ReadToEnd(), @"(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d{3}) (\[\d{1,}\])([A-Z]{1,})\s{1,2}([A-Za-z]+ - .+) (.+)([\s\S]*?)", RegexOptions.RightToLeft); } } foreach (Match item in matches) { LogEntity entity = new LogEntity(); entity.time = item.Groups[1].Value; entity.thread = item.Groups[2].Value; entity.priority = item.Groups[3].Value; entity.logger = item.Groups[4].Value; entity.msg = item.Groups[5].Value; entity.details = item.Groups[6].Value; _LogMsgs.Add(entity); } }
注意:当日志文件达到1m多时,性能明显较慢,