写入事件日志将异常记录到 sql aspnet_db日志文件

本文关键字:日志 aspnet db sql 文件 记录 入事件 异常 | 更新日期: 2023-09-27 18:34:15

有谁知道在下面的aspnetdb_log文件中写入事件日志是我在网络上找到的带有原始代码行的代码片段,但 Log.LogException(..) 不起作用,或者我不知道要使用的库,所以我使用了 EventLog。我想做的是将错误或事件记录到aspnetdb_log文件中,我的代码是否可以工作,因为我尚未对其进行测试,因为我处于开始阶段,如果有人可以进行任何更正,请留下回复谢谢。这适用于自定义成员资格提供程序

private void WriteToEventLog(Exception e, string action)
{
    string message = action + "-" + e.Message;
    if (!EventLog.SourceExists("aspnetdb_log"))
    {
        EventLog.CreateEventSource("aspnetdb_log", "aspnetdb_log");
    }
    EventLog log = new EventLog();
    log.Source = "aspnetdb_log";
    log.WriteEntry(message, EventLogEntryType.Error);
    // original code doesn't work 
    // Log.LogException(message, e, LogCategory.Membership, TraceEventType.Error);  
}

写入事件日志将异常记录到 sql aspnet_db日志文件

我建议查找或编写自己的自定义 TraceListener 以写入所需的数据库。

然后在类中使用 TraceSource,并在 Web.config 中配置两者。

类:

public class SqlTraceListener : TraceListener
{
    ...
}

用法:

private static TraceSource _traceSource = new TraceSource("MySource");
_traceSource.Trace(...);

配置:

<system.diagnostics>
    <sources>
        <source name="MySource" />
    </sources>
    <sharedListeners>
        <add name="sql" type="SqlTraceListener" />
    </sharedListeners>
    <trace autoflush="true">
    </trace>
</system.diagnostics>

您需要具有管理权限才能使用 CreateEventSource 创建 EventSource。

如果aspnetdb_log源已经存在,我相信您的代码应该运行良好。

我建议看看Log4Net,它有许多不同的附加器,允许您登录到不同的位置,即数据库,事件日志以及文本文件。

这是一个关于使用不同附加器的非常好的教程