我正在尝试将 Serilog 集成到我的 ASP.NET Core API 项目中,以根据其属性将特定类型的条目记录到不同的接收器。我的目标是配置记录器,以便当 Serilog 上下文包含特定属性时,日志被写入文件;否则,它们应该被定向到 SEQ 。但这对我不起作用。 请在下面找到我的代码
应用程序设置.json
{
"Serilog": {
"Using": [ "Serilog.Exceptions" ],
"LevelSwitches": { "$controlSwitch": "Error" },
"MinimumLevel": { "ControlledBy": "$controlSwitch" },
"Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId", "WithExceptionDetails" ],
"WriteTo": [
{
"Name": "File",
"Args": {
"pathFormat": "C:\\Logs\\MicrologicAPILog-{Date}.log",
"rollingInterval": "Day",
"outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}"
},
"Filter": [
{
"Name": "ByIncluding",
"Args": {
"Expression": "Matching.WithProperty('LogType', 'File')"
}
}
]
},
{
"Name": "Seq",
"Args": {
"serverUrl": "sequrl",
"apiKey": "api key",
"controlLevelSwitch": "$controlSwitch"
},
"Filter": [
{
"Name": "ByExcluding",
"Args": {
"Expression": "Matching.WithProperty('LogType', 'File')"
}
}
]
}
],
"Properties": {
"MLEnvironment": "Local",
"Client": "Unknown"
}
},
基础控制器
//下面的方法是专门将日志写入文件的。
internal void LogAuthInfo(string requestUrl, string authToken, string formattedAuth)
{
var hostName = Dns.GetHostName();
var ipAddress = Dns.GetHostAddresses(hostName);
using (LogContext.PushProperty("LogType", "File"))
{
_logger
.ForContext("CallingApplication", this.CallingApplication)
.ForContext("CustomerCode", this.CustomerCode)
.ForContext("LocationId", this.LocationId.ToString())
.ForContext("LocationDescription", this.LocationDescription)
.ForContext("Version", Assembly.GetExecutingAssembly().GetName().Version)
.ForContext("ServerIP", string.Join(",", ipAddress.Select(x => x.ToString())))
.ForContext("RequestUrl", requestUrl)
.ForContext("AuthToken", authToken)
.ForContext("FormattedAuthToken", formattedAuth)
.Error("AuthToken Info");
}
}
}
下面一个用于记录 seq 中的详细信息。由于两个日志需要保存不同的信息,所以我给出了不同的方法
protected internal void LogInfo(string message, [CallerMemberName] string memberName = null, bool detailedTracking = false)
{
var hostName = Dns.GetHostName();
var ipAddress = Dns.GetHostAddresses(hostName);
_logger
.ForContext("CallingApplication", this.CallingApplication)
.ForContext("CustomerCode", this.CustomerCode)
.ForContext("LocationId", this.LocationId.ToString())
.ForContext("LocationDescription", this.LocationDescription)
.ForContext("Version", Assembly.GetExecutingAssembly().GetName().Version)
.ForContext("ServerIP", string.Join(",", ipAddress.Select(x => x.ToString())))
.ForContext("DetailedTracking", detailedTracking.ToString())
.Information(message);
}
然后我在 BasicAuthorizeAttribute 类中调用此代码
public class BasicAuthorizeAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext actionContext)var configuration = actionContext.HttpContext.RequestServices.GetRequiredService<Microsoft.Extensions.Configuration.IConfiguration>();
var logDebugAccess = configuration.GetValue<string>("AppSettings:LogAuthToken:DebugAccessCodeEnabled");
string customerCodes = configuration.GetValue<string>("AppSettings:LogAuthToken:CustomerCodes");
BaseController controller = (BaseController)actionContext.Controller;
if (logDebugAccess != null && logDebugAccess == "true" && !string.IsNullOrEmpty(customerCodes)) //These are configurations to control the logging
{
var customerCodeList = customerCodes.Split(',').Select(code => code.ToUpper().Trim());
if (customerCodeList.Contains(siteCode.ToUpper()))
{
controller.LogAuthInfo(url, encryptetransactioncode, formattedAuth);
}
}
}
}
在 Serilog Logger Extension 类中,我给出了以下逻辑
public static class SerilogLoggerExtension
{
public static void Initialize(ILoggerFactory loggerFactory, IConfiguration configuration)
{
var mlEnvironment = configuration.GetValue<string>("MLEnvironment");
var productName = "MicrologicAPI";
// Read Seq server URL and API key from appsettings.json
var seqServerUrl = configuration.GetValue<string>("Serilog:WriteTo:1:Args:serverUrl");
var seqApiKey = configuration.GetValue<string>("Serilog:WriteTo:1:Args:apiKey");
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.Enrich.FromLogContext()
.Enrich.WithEnvironmentUserName()
.Enrich.WithExceptionDetails()
.CreateLogger();
loggerFactory.WithFilter(new FilterLoggerSettings
{
{"Trace",LogLevel.Trace },
{"Default", LogLevel.Trace},
{"Microsoft", LogLevel.Warning},
{"System", LogLevel.Warning}
})
.AddSerilog();
}
}
我正在使用 Serilog 版本 - 2.10.1。 任何人都可以帮助确定我的代码的问题吗?
请更新应用程序设置文件,如下所示
{
"Serilog": {
"Using": [
"Serilog",
"Serilog.Enrichers.Thread",
"Serilog.Settings.Configuration",
"Serilog.Sinks.Console",
"Serilog.Sinks.File"
],
"LevelSwitches": { "$controlSwitch": "Information" },
"MinimumLevel": { "ControlledBy": "$controlSwitch" },
"Enrich": [ "FromLogContext", "WithMachineName", "WithProcessId", "WithThreadId", "WithExceptionDetails" ],
"WriteTo": [
{ "Name": "Console" },
{
"Name": "Seq",
"MinimumLevel": "$controlSwitch",
"Args": {
"serverUrl": "seq url",
"apiKey": "seq key",
"controlLevelSwitch": "$controlSwitch"
}
},
{
"Name": "Logger",
"Args": {
"MinimumLevel": "Information",
"configureLogger": {
"Filter": [
{
"Name": "ByIncludingOnly",
"Args": {
"expression": "LogType is not null"
}
}
],
"WriteTo": [
{
"Name": "File",
"Args": {
"rollingInterval": "Day",
"path": "Logs/DEBUGACCESSLOG_.log",
"outputTemplate": "{Timestamp:HH:mm:ss.fff zzz}|{Level}|{ThreadId}|{SourceContext}|{Message:lj}|{NewLine}"
}
}
]
}
}
}
],
"Properties": {
"MLEnvironment": "Local",
"Client": "Unknown"
}
},