我正在尝试用我的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);
}
Run Code Online (Sandbox Code Playgroud)
这就是我试图称之为的地方:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
Bri*_*lph 87
问题可能是您尝试在不存在的日志中创建事件源.您需要指定"应用程序"日志.
尝试将其更改为:
if (!EventLog.SourceExists(cs))
EventLog.CreateEventSource(cs, "Application");
EventLog.WriteEntry(cs, message, EventLogEntryType.Error);
Run Code Online (Sandbox Code Playgroud)
另外:在sharepoint内部,如果应用程序以登录用户身份运行(通过Windows身份验证或委派),则用户将无权创建事件源.如果是这种情况,一个技巧是使用ThreadPool线程创建事件,该线程在创建时将具有App Pool正在运行的用户的安全上下文.
Nel*_*son 22
这是我实现事件记录的方式.我创建了一个通用的ILogger接口,因此我可以交换不同的日志记录机制:
interface ILogger
{
void Debug(string text);
void Warn(string text);
void Error(string text);
void Error(string text, Exception ex);
}
Run Code Online (Sandbox Code Playgroud)
我的实现类很简单:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,我没有实例化EventLog.要使用我的记录器类,我只需要以下参考(您可以通过静态工厂方法返回):
private static readonly ILogger log = new EventLogger();
Run Code Online (Sandbox Code Playgroud)
而实际用法是这样的:
try
{
// business logic
}
catch (Exception ex)
{
log.Error("Exception in MyMethodName()", ex);
}
Run Code Online (Sandbox Code Playgroud)