104 lines
3.4 KiB
C#
104 lines
3.4 KiB
C#
using System.Text;
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
namespace ConsoleApp2.Services;
|
|
|
|
public class ErrorRecorder
|
|
{
|
|
private readonly string _outputDir = "./ErrorRecords";
|
|
private readonly ILogger _logger;
|
|
private readonly Dictionary<string, int> _logIndex = new();
|
|
|
|
/// <summary>
|
|
/// 当次执行标识
|
|
/// </summary>
|
|
private static readonly string UID = DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss");
|
|
|
|
public ErrorRecorder(ILogger<ErrorRecorder> logger)
|
|
{
|
|
_logger = logger;
|
|
var dir = Path.Combine(_outputDir, UID);
|
|
if (!Directory.Exists(dir))
|
|
{
|
|
Directory.CreateDirectory(dir);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 记录已知表名发生错误的SQL
|
|
/// </summary>
|
|
/// <param name="commandText"></param>
|
|
/// <param name="tableName"></param>
|
|
/// <param name="exception"></param>
|
|
public async Task LogErrorSqlAsync(string commandText, string tableName, Exception exception)
|
|
{
|
|
if (!_logIndex.TryGetValue(tableName, out var idx))
|
|
{
|
|
idx = 0;
|
|
_logIndex.Add(tableName, idx);
|
|
}
|
|
var filePath = Path.Combine(_outputDir, UID, $"{tableName}-{idx}.errlog");
|
|
|
|
if (File.Exists(filePath) && new FileInfo(filePath).Length > 10 * 1024 * 1024)
|
|
{
|
|
++idx;
|
|
_logIndex[tableName] = idx;
|
|
filePath = Path.Combine(_outputDir, UID, $"{tableName}-{idx}.errlog");
|
|
}
|
|
var content = $"""
|
|
/* [{DateTime.Now:yyyy-MM-dd HH:mm:ss}]
|
|
* Error occurred when export table '{tableName}':
|
|
* {exception.Message}
|
|
*/
|
|
|
|
{commandText}
|
|
|
|
|
|
""";
|
|
await File.AppendAllTextAsync(filePath, content, Encoding.UTF8);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 记录发生错误的SQL
|
|
/// </summary>
|
|
/// <param name="commandText"></param>
|
|
/// <param name="exception"></param>
|
|
public async Task LogErrorSqlAsync(string commandText, Exception exception)
|
|
{
|
|
var filePath = Path.Combine(_outputDir, UID, "UnknownTables.errlog");
|
|
var content = $"""
|
|
/* [{DateTime.Now:yyyy-MM-dd HH:mm:ss}]
|
|
* Error occurred when export table with unknown table name:
|
|
* {exception.Message}
|
|
*/
|
|
{commandText}
|
|
|
|
|
|
""";
|
|
await File.AppendAllTextAsync(filePath, content, Encoding.UTF8);
|
|
}
|
|
|
|
public async Task LogErrorRecordsAsync(IDictionary<string, DataRecord> records, Exception exception)
|
|
{
|
|
var pathDict = new Dictionary<string, string>();
|
|
foreach (var pair in records)
|
|
{
|
|
if(!pathDict.TryGetValue(pair.Key, out var path))
|
|
{
|
|
path = Path.Combine(_outputDir, UID, "ErrorRecords", $"{pair.Key}.errlog");
|
|
pathDict.Add(pair.Key, path);
|
|
}
|
|
//
|
|
await File.AppendAllTextAsync(path, string.Join(',', pair.Value.Fields));
|
|
}
|
|
}
|
|
|
|
public void ClearErrorRecords()
|
|
{
|
|
_logger.LogInformation("***** Clear error records *****");
|
|
foreach (var file in Directory.GetFiles(_outputDir, "*.errlog", SearchOption.AllDirectories))
|
|
{
|
|
File.Delete(file);
|
|
}
|
|
}
|
|
} |