gpt4 book ai didi

c# - 如何使用跨多行的 c# 解析来自文本文件的消息?

转载 作者:行者123 更新时间:2023-12-02 05:00:05 24 4
gpt4 key购买 nike

给定此日志文件,我如何使用 StreamReader 读取包含多个换行符 (\n) 的行?ReadLine 方法按字面意思返回每一行,但一条消息可能跨越多行。

Larger Image for the down votes

这是我目前的情况

using (var sr = new StreamReader(filePath))
using (var store = new DocumentStore {ConnectionStringName = "RavenDB"}.Initialize())
{
IndexCreation.CreateIndexes(typeof(Logs_Search).Assembly, store);

using (var bulkInsert = store.BulkInsert())
{
const char columnDelimeter = '|';
const string quote = @"~";
string line;

while ((line = sr.ReadLine()) != null)
{
batch++;
List<string> columns = null;
try
{
columns = line.Split(columnDelimeter)
.Select(item => item.Replace(quote, string.Empty))
.ToList();

if (columns.Count != 5)
{
batch--;
Log.Error(string.Join(",", columns.ToArray()));
continue;
}

bulkInsert.Store(LogParser.Log.FromStringList(columns));

/* Give some feedback */
if (batch % 100000 == 0)
{
Log.Debug("batch: {0}", batch);
}

/* Use sparingly */
if (ThrottleEnabled && batch % ThrottleBatchSize == 0)
{
Thread.Sleep(ThrottleThreadWait);
}
}
catch (FormatException)
{
if (columns != null) Log.Error(string.Join(",", columns.ToArray()));
}
catch (Exception exception)
{
Log.Error(exception);
}
}
}
}

和模型

public class Log
{
public string Component { get; set; }
public string DateTime { get; set; }
public string Logger { get; set; }
public string Level { get; set; }
public string ThreadId { get; set; }
public string Message { get; set; }
public string Terms { get; set; }

public static Log FromStringList(List<string> row)
{
Log log = new Log();

/*log.Component = row[0] == string.Empty ? null : row[0];*/
log.DateTime = row[0] == string.Empty ? null : row[0].ToLower();
log.Logger = row[1] == string.Empty ? null : row[1].ToLower();
log.Level = row[2] == string.Empty ? null : row[2].ToLower();
log.ThreadId = row[3] == string.Empty ? null : row[3].ToLower();
log.Message = row[4] == string.Empty ? null : row[4].ToLower();

return log;
}
}

最佳答案

我会使用 Regex.Split并在每个错误的开头将文件分解为与日期模式(例如 2013-06-19)匹配的任何内容。

关于c# - 如何使用跨多行的 c# 解析来自文本文件的消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17223459/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com