c# 写入事件查看器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1133355/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 09:00:51  来源:igfitidea点击:

c# writing to the event viewer

c#event-log

提问by PushCode

I'm trying to write to the event viewer in my c# code, but I'm getting the wonderful "Object reference not set to an instance of an object" message. I'd appreciate some help with this code, either what's wrong with it or even a better way to do it. Here's what I have for writing to the event log:

我正在尝试在我的 c# 代码中写入事件查看器,但我收到了很棒的“对象引用未设置为对象的实例”消息。我很感激这段代码的一些帮助,无论是它有什么问题,还是更好的方法。这是我写入事件日志的内容:

private void WriteToEventLog(string message)
{
    string cs = "QualityDocHandler";
    EventLog elog = new EventLog();
    if (!EventLog.SourceExists(cs))
    {
        EventLog.CreateEventSource(cs, cs);
    }
    elog.Source = cs;
    elog.EnableRaisingEvents = true;
    elog.WriteEntry(message);
}

And here's where I'm trying to call it:

这就是我试图称呼它的地方:

private readonly Random _rng = new Random();
private const string _chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private string RandomString(int size)
{
    try
    {
        char[] buffer = new char[size];
        for (int i = 0; i < size; i++)
        {
            buffer[i] = _chars[_rng.Next(_chars.Length)];
        }
        return new string(buffer);
    }
    catch (Exception e)
    {
        WriteToEventLog(e.ToString());
        return null;
    }
}

采纳答案by Brian Rudolph

The problem is probably that you are trying to create an event source in a log that doesn't exist. You need to specify the "Application" log.

问题可能是您试图在不存在的日志中创建事件源。您需要指定“应用程序”日志。

Try changing it to:

尝试将其更改为:

if (!EventLog.SourceExists(cs))
   EventLog.CreateEventSource(cs, "Application");    

EventLog.WriteEntry(cs, message, EventLogEntryType.Error);

Also: Inside of sharepoint, if the app is running as logged in user(via windows auth or delegation), the user won't have access to create the event source. If this is the case, one trick is to create the event using a ThreadPool thread, which when created, will have the security context of the user the App Pool is running as.

另外:在 sharepoint 内部,如果应用程序以登录用户身份运行(通过 Windows 身份验证或委托),用户将无权创建事件源。如果是这种情况,一个技巧是使用 ThreadPool 线程创建事件,该线程在创建时将具有运行 App Pool 的用户的安全上下文。

回答by Nelson

Here's how I implemented Event logging. I created a generic ILogger interface so I can swap in different logging mechanisms:

这是我实现事件日志记录的方式。我创建了一个通用的 ILogger 接口,以便我可以交换不同的日志记录机制:

interface ILogger
{
    void Debug(string text);

    void Warn(string text);

    void Error(string text);
    void Error(string text, Exception ex);
}

My implementation class is very simple:

我的实现类很简单:

class EventLogger : ILogger
{
    public void Debug(string text)
    {
        EventLog.WriteEntry("MyAppName", text, EventLogEntryType.Information);
    }

    public void Warn(string text)
    {
        EventLog.WriteEntry("MyAppName", text, EventLogEntryType.Warning);
    }

    public void Error(string text)
    {
        EventLog.WriteEntry("MyAppName", text, EventLogEntryType.Error);
    }

    public void Error(string text, Exception ex)
    {
        Error(text);
        Error(ex.StackTrace);
    }
}

Note that I do not instantiate EventLog. To use my logger class I just have the following reference (you could have this returned by a static factory method):

请注意,我没有实例化 EventLog。要使用我的记录器类,我只有以下参考(您可以通过静态工厂方法返回它):

private static readonly ILogger log = new EventLogger();

And the actual usage is like this:

而实际的用法是这样的:

try
{
    // business logic
}
catch (Exception ex)
{
    log.Error("Exception in MyMethodName()", ex);
}

回答by Dutt93

   private void WriteEventLogToFile()
    {
        try
        {
            using (EventLog eventLog = new EventLog("Application"))
            {
             // source for your event 
                eventLog.Source = "IAStorDataMgrSvc";

             // Syntax details
            // eventLog.WriteEntry("details",type of event,event id);
             eventLog.WriteEntry("Hard disk Failure details", EventLogEntryType.Information, 11);
            }
        }
        catch (Exception)
        {
            throw;
        }
    }