我可以使用 Serilog 登录到 Windows 事件查看器。但是,它会记录到 Windows 日志/应用程序。我希望登录到应用程序和服务日志。我想我需要创建一个自定义 channel ,然后配置记录器以发送到该自定义 channel 。
https://learn.microsoft.com/en-us/previous-versions/bb756956(v=msdn.10)?redirectedfrom=MSDN 我认为这个自定义 channel 是一个应用程序 channel 。当我研究应用程序 channel 时,结果总是以 Application Insights 告终。我没有使用 Azure。只是 IIS。
这是我的 C# 代码。有什么建议吗?
Log.Logger = new LoggerConfiguration().MinimumLevel.Debug()
.WriteTo.EventLog("Laserfiche_Document_Finder",
manageEventSource: true).CreateLogger();
builder.Host.UseSerilog();
"Serilog": {
"using": [ "Serilog.Sinks.EventLog" ],
"Minimumlevel": {
"Default": "Information"
},
"WriteTo": [
{
"Name": "EventLog",
"Args": {
"source": "DLF",
"manageEventSource": true
}
}
]
最佳答案
命名空间 System.Diagnostics 提供了一个名为“EventLog”的类,用于创建消息并将其写入事件日志。
举个例子,我们的目标是编写一个简单的 C# .NET 类,它将创建一个名为“myEventLog”的新日志并写入一条消息“我不会说我失败了 1000 次;我不会说我失败了 1000 次;我会说我已经发现了 1000 种可能导致失败的方法——托马斯·爱迪生。”作为信息。
为此,我们需要使用以下方法、属性和枚举,它们可以在 System.Diagnostics 命名空间中找到。
SourceExists:确定事件源是否在本地计算机上注册。
CreateEventSource:建立一个能够将事件信息写入系统特定日志的应用程序。 可以在此链接中找到更多详细信息。
WriteEntry:在事件日志中写入条目,即,将具有给定消息文本的信息类型条目写入事件日志。 可以在此链接中找到更多详细信息。
public class ClsEventLog
{
public bool CreateLog(string strLogName)
{
bool Result = false;
try
{
System.Diagnostics.EventLog.CreateEventSource(strLogName, strLogName);
System.Diagnostics.EventLog SQLEventLog =
new System.Diagnostics.EventLog();
SQLEventLog.Source = strLogName;
SQLEventLog.Log = strLogName;
SQLEventLog.Source = strLogName;
SQLEventLog.WriteEntry("The " + strLogName + " was successfully
initialize component.", EventLogEntryType.Information);
Result = true;
}
catch
{
Result = false;
}
return Result;
}
public void WriteToEventLog(string strLogName
, string strSource
, string strErrDetail)
{
System.Diagnostics.EventLog SQLEventLog = new System.Diagnostics.EventLog();
try
{
if (!System.Diagnostics.EventLog.SourceExists(strLogName))
this.CreateLog(strLogName);
SQLEventLog.Source = strLogName;
SQLEventLog.WriteEntry(Convert.ToString(strSource)
+ Convert.ToString(strErrDetail),
EventLogEntryType.Information);
}
catch (Exception ex)
{
SQLEventLog.Source = strLogName;
SQLEventLog.WriteEntry(Convert.ToString("INFORMATION: ")
+ Convert.ToString(ex.Message),
EventLogEntryType.Information);
}
finally
{
SQLEventLog.Dispose();
SQLEventLog = null;
}
}
}
https://stackoverflow.com/questions/73732767/