C#写入事件查看器 [英] c# writing to the event viewer

查看:552
本文介绍了C#写入事件查看器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图写在我的C#代码的事件查看器,但我得到了精彩的对象引用不设置到对象的实例的消息。我会很感激一些帮助与此代码,无论是什么地方错了,甚至更好的方式来做到这一点。下面是我对写入事件日志:

 私人无效WriteToEventLog(字符串消息)
{
字符串CS =QualityDocHandler;
事件日志ELOG =新的EventLog();
如果
{
EventLog.CreateEventSource(CS,CS)(EventLog.SourceExists(CS)!);
}
elog.Source = CS;
elog.EnableRaisingEvents = TRUE;
elog.WriteEntry(消息);
}

和这里的地方我想叫它:

 私人只读随机_rng =新的随机(); 
私人常量字符串_chars =ABCDEFGHIJKLMNOPQRSTUVWXYZ;
私人字符串RandomString(INT大小)
{

{
的char []缓冲区=新的char [大小]
的for(int i = 0; I<大小;我++)
{
缓冲区[i] = _chars [_rng.Next(_chars.Length)];
}
返回新的字符串(缓冲);
}
赶上(例外五)
{
WriteToEventLog(e.ToString());
返回NULL;
}
}


解决方案

的问题可能是,你要创建的是不存在的日志的事件源。你需要指定应用程序日志



尝试将其更改为:

 如果
EventLog.CreateEventSource(CS,应用程序)(EventLog.SourceExists(CS)!);

EventLog.WriteEntry(CS,消息,EventLogEntryType.Error);



另外:共享点的内部,如果应用程序正在运行作为登录的用户(通过Windows验证或授权),用户将不能访问以创建事件源。如果是这样的话,一个技巧就是创建使用线程池线程,该线程创建的时候,才会有应用程序池正在运行的用户的安全上下文中的事件。


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:

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;
    }
}

解决方案

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.

这篇关于C#写入事件查看器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆