asp.net-core - Serilog dotnet core function app 和 sql sink
问题描述
我需要将 dotnet5 与 Azure Functions 一起使用,因此请按照指南创建新解决方案:https ://docs.microsoft.com/en-us/azure/azure-functions/dotnet-isolated-process-guide 。
这很好用,所以接下来的工作是为控制台和 sql 服务器添加带有接收器的 serilog。
我添加了 nuget 包:
- Serilog.AspNetCore v4.1.0
- Serilog.Sinks.MSSqlServer v5.6.0
这是 Program.Main:
static void Main(string[] args)
{
string EventName = "Main";
var columnOptions = new ColumnOptions
{
AdditionalColumns = new Collection<SqlColumn>
{
new SqlColumn
{ColumnName = "EventName", DataType = SqlDbType.NVarChar, DataLength = 32, NonClusteredIndex = true}
}
};
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Override("Microsoft.Azure", LogEventLevel.Warning)
.Enrich.FromLogContext()
.WriteTo.Console()
.WriteTo.MSSqlServer(
logEventFormatter: new RenderedCompactJsonFormatter(),
restrictedToMinimumLevel: LogEventLevel.Debug,
connectionString: "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=SmsRouter",
sinkOptions: new MSSqlServerSinkOptions
{
TableName = "LogEvents",
AutoCreateSqlTable = true,
},
columnOptions: columnOptions)
.CreateLogger();
try
{
Log.Information("Starting up {EventName}", EventName);
var host = new HostBuilder()
.UseSerilog()
.ConfigureFunctionsWorkerDefaults()
.ConfigureServices(s =>
{
//services configured here
})
.Build();
host.Run();
}
catch (Exception ex)
{
Log.Fatal(ex, "Application start-up failed");
}
finally
{
Log.CloseAndFlush();
}
}
您可以看到Log.Information("Starting up {EventName}", EventName);行 这有效并记录到控制台和 Sql Server :)
应用程序启动后,它将等待 Http 请求 - 如下所示:
[Function("SendSimpleSms")]
public async Task<QueueAndHttpOutputType> RunSimple([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")] HttpRequestData req,
FunctionContext executionContext)
{
string EventName = "SendSimpleSms";
try
{
Log.Information("Starting: {EventName}", EventName);
我的问题是,这个日志请求“开始:SendSimpleSms”被记录到控制台窗口而不是 Sql Server。
有人看到我有什么问题吗?
解决方案
感谢 Panagiotis Kanavos 让我了解了 Serilog 自记录。
在 LoggerConfiguration 之后,我在 program.main 中添加了以下内容:
Serilog.Debugging.SelfLog.Enable(Console.Error);
这让我意识到 sql sink 无法记录,因为自定义属性的长度超过了其列的长度
推荐阅读
- c# - C# 桌面应用程序/SQL Server 备份策略
- python - 使用python匹配或连接两个csv文件作为数据集
- python-3.x - Pip 卸载名称以 - 开头的奇数包
- web-crawler - Xing 将错误的公司与工作机会联系起来
- eclipse - 我们如何将 25%、35% ..100% 之类的百分比添加到 Eclipse 启动屏幕进度条,以了解到目前为止的进度?
- android - 无法从 TextInputEditText 材质库获取文本输入
- c - 字符串 C 中无用的随机字符
- android - Android 原生库崩溃
- python - SQL - 可以自动递增数字但带有前导零?
- reactjs - 从 api 获取数据时在 React 中获取一个空数组