asp.net core 6網站藉由Serilog上線添加只有在發生error跟例外的txt log檔並限制只保留2天以內的

 





~\Program.cs
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
using BingoSys.Data;
using BingoSys.Hubs;
using BingoSys.Services;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.EntityFrameworkCore;
using Serilog;
using Serilog.Events;
using System.Text.Encodings.Web;
using System.Text.Unicode;

var builder = WebApplication.CreateBuilder(args);


// 初始化 Serilog,名稱像是 myapp_20231029.txt,定時只保留最近3天的日誌檔案
Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)  // 過濾 Microsoft 日誌
    .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Error) // 只有在出現錯誤時才記錄 EF Core 的日誌
    .WriteTo.File("logs/myapp_.txt", rollingInterval: RollingInterval.Day, retainedFileCountLimit: 2)// 每日分割日誌
    .CreateLogger();


builder.Logging.AddSerilog();  // 將 Serilog 加入到日誌記錄系統

builder.Services.AddSingleton(HtmlEncoder.Create(UnicodeRanges.All));

var app = builder.Build();

var scope = app.Services.CreateScope();
bool IsCreated = scope.ServiceProvider.GetRequiredService<AppDbContext>().Database.EnsureCreated();


// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseResponseCaching();
app.UseRouting();

app.UseSession();//Session 中間件需要在 UseRouting 和 UseEndpoints 之間,且在使用任何需要 Session 的功能之前。

app.UseAuthentication();

app.UseAuthorization();



app.MapAreaControllerRoute(
    name: "Admin",
    areaName: "Admin",
    pattern: "Admin/{controller=Home}/{action=Index}/{id?}"
);

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

try
{
    AppDbInitializer.Seed(app);
    AppDbInitializer.SeedUsersAndRolesAsync(app).Wait();
    AppDbInitializer.SeedBetTypeAndBetSelection(app).Wait();
    //AppDbInitializer.SeedGameRounds(app).Wait();
}
catch (Exception ex)
{
    Log.Error($"Initialization error: {ex.Message}");
}

app.Run();

// 這裡關閉和清空日誌
Log.CloseAndFlush();

 Serilog 配置,通過設定最小日誌級別來實現,
只有在出現錯誤時才會記錄 EF Core 的 SQL 日誌。


這些調整可幫助開發者更有效地管理應用程式的日誌,可以保證只有在發生錯誤時,相關的日誌才會被記錄,從而減少不必要的日誌信息。


在資料庫efcore 層面也可添加
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
using BingoSys.Data;
using BingoSys.Hubs;
using BingoSys.Services;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.UI.Services;
using Microsoft.EntityFrameworkCore;
using Serilog;
using Serilog.Events;
using System.Text.Encodings.Web;
using System.Text.Unicode;

var builder = WebApplication.CreateBuilder(args);


// 初始化 Serilog,名稱像是 myapp_20231029.txt,定時只保留最近3天的日誌檔案
Log.Logger = new LoggerConfiguration()
    .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)  // 過濾 Microsoft 日誌
    .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Error) // 只有在出現錯誤時才記錄 EF Core 的日誌
    .WriteTo.File("logs/myapp_.txt", rollingInterval: RollingInterval.Day, retainedFileCountLimit: 2)// 每日分割日誌
    .CreateLogger();


builder.Logging.AddSerilog();  // 將 Serilog 加入到日誌記錄系統

builder.Services.AddSingleton(HtmlEncoder.Create(UnicodeRanges.All));

builder.Services.AddHostedService<MyBackgroundService>();
//builder.Services.AddSingleton<MyBackgroundService>(sp => sp.GetServices<IHostedService>().OfType<MyBackgroundService>().Single());
builder.Services.AddResponseCaching();
// Add services to the container.
builder.Services.AddDbContext<AppDbContext>(options => options.UseSqlServer(builder.Configuration
                                                .GetConnectionString("BingoDbConn"))
                                                .LogTo(Console.WriteLine, new[] { DbLoggerCategory.Database.Command.Name }, LogLevel.Error)
                                                .EnableSensitiveDataLogging());

builder.Services.AddIdentity<AppUser, IdentityRole>(options =>
{
    options.SignIn.RequireConfirmedAccount = false;
    options.User.RequireUniqueEmail = false;
    options.SignIn.RequireConfirmedEmail = false;
    options.Password.RequireDigit = false;
    options.Password.RequiredLength = 6;
    options.User.AllowedUserNameCharacters = null; // UserName可用中文
    options.Password.RequireNonAlphanumeric = false;
    options.Password.RequireUppercase = false;
    options.Password.RequireLowercase = false;
}).AddEntityFrameworkStores<AppDbContext>().AddDefaultTokenProviders();

builder.Services.AddTransient<IEmailSender, EmailService>();

builder.Services.AddControllersWithViews();

builder.Services.AddSignalR();
builder.Services.AddScoped<TimerService>();

builder.Services.AddTransient<GameRoundService>();


builder.Services.AddSession(options =>
{
    options.IdleTimeout = TimeSpan.FromMinutes(30);
    options.Cookie.HttpOnly = true;
    options.Cookie.IsEssential = true;
});


var app = builder.Build();

var scope = app.Services.CreateScope();
bool IsCreated = scope.ServiceProvider.GetRequiredService<AppDbContext>().Database.EnsureCreated();


// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseResponseCaching();
app.UseRouting();

app.UseSession();//Session 中間件需要在 UseRouting 和 UseEndpoints 之間,且在使用任何需要 Session 的功能之前。

app.UseAuthentication();

app.UseAuthorization();

app.MapHub<DefaultHub>("/meeting");

app.MapAreaControllerRoute(
    name: "Admin",
    areaName: "Admin",
    pattern: "Admin/{controller=Home}/{action=Index}/{id?}"
);

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

try
{
    AppDbInitializer.Seed(app);
    AppDbInitializer.SeedUsersAndRolesAsync(app).Wait();
    AppDbInitializer.SeedBetTypeAndBetSelection(app).Wait();
    //AppDbInitializer.SeedGameRounds(app).Wait();
}
catch (Exception ex)
{
    Log.Error($"Initialization error: {ex.Message}");
}

app.Run();

// 這裡關閉和清空日誌
Log.CloseAndFlush();


設定 EF Core 日誌級別
在 AddDbContext 方法中,使用 LogTo 方法來指定 EF Core 的日誌級別。只在出現錯誤時記錄日誌。只在 LogLevel.Error 級別記錄 SQL 命令

留言

這個網誌中的熱門文章

何謂淨重(Net Weight)、皮重(Tare Weight)與毛重(Gross Weight)

Architecture(架構) 和 Framework(框架) 有何不同?_軟體設計前的事前規劃的藍圖概念

經得起原始碼資安弱點掃描的程式設計習慣培養(五)_Missing HSTS Header