我有此.NET健康检查:
public Task<HealthCheckResult> CheckHealthAsync(
HealthCheckContext context,
CancellationToken cancellationToken = default)
{
Regex ConnectedRegex = new Regex(_healthOptions.ConnectedRegex);
Regex ConnectionRefusedRegex = new Regex(_healthOptions.ConnectionRefusedRegex);
Regex ErrorRegex = new Regex(_healtOptions.ErrorRegex);
int ConnectedRegexLine = GetLogLine(ConnectedRegex);
int ConnectionRefusedRegexLine = GetLogLine(ConnectionRefusedRegex);
int ErrorRegexLine = GetLogLine(ErrorRegex);
if ((ConnectionRefusedRegexLine > 0 || ErrorRegexLine > 0) &&
ConnectedRegexLine <= 0)
{
return Task.FromResult(HealthCheckResult.Unhealthy());
}
return Task.FromResult(HealthCheckResult.Healthy());
}
}
它需要3个正则表达式值,并找到它们在日志文件中出现的行。
这是我用来获取每一行的方法。
private int GetLogLine(Regex regex)
{
GetLogFile = DefaultLogFile.GetLogFileName();
using StreamReader reader = new StreamReader(GetLogFile);
string line;
int lineNumber = 0;
int errorLine = 0;
while ((line = reader.ReadLine()) != null)
{
// Try to match each line against the Regex.
Match match = regex.Match(line);
if (match.Success)
{
errorLine = lineNumber;
}
lineNumber++;
}
return errorLine;
}
我意识到每次运行此检查时,我都会读取日志文件3次。我是否可以更改支票,使其仅需读取一次日志文件,但仍为if语句的CheckHealthAsync
方法提供行号?如果是这样,我该怎么做?
答案 0 :(得分:0)
也许使用正则表达式命名组对您有用? https://www.regular-expressions.info/refext.html
我没有尝试过,但是拜拜,这是一个选择
var match = new Regex(string.Join("|",
$"(<?{nameof(_healthOptions.ConnectedRegex)}>{_healthOptions.ConnectedRegex})",
$"(<?{nameof(_healthOptions.ConnectionRefusedRegex)}>{_healthOptions.ConnectionRefusedRegex})",
$"(<?{nameof(_healtOptions.ErrorRegex)}>{_healtOptions.ErrorRegex)})")).Match("inputstring");
if (match.Success)
{
if (match.Groups.ContainsKey(nameof(_healthOptions.ConnectedRegex)))
{
}
else if (match.Groups.ContainsKey(nameof(_healthOptions.ConnectionRefusedRegex)))
{
}
else if (match.Groups.ContainsKey(nameof(_healthOptions.ErrorRegex)))
{
}
}