配置serilog
IDictionary<string, ColumnWriterBase> columnOptions = new Dictionary<string, ColumnWriterBase>
{
{ "message", new RenderedMessageColumnWriter(NpgsqlDbType.Text) },
{ "message_template", new MessageTemplateColumnWriter(NpgsqlDbType.Text) },
{ "level", new LevelColumnWriter(true, NpgsqlDbType.Varchar) },
{ "raise_date", new TimestampColumnWriter(NpgsqlDbType.TimestampTz) },
{ "exception", new ExceptionColumnWriter(NpgsqlDbType.Text) },
{ "properties", new LogEventSerializedColumnWriter(NpgsqlDbType.Jsonb) },
{ "props_test", new PropertiesColumnWriter(NpgsqlDbType.Jsonb) },
{ "machine_name", new SinglePropertyColumnWriter("MachineName", PropertyWriteMethod.ToString, NpgsqlDbType.Text, "l") },
};
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.Destructure.UsingAttributes()
.MinimumLevel.Debug()
.WriteTo.PostgreSQL(
connectionString: connectionStringHere,
tableName: "Logs",
columnOptions: columnOptions,
needAutoCreateTable: false,
schemaName: "public",
useCopy: true,
queueLimit: 3000,
batchSizeLimit: 40,
period: new TimeSpan(0, 0, 10),
formatProvider: null)
.CreateLogger();
然后您可以创建映射这些数据库字段的 C# 类
[Keyless]
[Table("Logs")]
public class ActivityLogs
{
[Column("message")]
public string Message { get; set; }
[Column("message_template")]
public string MessageTemplate { get; set; }
[Column("level")]
public string Level { get; set; }
[Column("raise_date")]
public DateTime RaiseDate { get; set; }
[Column("exception")]
public string Exception { get; set; }
[Column("properties", TypeName = "jsonb")]
public string Properties { get; set; }
[Column("props_test", TypeName = "jsonb")]
public string PropsTest { get; set; }
}
如果您想添加更多列,那么您还需要修改您的 C# 模型类和 columnOptions。
PS:这里我试图解释如何使用 Code-First 方法为 serilog 创建数据库。如果您有任何其他问题,请告诉我