我正在开发一个包含多个程序集的asp.net core(2.2)应用程序。对于日志记录,我使用serilog for asp.net core。现在需要在抛出异常时发送邮件。关键是:只有在特定程序集中抛出异常时才会发送电子邮件。有没有办法通过serilog电子邮件接收器实现这一目标?谢谢。
它不是特定于电子邮件接收器,而是任何记录器配置。有很多例子,请参阅这个答案。也可以过滤类和命名空间,并且可以通过其他接收器记录来自其他程序集的异常。喜欢滚动文件。 Filter Serilog logs to different sinks depending on context source?
以下是满足要求的appsettings.json的配置:
"Serilog": {
"Using": [ "Serilog.Sinks.File", "Serilog.Sinks.Email" ],
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Information",
"System": "Warning"
}
},
"WriteTo": [
{
"Name": "File", // general logging
"Args": {
"path": "", // ToDo: Add log path
"outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] [{SourceContext}] ({Application}/{MachineName}/{EnvironmentUserName}) {Message}{NewLine}{Exception}",
"rollingInterval": "Day",
"shared": true
}
},
{
"Name": "Logger",
"Args": {
"configureLogger": {
"WriteTo": [
{
"Name": "Email",
"Args": {
"restrictedToMinimumLevel": "Error",
"outputTemplate": "{Message}{NewLine}{NewLine}Zeitpunkt: {Timestamp:HH:mm:ss}{NewLine}Klasse: {SourceContext}{NewLine}{NewLine}{Exception}",
"FromEmail": "{email address}", // ToDo: Add DefaultMailAddress
"ToEmail": "{email address}", // ToDo: Add recipient mail addresses (separator: ; or ,)
"MailServer": "", // ToDo: Add host
"MailSubject": "", // ToDo: Add mail subject
"NetworkCredentials": {
"userName": "", // ToDo: Add UserName
"password": "" // ToDo: Add Password
},
"Port": 25, // ToDo: Add Port
"EnableSsl": true,
"IsBodyHtml": true
}
}
],
"Filter": [
{
"Name": "ByIncludingOnly",
"Args": {
"expression": "StartsWith(SourceContext, 'Assembly.Namespace.')"
}
}
]
}
}
}
],
"Enrich": [ "FromLogContext", "WithMachineName", "WithEnvironmentUserName" ],
"Properties": {
"Application": "My.Application"
}
}