From 5d55a31d8ce95e511ffb408f38ed06e81742b67e Mon Sep 17 00:00:00 2001
From: xiazhengtongxue <133085197+xiazhengtongxue@users.noreply.github.com>
Date: 星期五, 27 三月 2026 16:17:30 +0800
Subject: [PATCH] 1
---
项目代码/WCSServices/WIDESEAWCS_SystemServices/Sys_LogService.cs | 725 +++++++++++++------------------------------------------
1 files changed, 171 insertions(+), 554 deletions(-)
diff --git "a/\351\241\271\347\233\256\344\273\243\347\240\201/WCSServices/WIDESEAWCS_SystemServices/Sys_LogService.cs" "b/\351\241\271\347\233\256\344\273\243\347\240\201/WCSServices/WIDESEAWCS_SystemServices/Sys_LogService.cs"
index 9ffc2aa..21978b3 100644
--- "a/\351\241\271\347\233\256\344\273\243\347\240\201/WCSServices/WIDESEAWCS_SystemServices/Sys_LogService.cs"
+++ "b/\351\241\271\347\233\256\344\273\243\347\240\201/WCSServices/WIDESEAWCS_SystemServices/Sys_LogService.cs"
@@ -1,128 +1,4 @@
-锘�//using Microsoft.Data.SqlClient;
-//using NPOI.HSSF.Record;
-//using SkiaSharp;
-//using System;
-//using System.Collections.Generic;
-//using System.Linq;
-//using System.Linq.Expressions;
-//using System.Text;
-//using System.Threading.Tasks;
-//using WIDESEAWCS_Core.BaseServices;
-//using WIDESEAWCS_ISystemRepository;
-//using WIDESEAWCS_ISystemServices;
-//using WIDESEAWCS_Model.Models;
-
-//namespace WIDESEAWCS_SystemServices
-//{
-// public class Sys_LogService : ServiceBase<Sys_Log, ISys_LogRepository>, ISys_LogService
-// {
-// private static DateTime? _lastExecutionDate = null;
-// private readonly object _lock = new object();
-// private const string DbName = "WIDESEA_HF";
-// private const long MaxMdfSizeBytes = 8L * 1024 * 1024 * 1024; // 8GB
-// private const int TargetShrinkSizeMB = 4500; // 4.5GB
-
-// public Sys_LogService(ISys_LogRepository BaseDal) : base(BaseDal)
-// {
-
-// }
-
-// public void DeleteOldLogs()
-// {
-// // 浣跨敤閿佺‘淇濈嚎绋嬪畨鍏�
-// lock (_lock)
-// {
-// var today = DateTime.Today;
-
-// // 妫�鏌ヤ粖澶╂槸鍚﹀凡缁忔墽琛岃繃
-// if (_lastExecutionDate.HasValue && _lastExecutionDate.Value.Date == today)
-// {
-// return;
-// }
-// try
-// {
-// // 璁$畻3涓湀鍓嶇殑鏃ユ湡
-// var threeMonthsAgo = DateTime.Now.AddMonths(-3);
-// // 璁$畻3澶╁墠鐨勬棩鏈�
-// var sevenDaysAgo = DateTime.Now.AddDays(-3);
-// // 鐗瑰畾URL
-// var specificUrl = "http://11.2.30.141:10870/interfaces/api/amr/robotQuery";
-
-// // 鏋勫缓鍒犻櫎鏉′欢锛�3涓湀鍓嶇殑鏃ュ織 鎴� (3澶╁墠涓擴RL涓虹壒瀹氬湴鍧�鐨勬棩蹇�)
-// var result = BaseDal.Db.Deleteable<Sys_Log>()
-// .Where(log => log.EndDate < threeMonthsAgo ||
-// (log.EndDate < sevenDaysAgo && log.Url == specificUrl))
-// .ExecuteCommand();
-// // 鏇存柊鏈�鍚庢墽琛屾棩鏈熶负浠婂ぉ
-// _lastExecutionDate = today;
-// }
-// catch (Exception ex)
-// {
-// Console.WriteLine($"鎵ц鏃ュ織娓呯悊鏃跺彂鐢熼敊璇細{ex.Message}");
-// // 鍙戠敓閿欒鏃朵笉鏇存柊鏈�鍚庢墽琛屾棩鏈燂紝浠ヤ究閲嶈瘯
-// }
-// }
-// }
-// // 15澶╂墽琛屼竴娆℃槦鏈熷ぉ2鐐�
-// public void CheckAndManageFileSize()
-// {
-// try
-// {
-
-// // --妫�鏌ユ暟鎹簱鏂囦欢绌洪棿浣跨敤鎯呭喌
-// //SELECT
-// // name AS[鏂囦欢閫昏緫鍚峕,
-// // physical_name AS[鐗╃悊璺緞],
-// // size/ 128.0 AS[褰撳墠澶у皬MB],
-// // FILEPROPERTY(name, 'SpaceUsed') / 128.0 AS[宸茬敤绌洪棿MB],
-// // size / 128.0 - FILEPROPERTY(name, 'SpaceUsed') / 128.0 AS[鍙敤绌洪棿MB],
-// // growth / 128 AS[澧為暱閲廙B],
-// // CASE is_percent_growth
-// // WHEN 1 THEN CAST(growth AS VARCHAR) +'%'
-// // ELSE CAST(growth/ 128 AS VARCHAR) +'MB'
-// // END AS[澧為暱鏂瑰紡]
-// //FROM sys.database_files;
-// using (var connection = new SqlConnection("Data Source=.;Initial Catalog=WIDESEA_HF;User ID=sa;Password=123456;Integrated Security=False;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"))
-// {
-// connection.Open();
-
-// // 妫�鏌ユ暟鎹簱鏂囦欢澶у皬
-// var sizeCheckSql = @"SELECT name AS [鏂囦欢閫昏緫鍚峕, size/128.0 AS [褰撳墠澶у皬MB], FILEPROPERTY(name, 'SpaceUsed')/128.0 AS [宸茬敤绌洪棿MB] FROM sys.database_files WHERE name = @dbName";
-
-// using (var command = new SqlCommand(sizeCheckSql, connection))
-// {
-// command.Parameters.AddWithValue("@dbName", DbName);
-// using (var reader = command.ExecuteReader())
-// {
-// if (reader.Read())
-// {
-// double currentSizeMB = Convert.ToDouble(reader["褰撳墠澶у皬MB"]);
-// double usedSpaceMB = Convert.ToDouble(reader["宸茬敤绌洪棿MB"]);
-
-// if (currentSizeMB > MaxMdfSizeBytes / (1024 * 1024))
-// {
-// // 鎵ц鏀剁缉鏁版嵁搴�
-
-// }else
-// {
-// // 鏁寸悊纰庣墖>30%
-
-// }
-// }
-// }
-// }
-// }
-// }
-// catch (Exception ex)
-// {
-// throw new Exception($"鏂囦欢鐩戞帶澶辫触: {ex.Message}");
-// }
-// }
-
-
-// }
-//}
-using Microsoft.Data.SqlClient;
+锘縰sing Microsoft.Data.SqlClient;
using NPOI.HSSF.Record;
using SkiaSharp;
using System;
@@ -143,44 +19,17 @@
{
private static DateTime? _lastExecutionDate = null;
private static DateTime? _lastFileSizeCheckDate = null;
- private static DateTime? _lastBackupDate = null;
private readonly object _lock = new object();
private readonly object _fileSizeLock = new object();
- private readonly object _backupLock = new object();
private const string DbName = "WIDESEA_HF";
private const string ConnectionString = "Data Source=11.2.30.112;Initial Catalog=WIDESEA_HF;User ID=kuka;Password=kuka;Integrated Security=False;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
private const long MaxMdfSizeBytes = 7L * 1024 * 1024 * 1024; // 7GB
private const int TargetShrinkSizeMB = 4500; // 4.5GB
private const double FragmentationThreshold = 30.0; // 30%纰庣墖鐜囬槇鍊�
- private const int MaintenanceIntervalDays = 15; // 15澶╂墽琛屼竴娆�
- private const int BackupRetentionDays = 30; // 澶囦唤淇濈暀30澶�
- private static readonly string BackupBasePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DatabaseBackups"); // 澶囦唤鏂囦欢瀛樺偍鐩綍
- private const bool UseBackupCompression = true; // 鏄惁浣跨敤澶囦唤鍘嬬缉
- private const bool VerifyBackup = true; // 鏄惁楠岃瘉澶囦唤
- private const int MaxBackupRetryCount = 3; // 鏈�澶ч噸璇曟鏁�
- private const int BackupTimeoutSeconds = 7200; // 澶囦唤瓒呮椂鏃堕棿锛堢锛�
public Sys_LogService(ISys_LogRepository BaseDal) : base(BaseDal)
{
- // 纭繚澶囦唤鐩綍瀛樺湪
- //EnsureBackupDirectory();
- }
-
- private void EnsureBackupDirectory()
- {
- try
- {
- if (!Directory.Exists(BackupBasePath))
- {
- Directory.CreateDirectory(BackupBasePath);
- }
- }
- catch (Exception ex)
- {
- Console.WriteLine($"鍒涘缓澶囦唤鐩綍澶辫触: {ex.Message}");
- throw;
- }
}
public void DeleteOldLogs()
@@ -197,20 +46,10 @@
}
try
{
- var result = BaseDal.Db.Deleteable<Sys_Log>().ExecuteCommand();
- //// 璁$畻3涓湀鍓嶇殑鏃ユ湡
- //var threeMonthsAgo = DateTime.Now.AddMonths(-3);
- //// 璁$畻3澶╁墠鐨勬棩鏈�
- //var threeDaysAgo = DateTime.Now.AddDays(-3);
- //// 鐗瑰畾URL
- //var specificUrl = "http://11.2.30.141:10870/interfaces/api/amr/robotQuery";
- //var anonUrl = "http://11.2.30.111/anon/api/kuka/drivestatus";
-
- //// 鏋勫缓鍒犻櫎鏉′欢锛�3涓湀鍓嶇殑鏃ュ織 鎴� (3澶╁墠涓擴RL涓虹壒瀹氬湴鍧�鐨勬棩蹇�)
- //var result = BaseDal.Db.Deleteable<Sys_Log>()
- // .Where(log => log.EndDate < threeMonthsAgo ||
- // (log.EndDate < threeDaysAgo && (log.Url == specificUrl || log.Url == anonUrl)))
- // .ExecuteCommand();
+ // 鍒犻櫎5澶╁墠鐨勬棩蹇�
+ var result = BaseDal.Db.Deleteable<Sys_Log>()
+ .Where(log => log.EndDate < DateTime.Now.AddDays(-4))
+ .ExecuteCommand();
// 鏇存柊鏈�鍚庢墽琛屾棩鏈熶负浠婂ぉ
_lastExecutionDate = today;
}
@@ -223,35 +62,23 @@
}
}
- // 15澶╂墽琛屼竴娆℃槦鏈熷ぉ2鐐�
+ // 姣忓懆鏄熸湡澶�2鐐规墽琛屼竴娆�
public void CheckAndManageFileSize()
{
- // 妫�鏌ユ槸鍚︾鍚堟墽琛屾潯浠讹細鏄熸湡澶┿��2鐐瑰乏鍙炽�佽窛绂讳笂娆℃墽琛岃嚦灏�15澶�
- //if (!ShouldExecuteMaintenance())
- //{
- // return;
- //}
-
try
{
using (var connection = new SqlConnection(ConnectionString))
{
connection.Open();
- // 1. 澶囦唤鏁版嵁搴�
- //BackupDatabase();
-
- // 2. 妫�鏌ユ暟鎹簱鏂囦欢澶у皬
+ // 1. 妫�鏌ユ暟鎹簱鏂囦欢澶у皬
CheckDatabaseFileSize(connection);
- // 3. 妫�鏌ュ苟澶勭悊绱㈠紩纰庣墖
+ // 2. 妫�鏌ュ苟澶勭悊绱㈠紩纰庣墖
CheckAndHandleIndexFragmentation(connection);
- // 4. 鏇存柊缁熻淇℃伅
+ // 3. 鏇存柊缁熻淇℃伅
UpdateStatistics(connection);
-
- // 5. 娓呯悊鏃у浠�
- //CleanupOldBackups();
// 鏇存柊鏈�鍚庢鏌ユ棩鏈�
lock (_fileSizeLock)
@@ -267,205 +94,6 @@
}
}
- public void BackupDatabase()
- {
- lock (_backupLock)
- {
- try
- {
- var today = DateTime.Today;
- // 妫�鏌ヤ粖澶╂槸鍚﹀凡缁忓浠借繃
- if (_lastBackupDate.HasValue && _lastBackupDate.Value.Date == today)
- {
- return;
- }
- var timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
- var backupFileName = $"{DbName}_Full_{timestamp}.bak";
- var backupFilePath = Path.Combine(BackupBasePath, backupFileName);
-
- using (var connection = new SqlConnection(ConnectionString))
- {
- connection.Open();
- // 鑾峰彇鏁版嵁搴撴枃浠朵俊鎭紝璁$畻澶囦唤鏂囦欢澶у皬
- var dbSizeQuery = @"
- SELECT
- SUM(size/128.0) AS TotalSizeMB,
- SUM(FILEPROPERTY(name, 'SpaceUsed')/128.0) AS UsedSizeMB,
- COUNT(*) AS FileCount
- FROM sys.database_files
- WHERE type IN (0, 1)"; // 鏁版嵁鏂囦欢鍜屾棩蹇楁枃浠�
-
- double totalSizeMB = 0;
- double usedSizeMB = 0;
- int fileCount = 0;
-
- using (var cmd = new SqlCommand(dbSizeQuery, connection))
- using (var reader = cmd.ExecuteReader())
- {
- if (reader.Read())
- {
- totalSizeMB = Convert.ToDouble(reader["TotalSizeMB"]);
- usedSizeMB = Convert.ToDouble(reader["UsedSizeMB"]);
- fileCount = Convert.ToInt32(reader["FileCount"]);
- }
- }
- // 鏋勫缓澶囦唤SQL璇彞
- var backupSql = BuildBackupSql(backupFilePath);
-
- // 鎵ц澶囦唤锛堝甫閲嶈瘯鏈哄埗锛�
- ExecuteBackupWithRetry(connection, backupSql, backupFilePath);
-
- // 楠岃瘉澶囦唤鏂囦欢
- if (VerifyBackup)
- {
- VerifyBackupFile(connection, backupFilePath);
- }
-
- // 鏇存柊鏈�鍚庡浠芥棩鏈�
- _lastBackupDate = DateTime.Now;
-
- }
- }
- catch (Exception ex)
- {
- Console.WriteLine($"鏁版嵁搴撳浠藉け璐�: {ex.Message}");
- throw new Exception($"鏁版嵁搴撳浠藉け璐�: {ex.Message}", ex);
- }
- }
- }
-
- private string BuildBackupSql(string backupFilePath)
- {
- var compressionOption = UseBackupCompression ? "COMPRESSION" : "NO_COMPRESSION";
- var verifyOption = VerifyBackup ? ", CHECKSUM" : "";
-
- return $@"
- BACKUP DATABASE [{DbName}]
- TO DISK = '{backupFilePath.Replace("'", "''")}'
- WITH {compressionOption}
- {verifyOption}
- , STATS = 5
- , DESCRIPTION = 'Full database backup created by automated maintenance on {DateTime.Now:yyyy-MM-dd HH:mm:ss}'
- , MAXTRANSFERSIZE = 4194304
- , BLOCKSIZE = 65536
- , BUFFERCOUNT = 10";
- }
-
- private void ExecuteBackupWithRetry(SqlConnection connection, string backupSql, string backupFilePath)
- {
- int retryCount = 0;
- while (retryCount < MaxBackupRetryCount)
- {
- try
- {
-
- using (var cmd = new SqlCommand(backupSql, connection))
- {
- cmd.CommandTimeout = BackupTimeoutSeconds;
-
- var rowsAffected = cmd.ExecuteNonQuery();
- return; // 鎴愬姛鍒欓��鍑�
- }
- }
- catch (Exception ex)
- {
- retryCount++;
-
- if (retryCount >= MaxBackupRetryCount)
- {
- // 鍒犻櫎鍙兘鎹熷潖鐨勫浠芥枃浠�
- try
- {
- if (File.Exists(backupFilePath))
- {
- File.Delete(backupFilePath);
- }
- }
- catch { }
-
- throw new Exception($"澶囦唤澶辫触锛屽凡杈惧埌鏈�澶ч噸璇曟鏁�({MaxBackupRetryCount}娆�): {ex.Message}", ex);
- }
-
- Console.WriteLine($"澶囦唤澶辫触锛寋MaxBackupRetryCount - retryCount}娆¢噸璇曟満浼�: {ex.Message}");
- Thread.Sleep(5000); // 绛夊緟5绉掑悗閲嶈瘯
- }
- }
- }
-
- private void VerifyBackupFile(SqlConnection connection, string backupFilePath)
- {
- try
- {
-
- var verifySql = $@"
- RESTORE VERIFYONLY
- FROM DISK = '{backupFilePath.Replace("'", "''")}'
- WITH CHECKSUM";
-
- using (var cmd = new SqlCommand(verifySql, connection))
- {
- cmd.CommandTimeout = 300; // 5鍒嗛挓瓒呮椂
- cmd.ExecuteNonQuery();
- }
- }
- catch (Exception ex)
- {
- // 楠岃瘉澶辫触鏃跺垹闄ゅ浠芥枃浠�
- try
- {
- if (File.Exists(backupFilePath))
- {
- File.Delete(backupFilePath);
- }
- }
- catch { }
-
- throw new Exception($"澶囦唤鏂囦欢楠岃瘉澶辫触: {ex.Message}", ex);
- }
- }
-
- private void CleanupOldBackups()
- {
- try
- {
-
- if (!Directory.Exists(BackupBasePath))
- {
- Console.WriteLine("澶囦唤鐩綍涓嶅瓨鍦紝璺宠繃娓呯悊");
- return;
- }
-
- var cutoffDate = DateTime.Now.AddDays(-BackupRetentionDays);
- var backupFiles = Directory.GetFiles(BackupBasePath, $"{DbName}_Full_*.bak");
- int deletedCount = 0;
-
- foreach (var file in backupFiles)
- {
- try
- {
- var fileInfo = new FileInfo(file);
- if (fileInfo.CreationTime < cutoffDate)
- {
- fileInfo.Delete();
- deletedCount++;
- }
- }
- catch (Exception ex)
- {
- Console.WriteLine($"鍒犻櫎澶囦唤鏂囦欢 {file} 鏃跺嚭閿�: {ex.Message}");
- // 缁х画澶勭悊鍏朵粬鏂囦欢
- }
- }
-
-
- }
- catch (Exception ex)
- {
- Console.WriteLine($"娓呯悊鏃у浠芥椂鍑洪敊: {ex.Message}");
- // 涓嶆姏鍑哄紓甯革紝閬垮厤褰卞搷涓绘祦绋�
- }
- }
-
private bool ShouldExecuteMaintenance()
{
lock (_fileSizeLock)
@@ -477,19 +105,14 @@
{
return false;
}
- // 妫�鏌ユ椂闂存槸鍚︽槸1鐐瑰乏鍙筹紙鍏佽1:00-1:59锛�
- if (now.Hour != 1 && now.Hour != 2)
- {
- return false;
- }
- // 妫�鏌ユ槸鍚﹀凡缁忔墽琛岃繃
+ // 妫�鏌ヤ粖澶╂槸鍚﹀凡缁忔墽琛岃繃
if (_lastFileSizeCheckDate.HasValue)
{
- // 妫�鏌ヨ窛绂讳笂娆℃墽琛屾槸鍚︽弧瓒�15澶╅棿闅�
- var daysSinceLastCheck = (now - _lastFileSizeCheckDate.Value).TotalDays;
- if (daysSinceLastCheck < MaintenanceIntervalDays)
+ // 妫�鏌ユ槸鍚﹀湪浠婂ぉ鐨勫悓涓�灏忔椂鍐呮墽琛岃繃锛堥伩鍏嶉噸澶嶆墽琛岋級
+ if (_lastFileSizeCheckDate.Value.Date == now.Date)
{
+ // 濡傛灉宸茬粡鎵ц杩囷紝璺宠繃
return false;
}
}
@@ -529,11 +152,10 @@
double usedSpaceMB = Convert.ToDouble(reader["宸茬敤绌洪棿MB"]);
double freeSpaceMB = Convert.ToDouble(reader["鍙敤绌洪棿MB"]);
-
// 妫�鏌ユ槸鍚﹂渶瑕佹敹缂�
if (currentSizeMB * 1024 * 1024 > MaxMdfSizeBytes)
{
- Console.WriteLine("鏁版嵁搴撴枃浠惰秴杩�8GB锛屽紑濮嬫敹缂�...");
+ Console.WriteLine("鏁版嵁搴撴枃浠惰秴杩�7GB锛屽紑濮嬫敹缂�...");
ShrinkDatabaseFile(connection, logicalName);
}
}
@@ -551,7 +173,6 @@
{
try
{
-
// 鏀剁缉鏁版嵁搴撴枃浠�
string shrinkSql = $"DBCC SHRINKFILE (N'{logicalName}', {TargetShrinkSizeMB})";
using (var command = new SqlCommand(shrinkSql, connection))
@@ -574,7 +195,6 @@
{
try
{
-
// 鏌ヨ鎵�鏈夎〃鐨勭储寮曠鐗囩巼
string fragmentationSql = @"
SELECT
@@ -615,7 +235,6 @@
// 澶勭悊闇�瑕侀噸鏂扮粍缁囩殑绱㈠紩
if (indexesToReorganize.Any())
{
-
foreach (var index in indexesToReorganize)
{
ReorganizeIndex(connection, index.TableName, index.IndexName);
@@ -697,6 +316,7 @@
throw;
}
}
+
private void UpdateStatistics(SqlConnection connection)
{
try
@@ -715,6 +335,7 @@
throw;
}
}
+
// 鎻愪緵涓�涓柟娉曚緵浠诲姟璋冨害鍣ㄨ皟鐢�
public void ScheduleDatabaseMaintenance()
{
@@ -722,7 +343,7 @@
{
// 1. 鍒犻櫎鏃ф棩蹇�
DeleteOldLogs();
- // 妫�鏌ユ槸鍚︾鍚堟墽琛屾潯浠�
+ // 妫�鏌ユ槸鍚︾鍚堟墽琛屾潯浠讹紙姣忓懆鏄熸湡澶╂墽琛岋級
if (!ShouldExecuteMaintenance())
{
return;
@@ -737,174 +358,170 @@
}
}
+ /// <summary>
+ /// 閫掑綊鑾峰彇鏂囦欢淇℃伅
+ /// </summary>
+ /// <param name="dirPath"></param>
+ /// <returns></returns>
+ private DirInfo GetDirInfo(string dirPath)
+ {
+ //褰撳墠鏂囦欢澶�
+ var dirInfo = new DirInfo();
+ dirInfo.dirName = Path.GetFileName(dirPath);
-
-
- /// <summary>
- /// 閫掑綊鑾峰彇鏂囦欢淇℃伅
- /// </summary>
- /// <param name="dirPath"></param>
- /// <returns></returns>
- private DirInfo GetDirInfo(string dirPath)
+ //瀛愭枃浠�
+ List<FileDataInfo> files = new List<FileDataInfo>();
+ foreach (var file in Directory.GetFiles(dirPath))
{
- //褰撳墠鏂囦欢澶�
- var dirInfo = new DirInfo();
- dirInfo.dirName = Path.GetFileName(dirPath);
-
- //瀛愭枃浠�
- List<FileDataInfo> files = new List<FileDataInfo>();
- foreach (var file in Directory.GetFiles(dirPath))
+ files.Add(new FileDataInfo()
{
- files.Add(new FileDataInfo()
- {
- filePath = file,
- fileName = Path.GetFileName(file)
- });
- }
-
- //瀛愭枃浠跺す
- var dirs = Directory.GetDirectories(dirPath);
- dirInfo.dirs = new List<DirInfo>();
- foreach (var dir in dirs)
- {
- dirInfo.dirs.Add(GetDirInfo(dir));
- }
-
- //瀛愭枃浠跺す锛屼笌瀛愮洰褰曞悎骞�
- foreach (var file in files)
- {
- dirInfo.dirs.Add(new DirInfo() { dirPath = file.filePath, dirName = file.fileName });
- }
- return dirInfo;
+ filePath = file,
+ fileName = Path.GetFileName(file)
+ });
}
- /// <summary>
- /// 鑾峰彇鏃ュ織鏂囦欢鍒楄〃
- /// </summary>
- /// <returns></returns>
- public WebResponseContent GetLogList()
+ //瀛愭枃浠跺す
+ var dirs = Directory.GetDirectories(dirPath);
+ dirInfo.dirs = new List<DirInfo>();
+ foreach (var dir in dirs)
{
- WebResponseContent content = new WebResponseContent();
- string path = Path.Combine(AppContext.BaseDirectory, "log");
- if (!Directory.Exists(path))
- {
- return content.Error("鏆傛棤鏃ュ織鏂囦欢");
- }
-
- content.Data = GetDirInfo(path);
- content.OK();
- return content;
+ dirInfo.dirs.Add(GetDirInfo(dir));
}
- /// <summary>
- /// 鑾峰彇鏂囦欢鍐呭
- /// </summary>
- /// <param name="parm"></param>
- /// <returns></returns>
- public WebResponseContent GetLogData(GetLogParm parm)
+ //瀛愭枃浠跺す锛屼笌瀛愮洰褰曞悎骞�
+ foreach (var file in files)
{
- WebResponseContent content = new WebResponseContent();
- string res = "";
- //鏄惁璇诲彇鍒版渶鍚�
- bool isEnd = false;
- long startIndex = 0;
- //鏂囦欢澶у皬
- long len = 0;
- try
- {
- if (!File.Exists(parm.path))
- {
- throw new Exception($"鏂囦欢{parm.path}涓嶅瓨鍦紒");
- }
- using (FileStream fs = new FileStream(parm.path, FileMode.Open, FileAccess.Read, FileShare.Read))
- {
- //鏈�澶ц鍙栧ぇ灏�
- int maxsize = (int)(1024 * parm.maxsize_KB);
- len = fs.Length;
- long startPos = (long)(len * (parm.percent / 100));//璧峰浣嶇疆
- long readLen = len - startPos;//璇诲彇闀垮害
-
- //鍚戝墠鍔犺浇
- if (parm.topStartPos != 0)
- {
- startPos = parm.topStartPos - maxsize;
- if (startPos < 0)
- {
- //宸茶鍒拌捣濮嬩綅
- startPos = 0;
- readLen = parm.topStartPos;
- }
- else
- {
- readLen = maxsize;
- }
- }
- else
- {
- //璇诲彇澶у皬鏄惁瓒呭嚭鏈�澶ч暱搴�
- if (readLen > maxsize)
- {
- readLen = maxsize;
- }
- else
- {
- isEnd = true;
- }
- }
-
- //鍔犺浇100%锛屾寜鏈�澶у唴瀹硅鍙�
- if (parm.percent == 100)
- {
- if (len < maxsize)
- {
- startPos = 0;
- readLen = len;
- }
- else
- {
- startPos = len - maxsize;
- readLen = maxsize;
- }
- }
-
- fs.Seek(startPos, SeekOrigin.Begin);
- var buffer = new byte[readLen];
- fs.Read(buffer, 0, (int)readLen);
-
- startIndex = startPos;
- if (startPos != 0 && (parm.percent != 0 || parm.topStartPos != 0))
- {
- //涓嶆槸浠庡ご鍔犺浇锛屽垹闄ゅ彲鑳戒笉瀹屾暣鐨勭涓�琛�
- int skipCount = 0;
- for (int i = 0; i < buffer.Length; i++)
- {
- if (buffer[i] == 10)
- {
- skipCount = i;
- break;
- }
- }
- if (skipCount != 0)
- {
- //鍘绘帀鎹㈣
- skipCount++;
- //涓嬫璇诲彇鍓嶅欢
- startIndex += skipCount;
- }
- res = Encoding.UTF8.GetString(buffer.Skip(skipCount).ToArray());
- }
- else
- {
- res = Encoding.UTF8.GetString(buffer);
- }
- }
- }
- catch (Exception ex)
- {
- return content.Error(ex.Message);
- }
- return content.OK(data: new { content = res, isEnd, startIndex, len });
+ dirInfo.dirs.Add(new DirInfo() { dirPath = file.filePath, dirName = file.fileName });
}
+ return dirInfo;
}
+ /// <summary>
+ /// 鑾峰彇鏃ュ織鏂囦欢鍒楄〃
+ /// </summary>
+ /// <returns></returns>
+ public WebResponseContent GetLogList()
+ {
+ WebResponseContent content = new WebResponseContent();
+ string path = Path.Combine(AppContext.BaseDirectory, "log");
+ if (!Directory.Exists(path))
+ {
+ return content.Error("鏆傛棤鏃ュ織鏂囦欢");
+ }
+
+ content.Data = GetDirInfo(path);
+ content.OK();
+ return content;
+ }
+
+ /// <summary>
+ /// 鑾峰彇鏂囦欢鍐呭
+ /// </summary>
+ /// <param name="parm"></param>
+ /// <returns></returns>
+ public WebResponseContent GetLogData(GetLogParm parm)
+ {
+ WebResponseContent content = new WebResponseContent();
+ string res = "";
+ //鏄惁璇诲彇鍒版渶鍚�
+ bool isEnd = false;
+ long startIndex = 0;
+ //鏂囦欢澶у皬
+ long len = 0;
+ try
+ {
+ if (!File.Exists(parm.path))
+ {
+ throw new Exception($"鏂囦欢{parm.path}涓嶅瓨鍦紒");
+ }
+ using (FileStream fs = new FileStream(parm.path, FileMode.Open, FileAccess.Read, FileShare.Read))
+ {
+ //鏈�澶ц鍙栧ぇ灏�
+ int maxsize = (int)(1024 * parm.maxsize_KB);
+ len = fs.Length;
+ long startPos = (long)(len * (parm.percent / 100));//璧峰浣嶇疆
+ long readLen = len - startPos;//璇诲彇闀垮害
+
+ //鍚戝墠鍔犺浇
+ if (parm.topStartPos != 0)
+ {
+ startPos = parm.topStartPos - maxsize;
+ if (startPos < 0)
+ {
+ //宸茶鍒拌捣濮嬩綅
+ startPos = 0;
+ readLen = parm.topStartPos;
+ }
+ else
+ {
+ readLen = maxsize;
+ }
+ }
+ else
+ {
+ //璇诲彇澶у皬鏄惁瓒呭嚭鏈�澶ч暱搴�
+ if (readLen > maxsize)
+ {
+ readLen = maxsize;
+ }
+ else
+ {
+ isEnd = true;
+ }
+ }
+
+ //鍔犺浇100%锛屾寜鏈�澶у唴瀹硅鍙�
+ if (parm.percent == 100)
+ {
+ if (len < maxsize)
+ {
+ startPos = 0;
+ readLen = len;
+ }
+ else
+ {
+ startPos = len - maxsize;
+ readLen = maxsize;
+ }
+ }
+
+ fs.Seek(startPos, SeekOrigin.Begin);
+ var buffer = new byte[readLen];
+ fs.Read(buffer, 0, (int)readLen);
+
+ startIndex = startPos;
+ if (startPos != 0 && (parm.percent != 0 || parm.topStartPos != 0))
+ {
+ //涓嶆槸浠庡ご鍔犺浇锛屽垹闄ゅ彲鑳戒笉瀹屾暣鐨勭涓�琛�
+ int skipCount = 0;
+ for (int i = 0; i < buffer.Length; i++)
+ {
+ if (buffer[i] == 10)
+ {
+ skipCount = i;
+ break;
+ }
+ }
+ if (skipCount != 0)
+ {
+ //鍘绘帀鎹㈣
+ skipCount++;
+ //涓嬫璇诲彇鍓嶅欢
+ startIndex += skipCount;
+ }
+ res = Encoding.UTF8.GetString(buffer.Skip(skipCount).ToArray());
+ }
+ else
+ {
+ res = Encoding.UTF8.GetString(buffer);
+ }
+ }
+ }
+ catch (Exception ex)
+ {
+ return content.Error(ex.Message);
+ }
+ return content.OK(data: new { content = res, isEnd, startIndex, len });
+ }
+ }
}
\ No newline at end of file
--
Gitblit v1.9.3