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 _logIndex = new(); /// /// 当次执行标识 /// private static readonly string UID = DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss"); public ErrorRecorder(ILogger logger) { _logger = logger; var dir = Path.Combine(_outputDir, UID); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } } /// /// 记录已知表名发生错误的SQL /// /// /// /// 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); } /// /// 记录发生错误的SQL /// /// /// 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 records, Exception exception) { var pathDict = new Dictionary(); 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); } } }