我首先使用 Entity Framework Core 和代码。我想开始使用 Serilog.Sinks.MsSqlServer 记录到我的数据库。
由于我可能想要查询日志,因此我正在考虑通过 EF Core 创建Logs表,然后告诉 Serilog 不要创建该表。
有人有使用 Entity Framework 创建Logs表的经验吗?我还没有找到任何这方面的例子。我不知道Serilog.Sinks.MsSqlServer是否有查询日志的工具。创建表然后自己查询是否有意义?
最佳答案
首先,使用 EF Core 创建表来查询它是有意义的。我之前已经这样做过以查询一些日志(例如在管理仪表板中),并且这样做非常容易:
<强>1。日志实体定义:
public class LogEntry
{
public int Id { get; set; }
public string Message { get; set; }
public string MessageTemplate { get; set; }
public string Level { get; set; }
public DateTime TimeStamp { get; set; }
public string? Exception { get; set; }
public string? Properties { get; set; }
public string? LogEvent { get; set; }
}
此类具有 Serilog 接收器将日志写入数据库所需的所有属性。
<强>2。 DbContext
配置:
public class ApplicationDbContext : DbContext
{
public DbSet<LogEntry> Logs { get; set; }
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) :base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfigurationsFromAssembly(typeof(Program).Assembly);
}
}
我总是使用 ApplyConfigurationsFromAssembly()
来配置我的数据库实体,因此我还需要为 LogEntry
创建一个配置类,如下所示:
public class LogEntryConfiguration : IEntityTypeConfiguration<LogEntry>
{
public void Configure(EntityTypeBuilder<LogEntry> builder)
{
builder.ToTable("Logs");
builder.HasKey(p => p.Id);
builder.Property(p => p.Exception)
.IsRequired(false);
builder.Property(p => p.Properties)
.IsRequired(false);
builder.Property(p => p.LogEvent)
.IsRequired(false);
builder.Property(p => p.TimeStamp)
.HasColumnType("datetime");
builder.Property(p => p.Level)
.HasMaxLength(16);
}
}
当然你不必这样配置,但属性需要这样配置。
<强>3。配置 Serilog 接收器:
var logger = new LoggerConfiguration()
.ReadFrom.Configuration(builder.Configuration)
.Enrich.FromLogContext()
.WriteTo.MSSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"),
new MSSqlServerSinkOptions()
{
AutoCreateSqlDatabase = false,
AutoCreateSqlTable = false,
TableName = "Logs"
})
.CreateLogger();
builder.Logging.ClearProviders();
builder.Logging.AddSerilog(logger);
在此示例中,我从代码配置了 Serilog,但也可以在 appsettings.json
中完成,如文档 here 中所述。 。
这里重要的是 AutoCreateSqlDatabase = false
、AutoCreateSqlTable = false
,因此接收器不会尝试自行创建 Logs
表。
之后,接收器写入我们创建的 Logs
表,您可以使用 EF Core 查询该表,就像查询其他表一样。
关于c# - 将 Serilog.Sinks.MsSqlServer 与 Entity Framework Core 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76981482/