Browse Source

添加项目文件。

master
Administrator 2 weeks ago
parent
commit
948f99ffca
  1. 6
      App.config
  2. 9
      App.xaml
  3. 17
      App.xaml.cs
  4. 99
      LogAnalyzer.csproj
  5. 3
      LogAnalyzer.slnx
  6. 840
      LogParserService.cs
  7. 69
      MainWindow.xaml
  8. 96
      MainWindow.xaml.cs
  9. 52
      Properties/AssemblyInfo.cs
  10. 71
      Properties/Resources.Designer.cs
  11. 117
      Properties/Resources.resx
  12. 30
      Properties/Settings.Designer.cs
  13. 7
      Properties/Settings.settings

6
App.config

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
</configuration>

9
App.xaml

@ -0,0 +1,9 @@
<Application x:Class="LogAnalyzer.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:LogAnalyzer"
StartupUri="MainWindow.xaml">
<Application.Resources>
</Application.Resources>
</Application>

17
App.xaml.cs

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace LogAnalyzer
{
/// <summary>
/// App.xaml 的交互逻辑
/// </summary>
public partial class App : Application
{
}
}

99
LogAnalyzer.csproj

@ -0,0 +1,99 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{0B886B0C-D80A-4AF0-A670-4FFD5FAE70FD}</ProjectGuid>
<OutputType>WinExe</OutputType>
<RootNamespace>LogAnalyzer</RootNamespace>
<AssemblyName>LogAnalyzer</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<WarningLevel>4</WarningLevel>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xaml">
<RequiredTargetFramework>4.0</RequiredTargetFramework>
</Reference>
<Reference Include="WindowsBase" />
<Reference Include="PresentationCore" />
<Reference Include="PresentationFramework" />
</ItemGroup>
<ItemGroup>
<ApplicationDefinition Include="App.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</ApplicationDefinition>
<Page Include="MainWindow.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Compile Include="App.xaml.cs">
<DependentUpon>App.xaml</DependentUpon>
<SubType>Code</SubType>
</Compile>
<Compile Include="LogParserService.cs" />
<Compile Include="MainWindow.xaml.cs">
<DependentUpon>MainWindow.xaml</DependentUpon>
<SubType>Code</SubType>
</Compile>
</ItemGroup>
<ItemGroup>
<Compile Include="Properties\AssemblyInfo.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

3
LogAnalyzer.slnx

@ -0,0 +1,3 @@
<Solution>
<Project Path="LogAnalyzer.csproj" Id="0b886b0c-d80a-4af0-a670-4ffd5fae70fd" />
</Solution>

840
LogParserService.cs

@ -0,0 +1,840 @@
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace LogAnalyzer
{
public class LogParserService
{
// 匹配行首的时间戳格式: 2026/7/17 2:46:38
// 使用 ^ 确保匹配行首
private readonly Regex _timestampRegex = new Regex(
@"^(?<datetime>\d{4}/\d{1,2}/\d{1,2}\s+\d{1,2}:\d{1,2}:\d{1,2})\s*(?<message>.*)$",
RegexOptions.Compiled
);
/// <summary>
/// 解析日志文件,以行首时间戳作为分隔符合并多行日志
/// </summary>
public DataTable ParseLogFile(string filePath)
{
return ParseLogFile(filePath, Encoding.Default);
}
/// <summary>
/// 解析日志文件(支持指定编码)
/// </summary>
public DataTable ParseLogFile(string filePath, Encoding encoding)
{
if (!File.Exists(filePath))
throw new FileNotFoundException($"日志文件未找到: {filePath}", filePath);
var logTable = CreateLogTable();
try
{
using (var reader = new StreamReader(filePath, encoding))
{
string line;
string currentTimestamp = null;
StringBuilder currentMessage = new StringBuilder();
bool hasContent = false;
while ((line = reader.ReadLine()) != null)
{
// 检查行首是否匹配时间戳格式
var match = _timestampRegex.Match(line);
if (match.Success)
{
// 遇到新的时间戳,保存之前的条目
if (hasContent && currentTimestamp != null)
{
AddLogEntry(logTable, currentTimestamp, currentMessage.ToString());
}
// 开始新的条目
currentTimestamp = match.Groups["datetime"].Value;
string messagePart = match.Groups["message"].Value.Trim();
currentMessage.Clear();
if (!string.IsNullOrEmpty(messagePart))
{
currentMessage.Append(messagePart);
}
hasContent = true;
}
else
{
// 不是时间戳行,追加到当前消息
if (hasContent)
{
if (currentMessage.Length > 0)
{
currentMessage.Append(Environment.NewLine);
}
currentMessage.Append(line.TrimEnd());
}
else
{
// 如果文件开头没有时间戳,将整行作为特殊处理
// 这里可以忽略或作为独立条目
if (!string.IsNullOrWhiteSpace(line))
{
logTable.Rows.Add("未知时间", line.Trim());
}
}
}
}
// 保存最后一个条目
if (hasContent && currentTimestamp != null)
{
AddLogEntry(logTable, currentTimestamp, currentMessage.ToString());
}
}
}
catch (IOException ex)
{
throw new InvalidOperationException($"读取日志文件失败: {ex.Message}", ex);
}
return logTable;
}
/// <summary>
/// 添加日志条目到 DataTable
/// </summary>
private void AddLogEntry(DataTable table, string timestamp, string message)
{
// 去除多余的空行
string cleanMessage = message.Trim();
if (!string.IsNullOrEmpty(cleanMessage))
{
table.Rows.Add(timestamp, cleanMessage);
}
}
/// <summary>
/// 创建日志 DataTable 结构
/// </summary>
private DataTable CreateLogTable()
{
var table = new DataTable("LogData");
table.Columns.Add("时间戳", typeof(string));
table.Columns.Add("日志内容", typeof(string));
return table;
}
/// <summary>
/// 解析日志并显示详细信息(用于调试)
/// </summary>
public void ParseAndDisplay(string filePath)
{
var logData = ParseLogFile(filePath);
Console.WriteLine($"总共解析了 {logData.Rows.Count} 条日志条目");
Console.WriteLine(new string('=', 80));
int index = 1;
foreach (DataRow row in logData.Rows)
{
string timestamp = row["时间戳"]?.ToString() ?? "";
string message = row["日志内容"]?.ToString() ?? "";
Console.WriteLine($"条目 {index}:");
Console.WriteLine($"时间: {timestamp}");
Console.WriteLine($"内容:");
Console.WriteLine(message);
Console.WriteLine(new string('-', 80));
Console.WriteLine();
index++;
}
}
/// <summary>
/// 检查特定日志文件,显示每行的解析情况(调试用)
/// </summary>
public void DebugParse(string filePath)
{
if (!File.Exists(filePath))
{
Console.WriteLine($"文件不存在: {filePath}");
return;
}
Console.WriteLine("逐行解析调试:");
Console.WriteLine(new string('=', 80));
using (var reader = new StreamReader(filePath, Encoding.Default))
{
string line;
int lineNumber = 0;
while ((line = reader.ReadLine()) != null)
{
lineNumber++;
var match = _timestampRegex.Match(line);
Console.WriteLine($"行 {lineNumber}:");
Console.WriteLine($" 原始: {line}");
if (match.Success)
{
Console.WriteLine($" 识别为时间戳: {match.Groups["datetime"].Value}");
Console.WriteLine($" 消息部分: {match.Groups["message"].Value}");
}
else
{
Console.WriteLine($" 不是时间戳行(作为多行内容的一部分)");
}
Console.WriteLine();
}
}
}
/// <summary>
/// 从日志中提取包含数据库指令关键词的条目及其前后N条日志
/// </summary>
/// <param name="logTable">原始日志DataTable</param>
/// <param name="contextLines">前后文行数,默认为3</param>
/// <returns>包含数据库指令及其上下文的DataTable</returns>
public DataTable ExtractDatabaseCommandsWithContext(DataTable logTable, int contextLines = 3)
{
if (logTable == null || logTable.Rows.Count == 0)
throw new ArgumentException("日志数据为空", nameof(logTable));
// 创建结果表
var resultTable = new DataTable("DbCommandContext");
resultTable.Columns.Add("时间戳", typeof(string));
resultTable.Columns.Add("日志内容", typeof(string));
resultTable.Columns.Add("是否数据库指令", typeof(bool));
resultTable.Columns.Add("条目索引", typeof(int));
resultTable.Columns.Add("上下文类型", typeof(string));
resultTable.Columns.Add("匹配关键词", typeof(string)); // 记录匹配到的关键词
// 1. 查找所有包含数据库指令关键词的条目索引
var dbCommandIndices = new List<int>();
var keywordMatches = new Dictionary<int, string>(); // 记录每个条目匹配的关键词
for (int i = 0; i < logTable.Rows.Count; i++)
{
string message = logTable.Rows[i]["日志内容"]?.ToString() ?? "";
string matchedKeyword = ContainsDbKeyword(message);
if (!string.IsNullOrEmpty(matchedKeyword))
{
dbCommandIndices.Add(i);
keywordMatches[i] = matchedKeyword;
}
}
if (dbCommandIndices.Count == 0)
{
// 如果没有找到数据库指令,返回空表
return resultTable;
}
// 2. 收集需要提取的索引范围
var indicesToExtract = new HashSet<int>();
foreach (int dbIndex in dbCommandIndices)
{
// 添加数据库指令本身
indicesToExtract.Add(dbIndex);
// 添加前N条
for (int i = 1; i <= contextLines; i++)
{
int prevIndex = dbIndex - i;
if (prevIndex >= 0)
indicesToExtract.Add(prevIndex);
}
// 添加后N条
for (int i = 1; i <= contextLines; i++)
{
int nextIndex = dbIndex + i;
if (nextIndex < logTable.Rows.Count)
indicesToExtract.Add(nextIndex);
}
}
// 3. 按索引排序并添加到结果表
var sortedIndices = indicesToExtract.OrderBy(idx => idx).ToList();
foreach (int idx in sortedIndices)
{
DataRow originalRow = logTable.Rows[idx];
string message = originalRow["日志内容"]?.ToString() ?? "";
bool isDbCommand = dbCommandIndices.Contains(idx);
string matchedKeyword = isDbCommand ? keywordMatches[idx] : "";
// 确定上下文类型
string contextType;
if (isDbCommand)
contextType = "数据库指令";
else
{
// 判断是前文还是后文
bool isBeforeDb = dbCommandIndices.Any(dbIdx => dbIdx > idx);
bool isAfterDb = dbCommandIndices.Any(dbIdx => dbIdx < idx);
if (isBeforeDb && !isAfterDb)
contextType = "指令前文";
else if (isAfterDb && !isBeforeDb)
contextType = "指令后文";
else if (isBeforeDb && isAfterDb)
contextType = "上下文(指令之间)";
else
contextType = "上下文";
}
resultTable.Rows.Add(
originalRow["时间戳"]?.ToString() ?? "",
message,
isDbCommand,
idx,
contextType,
matchedKeyword
);
}
return resultTable;
}
public DataTable ExtractTank1CommandsWithContext(DataTable logTable)
{
// 1. 参数校验
if (logTable == null || logTable.Rows.Count == 0)
throw new ArgumentException("日志数据为空", nameof(logTable));
// 2. 创建结果表,保持与输入表相同的结构(或按需自定义)
// var resultTable = logTable.Clone(); // Clone() 会复制表结构,但不复制数据
var matchedRows = new List<DataRow>();
// 3. 遍历原始表,匹配关键字
foreach (DataRow row in logTable.Rows)
{
string message = row["日志内容"]?.ToString() ?? "";
// 同时包含 "M1T1" 和 "T1执行" 才匹配(如需匹配其一,请将 && 改为 ||)
if (message.Contains("M1T1") || message.Contains("T1执行") ||
message.Contains(" T1") || message.Contains(",T1") || message.Contains(",401)"))
{
matchedRows.Add(row);
}
}
var finalRows = new List<DataRow>();
if (matchedRows.Count > 0)
{
int startIdx = 0;
string currentContent = matchedRows[0]["日志内容"]?.ToString() ?? "";
for (int i = 1; i < matchedRows.Count; i++)
{
string nextContent = matchedRows[i]["日志内容"]?.ToString() ?? "";
// 如果下一行的内容与当前块的内容不同
if (nextContent != currentContent)
{
// 将当前块的【开始行】加入结果
finalRows.Add(matchedRows[startIdx]);
// 如果当前块有连续重复(即 i - startIdx > 1),将【结束行】加入结果
if (i - startIdx > 1)
{
finalRows.Add(matchedRows[i - 1]);
}
// 重置状态,开始新的块
startIdx = i;
currentContent = nextContent;
}
}
// 处理最后一个块(循环结束后别忘了处理尾部)
finalRows.Add(matchedRows[startIdx]);
if (matchedRows.Count - startIdx > 1)
{
finalRows.Add(matchedRows[matchedRows.Count - 1]);
}
}
// 3. 构建并返回结果表
var resultTable = logTable.Clone();
foreach (var row in finalRows)
{
resultTable.ImportRow(row);
}
return resultTable;
}
public DataTable ExtractTank2CommandsWithContext(DataTable logTable)
{
// 1. 参数校验
if (logTable == null || logTable.Rows.Count == 0)
throw new ArgumentException("日志数据为空", nameof(logTable));
var matchedRows = new List<DataRow>();
// 3. 遍历原始表,匹配关键字
foreach (DataRow row in logTable.Rows)
{
string message = row["日志内容"]?.ToString() ?? "";
// 同时包含 "M1T1" 和 "T1执行" 才匹配(如需匹配其一,请将 && 改为 ||)
if (message.Contains("M1T2") || message.Contains("T2执行") ||
message.Contains(" T2") || message.Contains(",T2") || message.Contains(",402)"))
{
// 将匹配到的行导入结果表
matchedRows.Add(row);
}
}
var finalRows = new List<DataRow>();
if (matchedRows.Count > 0)
{
int startIdx = 0;
string currentContent = matchedRows[0]["日志内容"]?.ToString() ?? "";
for (int i = 1; i < matchedRows.Count; i++)
{
string nextContent = matchedRows[i]["日志内容"]?.ToString() ?? "";
// 如果下一行的内容与当前块的内容不同
if (nextContent != currentContent)
{
// 将当前块的【开始行】加入结果
finalRows.Add(matchedRows[startIdx]);
// 如果当前块有连续重复(即 i - startIdx > 1),将【结束行】加入结果
if (i - startIdx > 1)
{
finalRows.Add(matchedRows[i - 1]);
}
// 重置状态,开始新的块
startIdx = i;
currentContent = nextContent;
}
}
// 处理最后一个块(循环结束后别忘了处理尾部)
finalRows.Add(matchedRows[startIdx]);
if (matchedRows.Count - startIdx > 1)
{
finalRows.Add(matchedRows[matchedRows.Count - 1]);
}
}
// 3. 构建并返回结果表
var resultTable = logTable.Clone();
foreach (var row in finalRows)
{
resultTable.ImportRow(row);
}
return resultTable;
}
public DataTable ExtractTank3CommandsWithContext(DataTable logTable)
{
// 1. 参数校验
if (logTable == null || logTable.Rows.Count == 0)
throw new ArgumentException("日志数据为空", nameof(logTable));
var matchedRows = new List<DataRow>();
// 3. 遍历原始表,匹配关键字
foreach (DataRow row in logTable.Rows)
{
string message = row["日志内容"]?.ToString() ?? "";
// 同时包含 "M1T1" 和 "T1执行" 才匹配(如需匹配其一,请将 && 改为 ||)
if (message.Contains("M2T1") || message.Contains("T3执行") ||
message.Contains(" T3") || message.Contains(",T3") || message.Contains(",403)"))
{
// 将匹配到的行导入结果表
matchedRows.Add(row);
}
}
var finalRows = new List<DataRow>();
if (matchedRows.Count > 0)
{
int startIdx = 0;
string currentContent = matchedRows[0]["日志内容"]?.ToString() ?? "";
for (int i = 1; i < matchedRows.Count; i++)
{
string nextContent = matchedRows[i]["日志内容"]?.ToString() ?? "";
// 如果下一行的内容与当前块的内容不同
if (nextContent != currentContent)
{
// 将当前块的【开始行】加入结果
finalRows.Add(matchedRows[startIdx]);
// 如果当前块有连续重复(即 i - startIdx > 1),将【结束行】加入结果
if (i - startIdx > 1)
{
finalRows.Add(matchedRows[i - 1]);
}
// 重置状态,开始新的块
startIdx = i;
currentContent = nextContent;
}
}
// 处理最后一个块(循环结束后别忘了处理尾部)
finalRows.Add(matchedRows[startIdx]);
if (matchedRows.Count - startIdx > 1)
{
finalRows.Add(matchedRows[matchedRows.Count - 1]);
}
}
// 3. 构建并返回结果表
var resultTable = logTable.Clone();
foreach (var row in finalRows)
{
resultTable.ImportRow(row);
}
return resultTable;
}
public DataTable ExtractTank4CommandsWithContext(DataTable logTable)
{
// 1. 参数校验
if (logTable == null || logTable.Rows.Count == 0)
throw new ArgumentException("日志数据为空", nameof(logTable));
var matchedRows = new List<DataRow>();
// 3. 遍历原始表,匹配关键字
foreach (DataRow row in logTable.Rows)
{
string message = row["日志内容"]?.ToString() ?? "";
// 同时包含 "M1T1" 和 "T1执行" 才匹配(如需匹配其一,请将 && 改为 ||)
if (message.Contains("M2T2") || message.Contains("T4执行") ||
message.Contains(" T4") || message.Contains(",T4") || message.Contains(",404)"))
{
// 将匹配到的行导入结果表
matchedRows.Add(row);
}
}
var finalRows = new List<DataRow>();
if (matchedRows.Count > 0)
{
int startIdx = 0;
string currentContent = matchedRows[0]["日志内容"]?.ToString() ?? "";
for (int i = 1; i < matchedRows.Count; i++)
{
string nextContent = matchedRows[i]["日志内容"]?.ToString() ?? "";
// 如果下一行的内容与当前块的内容不同
if (nextContent != currentContent)
{
// 将当前块的【开始行】加入结果
finalRows.Add(matchedRows[startIdx]);
// 如果当前块有连续重复(即 i - startIdx > 1),将【结束行】加入结果
if (i - startIdx > 1)
{
finalRows.Add(matchedRows[i - 1]);
}
// 重置状态,开始新的块
startIdx = i;
currentContent = nextContent;
}
}
// 处理最后一个块(循环结束后别忘了处理尾部)
finalRows.Add(matchedRows[startIdx]);
if (matchedRows.Count - startIdx > 1)
{
finalRows.Add(matchedRows[matchedRows.Count - 1]);
}
}
// 3. 构建并返回结果表
var resultTable = logTable.Clone();
foreach (var row in finalRows)
{
resultTable.ImportRow(row);
}
return resultTable;
}
/// <summary>
/// 检查日志内容是否包含数据库指令关键词,返回匹配的关键词
/// </summary>
private string ContainsDbKeyword(string message)
{
if (string.IsNullOrWhiteSpace(message))
return null;
// 数据库指令关键词列表(不区分大小写)
string[] dbKeywords = {
"SELECT", "INSERT", "UPDATE", "DELETE", "CREATE", "ALTER",
"DROP", "TRUNCATE", "MERGE", "EXEC", "EXECUTE",
"FROM", "WHERE", "JOIN", "INNER", "LEFT", "RIGHT", "FULL", "OUTER",
"UNION", "INTERSECT", "EXCEPT", "VALUES", "SET", "WITH",
"AS", "ON", "AND", "OR", "NOT", "IN", "LIKE", "BETWEEN",
"BEGIN", "COMMIT", "ROLLBACK", "GRANT", "REVOKE",
"PROCEDURE", "FUNCTION", "TRIGGER", "INDEX", "VIEW"
};
string upperMessage = message.ToUpper();
// 检查是否包含任何关键词
foreach (string keyword in dbKeywords)
{
// 使用正则表达式确保关键词是独立的单词
string pattern = $@"\b{keyword}\b";
if (Regex.IsMatch(upperMessage, pattern, RegexOptions.IgnoreCase))
{
return keyword;
}
}
return null;
}
/// <summary>
/// 提取数据库指令及其上下文(分组版本)
/// </summary>
public DataTable ExtractDbCommandsGrouped(DataTable logTable, int contextLines = 3)
{
if (logTable == null || logTable.Rows.Count == 0)
throw new ArgumentException("日志数据为空", nameof(logTable));
var resultTable = new DataTable("DbCommandGrouped");
resultTable.Columns.Add("组ID", typeof(int));
resultTable.Columns.Add("时间戳", typeof(string));
resultTable.Columns.Add("日志内容", typeof(string));
resultTable.Columns.Add("类型", typeof(string));
resultTable.Columns.Add("行号", typeof(int));
resultTable.Columns.Add("匹配关键词", typeof(string));
// 查找所有包含数据库指令关键词的条目索引
var dbIndices = new List<int>();
var keywordMap = new Dictionary<int, string>();
for (int i = 0; i < logTable.Rows.Count; i++)
{
string message = logTable.Rows[i]["日志内容"]?.ToString() ?? "";
string matchedKeyword = ContainsDbKeyword(message);
if (!string.IsNullOrEmpty(matchedKeyword))
{
dbIndices.Add(i);
keywordMap[i] = matchedKeyword;
}
}
if (dbIndices.Count == 0)
return resultTable;
int groupId = 0;
var processedIndices = new HashSet<int>();
foreach (int dbIndex in dbIndices)
{
if (processedIndices.Contains(dbIndex))
continue;
groupId++;
var indicesInGroup = new List<int>();
// 添加数据库指令本身
indicesInGroup.Add(dbIndex);
processedIndices.Add(dbIndex);
// 添加前N条
for (int i = 1; i <= contextLines; i++)
{
int prevIndex = dbIndex - i;
if (prevIndex >= 0 && !processedIndices.Contains(prevIndex))
{
indicesInGroup.Add(prevIndex);
processedIndices.Add(prevIndex);
}
}
// 添加后N条
for (int i = 1; i <= contextLines; i++)
{
int nextIndex = dbIndex + i;
if (nextIndex < logTable.Rows.Count && !processedIndices.Contains(nextIndex))
{
indicesInGroup.Add(nextIndex);
processedIndices.Add(nextIndex);
}
}
// 按索引排序
indicesInGroup.Sort();
// 添加到结果表
foreach (int idx in indicesInGroup)
{
DataRow originalRow = logTable.Rows[idx];
string message = originalRow["日志内容"]?.ToString() ?? "";
bool isDb = idx == dbIndex || dbIndices.Contains(idx);
string matchedKeyword = isDb ? keywordMap[idx] : "";
string type;
if (isDb)
type = $"数据库指令 [{matchedKeyword}]";
else if (idx < dbIndex)
type = "前文";
else
type = "后文";
resultTable.Rows.Add(
groupId,
originalRow["时间戳"]?.ToString() ?? "",
message,
type,
idx + 1,
matchedKeyword
);
}
}
return resultTable;
}
/// <summary>
/// 获取数据库指令统计信息
/// </summary>
public Dictionary<string, int> GetDbCommandStatistics(DataTable logTable)
{
var stats = new Dictionary<string, int>();
for (int i = 0; i < logTable.Rows.Count; i++)
{
string message = logTable.Rows[i]["日志内容"]?.ToString() ?? "";
string matchedKeyword = ContainsDbKeyword(message);
if (!string.IsNullOrEmpty(matchedKeyword))
{
if (!stats.ContainsKey(matchedKeyword))
stats[matchedKeyword] = 0;
stats[matchedKeyword]++;
}
}
return stats;
}
/// <summary>
/// 导出数据库指令及其上下文为格式化字符串
/// </summary>
public string ExportDbCommandsToString(DataTable logTable, int contextLines = 3)
{
var dbContext = ExtractDbCommandsGrouped(logTable, contextLines);
if (dbContext.Rows.Count == 0)
return "未找到数据库指令";
StringBuilder sb = new StringBuilder();
sb.AppendLine("=".PadRight(100, '='));
sb.AppendLine($"数据库指令及其上下文(前后各{contextLines}条)");
sb.AppendLine("=".PadRight(100, '='));
sb.AppendLine();
// 统计信息
var stats = GetDbCommandStatistics(logTable);
sb.AppendLine("【统计信息】");
foreach (var kvp in stats.OrderByDescending(k => k.Value))
{
sb.AppendLine($" {kvp.Key}: {kvp.Value} 次");
}
sb.AppendLine();
sb.AppendLine(new string('-', 100));
sb.AppendLine();
int currentGroupId = -1;
foreach (DataRow row in dbContext.Rows)
{
int groupId = Convert.ToInt32(row["组ID"]);
string timestamp = row["时间戳"]?.ToString() ?? "";
string message = row["日志内容"]?.ToString() ?? "";
string type = row["类型"]?.ToString() ?? "";
int lineNumber = Convert.ToInt32(row["行号"]);
if (groupId != currentGroupId)
{
if (currentGroupId != -1)
{
sb.AppendLine(new string('-', 100));
sb.AppendLine();
}
currentGroupId = groupId;
sb.AppendLine($"--- 数据库指令组 {groupId} ---");
}
string prefix = type.StartsWith("数据库指令") ? "▶▶▶ " : " ";
sb.AppendLine($"{prefix}[{timestamp}] 行{lineNumber} [{type}]");
// 显示消息内容
string[] lines = message.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
foreach (string line in lines)
{
if (type.StartsWith("数据库指令"))
sb.AppendLine($" {line}");
else
sb.AppendLine($" {line}");
}
sb.AppendLine();
}
return sb.ToString();
}
/// <summary>
/// 只提取包含数据库指令的条目(不包含上下文)
/// </summary>
public DataTable ExtractDbCommandsOnly(DataTable logTable)
{
var resultTable = new DataTable("DbCommandsOnly");
resultTable.Columns.Add("时间戳", typeof(string));
resultTable.Columns.Add("日志内容", typeof(string));
resultTable.Columns.Add("匹配关键词", typeof(string));
resultTable.Columns.Add("条目索引", typeof(int));
for (int i = 0; i < logTable.Rows.Count; i++)
{
string message = logTable.Rows[i]["日志内容"]?.ToString() ?? "";
string matchedKeyword = ContainsDbKeyword(message);
if (!string.IsNullOrEmpty(matchedKeyword))
{
resultTable.Rows.Add(
logTable.Rows[i]["时间戳"]?.ToString() ?? "",
message,
matchedKeyword,
i
);
}
}
return resultTable;
}
}
}

69
MainWindow.xaml

@ -0,0 +1,69 @@
<Window x:Class="LogAnalyzer.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:LogAnalyzer"
mc:Ignorable="d"
Title="MainWindow" Height="720" Width="1080">
<Grid Margin="10">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!-- 操作栏 -->
<StackPanel Orientation="Horizontal" Grid.Row="0" Margin="0,0,0,10">
<Button Content="加载日志文件" Click="BtnLoadLog_Click" Width="100" Height="30" Margin="0,0,10,0"/>
<Button Content="搜索数据库指令" Click="Button_Click" Width="100" Height="30" Margin="0,0,10,0"/>
<Button Content="寻找T1日志" Click="Button_Click1" Width="100" Height="30" Margin="0,0,10,0"/>
<Button Content="寻找T2日志" Click="Button_Click2" Width="100" Height="30" Margin="0,0,10,0"/>
<Button Content="寻找T3日志" Click="Button_Click3" Width="100" Height="30" Margin="0,0,10,0"/>
<Button Content="寻找T4日志" Click="Button_Click4" Width="100" Height="30" Margin="0,0,10,0"/>
<TextBlock x:Name="TxtStatus" VerticalAlignment="Center" Foreground="Green"/>
</StackPanel>
<Grid Grid.Row="1" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="400"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<!-- 数据展示区 -->
<DataGrid x:Name="LogDataGrid"
Grid.Column="0"
AutoGenerateColumns="True"
CanUserAddRows="False"
IsReadOnly="True"
ItemsSource="{Binding}">
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<!-- 简单的隔行变色,提高可读性 -->
<Setter Property="Background" Value="White"/>
<Style.Triggers>
<Trigger Property="AlternationIndex" Value="1">
<Setter Property="Background" Value="#F2F2F2"/>
</Trigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
</DataGrid>
<DataGrid x:Name="LogDataGrid1"
Grid.Column="1"
AutoGenerateColumns="True"
CanUserAddRows="False"
IsReadOnly="True"
ItemsSource="{Binding}">
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<!-- 简单的隔行变色,提高可读性 -->
<Setter Property="Background" Value="White"/>
<Style.Triggers>
<Trigger Property="AlternationIndex" Value="1">
<Setter Property="Background" Value="#F2F2F2"/>
</Trigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
</DataGrid>
</Grid>
</Grid>
</Window>

96
MainWindow.xaml.cs

@ -0,0 +1,96 @@
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace LogAnalyzer
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
private readonly LogParserService _parser;
private DataTable resultTable;
public MainWindow()
{
InitializeComponent();
_parser = new LogParserService();
}
private void BtnLoadLog_Click(object sender, RoutedEventArgs e)
{
// 1. 打开文件选择对话框
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "文本文件 (*.txt)|*.txt|所有文件 (*.*)|*.*";
openFileDialog.Title = "请选择染整设备日志文件";
if (openFileDialog.ShowDialog() == true)
{
try
{
TxtStatus.Text = "正在解析...";
// 强制UI刷新状态文本
LogDataGrid.UpdateLayout();
// 2. 调用服务解析文件
// 注意:如果文件非常大,建议使用异步 Task.Run 避免界面卡顿
resultTable = _parser.ParseLogFile(openFileDialog.FileName);
//DataTable resultTable1 = _parser.ExtractDatabaseCommandsWithContext(resultTable,1);
// 3. 绑定数据到 DataGrid
// DataTable 的 DefaultView 实现了 IBindingList,适合直接绑定
LogDataGrid.ItemsSource = resultTable.DefaultView;
//LogDataGrid1.ItemsSource = resultTable1.DefaultView;
TxtStatus.Text = $"解析完成,共加载 {resultTable.Rows.Count} 条记录。";
}
catch (Exception ex)
{
MessageBox.Show($"发生错误: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
TxtStatus.Text = "加载失败";
}
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
DataTable resultTable1 = _parser.ExtractDatabaseCommandsWithContext(resultTable, 1);
LogDataGrid1.ItemsSource = resultTable1.DefaultView;
}
private void Button_Click1(object sender, RoutedEventArgs e)
{
DataTable resultTable1 = _parser.ExtractTank1CommandsWithContext(resultTable);
LogDataGrid1.ItemsSource = resultTable1.DefaultView;
}
private void Button_Click2(object sender, RoutedEventArgs e)
{
DataTable resultTable1 = _parser.ExtractTank2CommandsWithContext(resultTable);
LogDataGrid1.ItemsSource = resultTable1.DefaultView;
}
private void Button_Click3(object sender, RoutedEventArgs e)
{
DataTable resultTable1 = _parser.ExtractTank3CommandsWithContext(resultTable);
LogDataGrid1.ItemsSource = resultTable1.DefaultView;
}
private void Button_Click4(object sender, RoutedEventArgs e)
{
DataTable resultTable1 = _parser.ExtractTank4CommandsWithContext(resultTable);
LogDataGrid1.ItemsSource = resultTable1.DefaultView;
}
}
}

52
Properties/AssemblyInfo.cs

@ -0,0 +1,52 @@
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("LogAnalyzer")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("LogAnalyzer")]
[assembly: AssemblyCopyright("Copyright © 2026")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
//若要开始生成可本地化的应用程序,请设置
//.csproj 文件中的 <UICulture>CultureYouAreCodingWith</UICulture>
//在 <PropertyGroup> 中。例如,如果你使用的是美国英语。
//使用的是美国英语,请将 <UICulture> 设置为 en-US。 然后取消
//对以下 NeutralResourceLanguage 特性的注释。 更新
//以下行中的“en-US”以匹配项目文件中的 UICulture 设置。
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //主题特定资源词典所处位置
//(未在页面中找到资源时使用,
//或应用程序资源字典中找到时使用)
ResourceDictionaryLocation.SourceAssembly //常规资源词典所处位置
//(未在页面中找到资源时使用,
//、应用程序或任何主题专用资源字典中找到时使用)
)]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

71
Properties/Resources.Designer.cs

@ -0,0 +1,71 @@
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行时版本: 4.0.30319.42000
//
// 对此文件的更改可能导致不正确的行为,如果
// 重新生成代码,则所做更改将丢失。
// </auto-generated>
//------------------------------------------------------------------------------
namespace LogAnalyzer.Properties
{
/// <summary>
/// 强类型资源类,用于查找本地化字符串等。
/// </summary>
// 此类是由 StronglyTypedResourceBuilder
// 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
// 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen
// (以 /str 作为命令选项),或重新生成 VS 项目。
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources
{
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources()
{
}
/// <summary>
/// 返回此类使用的缓存 ResourceManager 实例。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager
{
get
{
if ((resourceMan == null))
{
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("LogAnalyzer.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// 重写当前线程的 CurrentUICulture 属性,对
/// 使用此强类型资源类的所有资源查找执行重写。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture
{
get
{
return resourceCulture;
}
set
{
resourceCulture = value;
}
}
}
}

117
Properties/Resources.resx

@ -0,0 +1,117 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

30
Properties/Settings.Designer.cs

@ -0,0 +1,30 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace LogAnalyzer.Properties
{
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
{
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default
{
get
{
return defaultInstance;
}
}
}
}

7
Properties/Settings.settings

@ -0,0 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="uri:settings" CurrentProfile="(Default)">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>
Loading…
Cancel
Save