A:增加数据库配置和使用

This commit is contained in:
jimmy committed 2025-11-18 11:14:56 +08:00
1 parent 53d1dd2dbf
commit f7660c49e8
86 files changed
+7401 -271

No files matched your search

+1
View File
@@ -7,6 +7,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="8.0.0" />
<PackageReference Include="Serilog" Version="4.0.0" />
+15 -1
View File
@@ -32,6 +32,21 @@ app.UseSharpRequestLogging(); // 可选:请求日志
app.Run();
```
// WPF/WinForms/任意桌面
```csharp
using Sharp.Log;
using Microsoft.Extensions.Configuration;
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: true)
.AddEnvironmentVariables()
.Build();
using var loggerFactory = SharpLogDefaults.CreateLoggerFactory(configuration);
var logger = loggerFactory.CreateLogger<App>();
logger.LogInformation("桌面程序已启动");
```
无需任何 `appsettings.json`,即可获得:
- Console 文本输出
- 文件 JSON 输出:`logs/app-.log`(按天滚动,保留 30 个文件,异步写)
@@ -98,4 +113,3 @@ app.Run();
```
日志要简单可靠:一行接入,默认即用,可配更强。
```
+98
View File
@@ -0,0 +1,98 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Sharp.Log.Extensions;
using Sharp.Log.Options;
namespace Sharp.Log;
/// <summary>
/// 提供针对桌面程序/简单控制台的“开箱即用”日志工厂。
/// </summary>
public static class SharpLogDefaults
{
/// <summary>
/// 创建一个已预置 Sharp.Log 的 <see cref="ILoggerFactory"/>。
/// 适用于无需完整 HostBuilder 的场景(WPF、WinForms、单元测试等)。
/// </summary>
/// <param name="configuration">可选:传入已加载的 IConfiguration,用于绑定 SharpLog 节点。</param>
/// <param name="environmentName">可选:覆盖环境名,默认读取 DOTNET/ASPNETCORE_ENVIRONMENT。</param>
/// <param name="configure">可选:对 <see cref="SharpLogOptions"/> 做额外调整。</param>
public static ILoggerFactory CreateLoggerFactory(
IConfiguration? configuration = null,
string? environmentName = null,
Action<SharpLogOptions>? configure = null)
{
var config = configuration ?? new ConfigurationBuilder().Build();
var services = new ServiceCollection();
services.AddSingleton(config);
services.AddSingleton<IHostEnvironment>(new SimpleHostEnvironment(environmentName));
services.AddLogging(builder =>
{
builder.ClearProviders();
builder.AddSharpLog(configure);
});
var provider = services.BuildServiceProvider();
return new DisposableLoggerFactory(provider);
}
private sealed class DisposableLoggerFactory : ILoggerFactory
{
private readonly ServiceProvider _provider;
private readonly ILoggerFactory _inner;
public DisposableLoggerFactory(ServiceProvider provider)
{
_provider = provider;
_inner = provider.GetRequiredService<ILoggerFactory>();
}
public void AddProvider(ILoggerProvider provider) => _inner.AddProvider(provider);
public ILogger CreateLogger(string categoryName) => _inner.CreateLogger(categoryName);
public void Dispose()
{
_inner.Dispose();
_provider.Dispose();
}
}
private sealed class SimpleHostEnvironment : IHostEnvironment
{
public SimpleHostEnvironment(string? environmentName)
{
EnvironmentName = environmentName
?? Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT")
?? Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")
?? Environments.Production;
ApplicationName = TryGetEntryAssemblyName()
?? AppDomain.CurrentDomain.FriendlyName
?? "SharpApp";
ContentRootPath = AppContext.BaseDirectory;
ContentRootFileProvider = new NullFileProvider();
}
public string EnvironmentName { get; set; }
public string ApplicationName { get; set; }
public string ContentRootPath { get; set; }
public IFileProvider ContentRootFileProvider { get; set; }
private static string? TryGetEntryAssemblyName()
{
try
{
return System.Reflection.Assembly.GetEntryAssembly()?.GetName().Name;
}
catch
{
return null;
}
}
}
}
+23 -7
View File
@@ -32,7 +32,24 @@ app.MapGet("/", () => Results.Ok("ok"));
app.Run();
```
## 3. 可选配置(appsettings.json)
## 3. 桌面/WPF/WinForms
```csharp
using Microsoft.Extensions.Configuration;
using Sharp.Log;
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: true)
.AddEnvironmentVariables()
.Build();
using var loggerFactory = SharpLogDefaults.CreateLoggerFactory(configuration);
var logger = loggerFactory.CreateLogger<App>();
logger.LogInformation("桌面程序已启动");
```
无需 HostBuilder,即可获得默认 Console + 滚动文件输出;同样支持 `SharpLog` 配置节/环境变量。
## 4. 可选配置(appsettings.json)
添加 `SharpLog` 配置节(可省略)。
```json
{
@@ -66,7 +83,7 @@ app.Run();
- `SHARPLOG__FILE__PATH=/var/logs/app-.log`
- `SHARPLOG__FILE__RETAINEDFILECOUNTLIMIT=7`
## 4. 常见定制
## 5. 常见定制
- 仅文件输出(关闭 Console):
```csharp
builder.Logging.AddSharpLog(o => { o.UseConsole = false; });
@@ -84,17 +101,17 @@ app.Run();
builder.Logging.AddSharpLog(o => { o.Enrich.Application = "MyApp"; });
```
## 5. 与现有 Provider 协作
## 6. 与现有 Provider 协作
- 默认不清空 Provider;若希望仅用 Sharp.Log,可在应用中先执行 `ClearProviders()` 再调用 `AddSharpLog()`。
- 如将 `UseSerilog` 设为 `false`,不会注入 Serilog Provider,请保留框架自带 Console Provider(不要 `ClearProviders()`)。
## 6. 请求日志中间件
## 7. 请求日志中间件
启用后会记录:请求开始、结束(状态码与耗时)、异常。
```csharp
app.UseSharpRequestLogging();
```
## 7. 结构化与上下文
## 8. 结构化与上下文
日志条目自动包含:
- `Application`、`Environment`、`MachineName`、`ProcessId`、`ThreadId`
- `TraceId`、`SpanId`(来自 `Activity.Current`)
@@ -105,7 +122,7 @@ using var scope = logger.BeginScope(new Dictionary<string, object>{ ["UserId"] =
logger.LogInformation("User {UserId} logged in", userId);
```
## 8. 测试建议
## 9. 测试建议
- 在测试中为文件输出设置临时目录:
```csharp
builder.Logging.AddSharpLog(o =>
@@ -117,4 +134,3 @@ logger.LogInformation("User {UserId} logged in", userId);
```
如需更多示例,请参考本仓库的测试项目 `test/Log.Test`。