Skip to content

Commit

Permalink
update logging message
Browse files Browse the repository at this point in the history
  • Loading branch information
Lightczx committed Feb 18, 2024
1 parent d6c7df1 commit 32b1b69
Show file tree
Hide file tree
Showing 13 changed files with 42 additions and 66 deletions.
52 changes: 27 additions & 25 deletions src/Snap.Hutao/Snap.Hutao/Core/Caching/ImageCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,20 @@ internal sealed partial class ImageCache : IImageCache, IImageCacheFilePathOpera
private string? baseFolder;
private string? cacheFolder;

private string CacheFolder
{
get => LazyInitializer.EnsureInitialized(ref cacheFolder, () =>
{
baseFolder ??= serviceProvider.GetRequiredService<RuntimeOptions>().LocalCache;
DirectoryInfo info = Directory.CreateDirectory(Path.Combine(baseFolder, CacheFolderName));
return info.FullName;
});
}

/// <inheritdoc/>
public void RemoveInvalid()
{
RemoveInternal(Directory.GetFiles(GetCacheFolder()).Where(file => IsFileInvalid(file, false)));
RemoveCore(Directory.GetFiles(CacheFolder).Where(file => IsFileInvalid(file, false)));
}

/// <inheritdoc/>
Expand All @@ -62,7 +72,7 @@ public void Remove(in ReadOnlySpan<Uri> uriForCachedItems)
return;
}

string folder = GetCacheFolder();
string folder = CacheFolder;
string[] files = Directory.GetFiles(folder);

List<string> filesToDelete = [];
Expand All @@ -75,16 +85,16 @@ public void Remove(in ReadOnlySpan<Uri> uriForCachedItems)
}
}

RemoveInternal(filesToDelete);
RemoveCore(filesToDelete);
}

/// <inheritdoc/>
public async ValueTask<ValueFile> GetFileFromCacheAsync(Uri uri)
{
string fileName = GetCacheFileName(uri);
string filePath = Path.Combine(GetCacheFolder(), fileName);
string filePath = Path.Combine(CacheFolder, fileName);

if (File.Exists(filePath) && new FileInfo(filePath).Length != 0)
if (!IsFileInvalid(filePath))
{
return filePath;
}
Expand All @@ -94,10 +104,12 @@ public async ValueTask<ValueFile> GetFileFromCacheAsync(Uri uri)
{
if (concurrentTasks.TryAdd(fileName, taskCompletionSource.Task))
{
logger.LogDebug("Begin downloading image file from '{Uri}' to '{File}'", uri, filePath);
await DownloadFileAsync(uri, filePath).ConfigureAwait(false);
}
else if (concurrentTasks.TryGetValue(fileName, out Task? task))
{
logger.LogDebug("Waiting for a queued image download task to complete for '{Uri}'", uri);
await task.ConfigureAwait(false);
}

Expand All @@ -115,7 +127,7 @@ public async ValueTask<ValueFile> GetFileFromCacheAsync(Uri uri)
public ValueFile GetFileFromCategoryAndName(string category, string fileName)
{
Uri dummyUri = Web.HutaoEndpoints.StaticRaw(category, fileName).ToUri();
return Path.Combine(GetCacheFolder(), GetCacheFileName(dummyUri));
return Path.Combine(CacheFolder, GetCacheFileName(dummyUri));
}

private static string GetCacheFileName(Uri uri)
Expand All @@ -137,32 +149,36 @@ private static bool IsFileInvalid(string file, bool treatNullFileAsInvalid = tru
return fileInfo.Length == 0;
}

private void RemoveInternal(IEnumerable<string> filePaths)
private void RemoveCore(IEnumerable<string> filePaths)
{
foreach (string filePath in filePaths)
{
try
{
File.Delete(filePath);
logger.LogInformation("Remove cached image succeed:{File}", filePath);
}
catch (Exception ex)
{
logger.LogWarning(ex, "Remove Cache Image Failed:{File}", filePath);
logger.LogWarning(ex, "Remove cached image failed:{File}", filePath);
}
}
}

[SuppressMessage("", "SH003")]
private async Task DownloadFileAsync(Uri uri, string baseFile)
{
logger.LogInformation("Begin downloading for {Uri}", uri);

int retryCount = 0;
HttpClient httpClient = httpClientFactory.CreateClient(nameof(ImageCache));
while (retryCount < 3)
{
using (HttpResponseMessage message = await httpClient.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false))
{
if (message.RequestMessage is { RequestUri: { } target } && target != uri)
{
logger.LogDebug("The Request '{Source}' has been redirected to '{Target}'", uri, target);
}

if (message.IsSuccessStatusCode)
{
using (Stream httpStream = await message.Content.ReadAsStreamAsync().ConfigureAwait(false))
Expand All @@ -181,7 +197,7 @@ private async Task DownloadFileAsync(Uri uri, string baseFile)
{
retryCount++;
TimeSpan delay = message.Headers.RetryAfter?.Delta ?? retryCountToDelay[retryCount];
logger.LogInformation("Retry {Uri} after {Delay}.", uri, delay);
logger.LogInformation("Retry download '{Uri}' after {Delay}.", uri, delay);
await Task.Delay(delay).ConfigureAwait(false);
break;
}
Expand All @@ -192,18 +208,4 @@ private async Task DownloadFileAsync(Uri uri, string baseFile)
}
}
}

private string GetCacheFolder()
{
if (cacheFolder is not null)
{
return cacheFolder;
}

baseFolder ??= serviceProvider.GetRequiredService<RuntimeOptions>().LocalCache;
DirectoryInfo info = Directory.CreateDirectory(Path.Combine(baseFolder, CacheFolderName));
cacheFolder = info.FullName;

return cacheFolder;
}
}
4 changes: 2 additions & 2 deletions src/Snap.Hutao/Snap.Hutao/Core/Database/QueryableExtension.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ namespace Snap.Hutao.Core.Database;
internal static class QueryableExtension
{
/// <summary>
/// source.Where(predicate).ExecuteDelete()
/// <code>source.Where(predicate).ExecuteDelete()</code>
/// </summary>
/// <typeparam name="TSource">源类型</typeparam>
/// <param name="source">源</param>
Expand All @@ -27,7 +27,7 @@ public static int ExecuteDeleteWhere<TSource>(this IQueryable<TSource> source, E
}

/// <summary>
/// source.Where(predicate).ExecuteDeleteAsync(token)
/// <code>source.Where(predicate).ExecuteDeleteAsync(token)</code>
/// </summary>
/// <typeparam name="TSource">源类型</typeparam>
/// <param name="source">源</param>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ namespace Snap.Hutao.Core.DependencyInjection.Abstraction;
/// <summary>
/// 可转换类型服务
/// </summary>
[Obsolete("Not useful anymore")]
internal interface ICastService
{
}

This file was deleted.

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ internal static class CastServiceExtension
/// <typeparam name="T">目标转换类型</typeparam>
/// <param name="service">对象</param>
/// <returns>转换类型后的对象</returns>
[Obsolete("Not useful anymore")]
public static T? As<T>(this ICastService service)
where T : class
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,13 @@ private static void InitializeCulture(this IServiceProvider serviceProvider)
CultureOptions cultureOptions = serviceProvider.GetRequiredService<CultureOptions>();
cultureOptions.SystemCulture = CultureInfo.CurrentCulture;

ILogger<CultureOptions> logger = serviceProvider.GetRequiredService<ILogger<CultureOptions>>();
logger.LogDebug("System Culture: {System}", cultureOptions.SystemCulture);

CultureInfo cultureInfo = cultureOptions.CurrentCulture;

logger.LogDebug("Current Culture: {Current}", cultureInfo);

CultureInfo.DefaultThreadCurrentCulture = cultureInfo;
CultureInfo.DefaultThreadCurrentUICulture = cultureInfo;
CultureInfo.CurrentCulture = cultureInfo;
Expand All @@ -63,6 +68,7 @@ private static void InitializeCulture(this IServiceProvider serviceProvider)
SH.Culture = cultureInfo;
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void InitializeConsoleWindow(this IServiceProvider serviceProvider)
{
_ = serviceProvider.GetRequiredService<ConsoleWindowLifeTime>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,17 +47,13 @@ private static void AddDbContextCore(IServiceProvider provider, DbContextOptions
{
if (context.Database.GetPendingMigrations().Any())
{
#if DEBUG
System.Diagnostics.Debug.WriteLine("[Database] Performing AppDbContext Migrations");
#endif
context.Database.Migrate();
}
}

builder
#if DEBUG
.EnableSensitiveDataLogging()
#endif
.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking)
.UseSqlite(sqlConnectionString);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,6 @@ public MeasureExecutionToken(in ValueStopwatch stopwatch, ILogger logger, string

public void Dispose()
{
logger.LogInformation("{Caller} toke {Time} ms", callerName, stopwatch.GetElapsedTime().TotalMilliseconds);
logger.LogDebug("{Caller} toke {Time} ms", callerName, stopwatch.GetElapsedTime().TotalMilliseconds);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ namespace Snap.Hutao.Core.ExceptionService;
/// 数据库损坏异常
/// </summary>
[HighQuality]
[Obsolete("Use HutaoException instead")]
internal sealed class DatabaseCorruptedException : Exception
{
/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ namespace Snap.Hutao.Core.ExceptionService;
/// 用户的计算机中的某些设置不符合要求
/// </summary>
[HighQuality]
[Obsolete("Use HutaoException instead")]
internal sealed class RuntimeEnvironmentException : Exception
{
/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ namespace Snap.Hutao.Core.ExceptionService;
/// </summary>
[HighQuality]
[System.Diagnostics.StackTraceHidden]
[Obsolete("Use HutaoException instead")]
internal static class ThrowHelper
{
[DoesNotReturn]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ namespace Snap.Hutao.Core.ExceptionService;
/// 用户数据损坏异常
/// </summary>
[HighQuality]
[Obsolete("Use HutaoException instead")]
internal sealed class UserdataCorruptedException : Exception
{
/// <summary>
Expand Down

0 comments on commit 32b1b69

Please sign in to comment.