我试图用我的c#代码写事件查看器,但是我得到了一个很棒的"Object reference not set to an instance of an object“消息。我希望这段代码能得到一些帮助,不管是哪里出了问题,或者是更好的方法。下面是我可以写入事件日志的内容:
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);
}
这就是我想要说的:
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;
}
}
发布于 2009-07-15 19:29:28
问题可能是您试图在不存在的日志中创建事件源。您需要指定"Application“日志。
尝试将其更改为:
if (!EventLog.SourceExists(cs))
EventLog.CreateEventSource(cs, "Application");
EventLog.WriteEntry(cs, message, EventLogEntryType.Error);
另外:在sharepoint内部,如果应用程序以登录用户的身份运行(通过windows认证或委派),则该用户将无权创建事件源。如果是这种情况,一种技巧是使用ThreadPool线程创建事件,该线程在创建时将具有运行应用程序池的用户的安全上下文。
发布于 2009-07-15 19:28:49
下面是我如何实现事件日志记录。我创建了一个通用的ILogger接口,这样我就可以交换不同的日志记录机制:
interface ILogger
{
void Debug(string text);
void Warn(string text);
void Error(string text);
void Error(string text, Exception ex);
}
我的实现类非常简单:
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);
}
}
请注意,我没有实例化EventLog。为了使用我的记录器类,我只需要下面的引用(你可以通过一个静态工厂方法返回它):
private static readonly ILogger log = new EventLogger();
实际用法如下:
try
{
// business logic
}
catch (Exception ex)
{
log.Error("Exception in MyMethodName()", ex);
}
发布于 2017-02-06 17:14:10
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;
}
}
https://stackoverflow.com/questions/1133355
复制相似问题