什么是事件ID管理的最佳实践?

时间:2009-10-28 14:06:40

标签: c# .net events trace event-log

我正在试图弄清楚如何管理我的事件ID。到目前为止,我已经手动将每个事件id放在每个方法中,并按顺序编号的方法中的每个步骤。这不允许我有效地过滤事件日志中的事件。为了在事件日志中使用过滤器,似乎每个记录的事件都必须有自己唯一的id。

我可以将它们全部存储在一个链接到它们的描述的表中,但随着我的代码执行,我正在记录“神奇的”无意义的事件代码。

我进行了谷歌搜索,但我似乎对用于解决此问题的正确关键字感到茫然。

提前致谢

3 个答案:

答案 0 :(得分:10)

与Ben的建议一样,它可能值得使用间接级别 - 但不是使用int代码,而是使用实际的枚举,所以对于Ben的例子:

public enum EventId
{
    [Format("Building command object from {0}.")]
    BuildingCommandObject = 1,
    [Format("Command object build successfully.")]
    CommandObjectBuilt = 2,
    [Format("Connecting to {0}.")]
    ConnectingToDatabase = 3,
    [Format("Executing command against database {0}.")]
    ExecutingCommand = 4,
    [Format("Command executed successfully.")]
    CommandExecuted = 5,
    [Format("Disconnecting from {0}.")]
    DisconnectingFromDatabase = 6,
    [Format("Connection terminated")]
    Disconnected = 7
}

或者(以更面向对象的方式)使用“智能枚举”模式:

public class LogEvent
{
    public static readonly LogEvent BuildingCommandObject = new LogEvent(1,
         "Building command object from {0}");
    // etc

    private readonly int id;
    private readonly string format;

    // Add the description if you want
    private LogEvent(int id, string format)
    {
        this.id = id;
        this.format = format;
    }

    public void Log(params object[] data)
    {
        string message = string.Format(format, data);
        // Do the logging here
    }
}

然后你可以打电话:

LogEvent.BuildingCommandObject.Log("stuff");

通过一些工作,您可能能够以安全的方式公开它,使用具有不同接口的不同日志事件,以便在安全性方面(在编译时)根据参数的数量每个人都有。事实上,我确信你可以使用接口和私有嵌套类来实现它,但是凌晨4点,我太累了,不能把它写出来:)

答案 1 :(得分:7)

首先想到 - 我还没有完全想到这一点,但这似乎是一个合理的可能性:

public class LogEvent
{
    /* This is the event code you reference from your code 
     * so you're not working with magic numbers.  It will work
     * much like an enum */
    public string Code; 

    /* This is the event id that's published to the event log
     * to allow simple filtering for specific events */
    public int Id; 

    /* This is a predefined string format that allows insertion
     * of variables so you can have a descriptive text template. */
    public string DisplayFormat;

    /* A constructor to allow you to add items to a collection in
     * a single line of code */
    public LogEvent(int id, string code, string displayFormat)
    {
        Code = code;
        Id = id;
        DisplayFormat = displayFormat;
    }
    public LogEvent(int id, string code)
        : this(id, code, null)
    {
    }
    public LogEvent()
    {
    }
}

然后,您可以拥有一个事件管理器类,它包装您的事件列表,提供根据您传递的参数查询列表的方法 - 例如:

public class EventManager
{
    private List<LogEvent> _eventList;
    public LogEvent this[string eventCode]
    {
        get
        {
            return _eventList.Where(i => i.Code.Equals(eventCode)).SingleOrDefault();
        }
    }
    public LogEvent this[int id]
    {
        get
        {
            return _eventList.Where(i => i.Id.Equals(id)).SingleOrDefault();
        }
    }
    public void AddRange(params LogEvent[] logEvents)
    {
        Array.ForEach(logEvents, AddEvent);
    }
    public void Add(int id, string code)
    {
        AddEvent(new LogEvent(id, code));
    }
    public void Add(int id, string code, string displayFormat)
    {
        AddEvent(new LogEvent(id, code, displayFormat));
    }
    public void Add(LogEvent logEvent)
    {
        _events.Add(logEvent);
    }
    public void Remove(int id)
    {
        _eventList.Remove(_eventList.Where(i => i.id.Equals(id)).SingleOrDefault());
    }
    public void Remove(string code)
    {
        _eventList.Remove(_eventList.Where(i => i.Code.Equals(code)).SingleOrDefault());
    }
    public void Remove(LogEvent logEvent)
    {
        _eventList.Remove(logEvent);
    }
}

这样可以简化事件定义的管理,可以为每个TraceSource独立管理。

var Events = new EventManager();
Events.AddRange(
    new LogEvent(1, "BuildingCommandObject", "Building command object from {0}."),
    new LogEvent(2, "CommandObjectBuilt", "Command object built successfully."),
    new LogEvent(3, "ConnectingToDatabase", "Connecting to {0}."),
    new LogEvent(4, "ExecutingCommand", "Executing command against database {0}".),
    new LogEvent(5, "CommandExecuted", "Command executed succesfully."),
    new LogEvent(6, "DisconnectingFromDatabase", "Disconnecting from {0}."),
    new LogEvent(7, "Disconnected", "Connection terminated.")
)

您可以使用您指定的有意义的标识符访问事件:

var evt = Events["ConnectingToDatabase"];
TraceSource.TraceEvent(TraceEventType.Information, evt.Id, evt.DisplayFormat, otherParams);

var evt = Events[1024];
Console.WriteLine("Id: {1}{0}Code: {2}{0}DisplayFormat{3}", 
    Environment.NewLine, evt.Id, evt.Code, evt.DisplayFormat);

这可能会简化您的事件管理,您不再通过幻数来调用您的事件,在一个地方管理所有事件很简单 - 您的EventManager类,您仍然可以通过幻数过滤您的事件日志要求你过滤。

答案 2 :(得分:0)

我知道这是一个老问题,但也许您正在寻找一种方法来执行此类操作,您可以将自定义事件ID用于不同目的,并在代码中的适当位置调用它们:

public class ErrorLog
{
    //Notifications
    public const int NOTIFY_ALPHA = 2000;
    public const int NOTIFY_BETA = 2001;
    public const int NOTIFY_GAMMA = 2002;

    public static string[] errMessage = 
        {"Critical Error.",           //2000
         "File not found.",          //2001
         "Unknown Event Action Encountered - "     //2002
        };

    public static string GetErrMsg(int errNum)
    {
        return (errMessage[errNum-2000]);
    }

    private static bool ErrorRoutine(int eventLogId)
    {
        try
        {
            string eventAppName = "My Application";
            string eventLogName = "My Apps Events";
            string msgStr = GetErrMsg(eventLogId);  // gets the message associated with the ID from the constant you passed in

            if (!EventLog.SourceExists(eventAppName))
                EventLog.CreateEventSource(eventAppName, eventLogName);

            EventLog.WriteEntry(eventAppName, msgStr, EventLogEntryType.Error, eventLogId);

            return true;
        }
        catch (Exception)
        {
            return false;
        }
    }
}

然后当你抛出异常时,你就像这样调用这个类:

ErrorLog.ErrorRoutine(ErrorLog.NOTIFY_ALPHA);

就最佳实践而言,我会说如果将自己的类中的所有错误处理都设置为自定义(或更多,例如绑定警告和信息时EventLogEntryTypes或其他信息而不是固定的信息比这个更好。拥有个人ID,您可以查看他们的消息,这样可以让您在尝试调出要呼叫的消息,时间和地点时更轻松。

相关问题