Viewing System Logs with C# and WMI

Viewing System Logs with C# and WMI

As a system administrator, being able to view system logs is crucial for troubleshooting and debugging purposes. In this article, we will explore how to use C# and the Windows Management Instrumentation (WMI) system to view system logs on both local and remote computers.

Retrieving Log Files

To retrieve log files, we need to provide the remote computer’s remote user name and password. This can be achieved by implementing the following feature using the wind32 API function of the WMI system.

#region // Retrieve Log Files
/// <summary>
/// Retrieve log files
/// </summary>
/// <param name="topNumber">How many</param>
/// <param name="eventCode">Event ID</param>
/// <param name="startTime">Start Time</param>
/// <param name="endTime">End Time</param>
/// <returns>Returns a collection of</returns>
public List<EventLogEntity> GetEventLogList(int topNumber, string eventCode, string startTime, string endTime)
{
    List<EventLogEntity> logList = new List<EventLogEntity>();

    try
    {
        // Conditional statements
        StringBuilder query = new StringBuilder();
        StringBuilder strWhere = new StringBuilder();
        query.Append("select EventType, TimeWritten, Category, SourceName, EventIdentifier, RecordNumber, CategoryString, EventCode, Message from Win32_NTLogEvent");

        // Log ID
        if (!string.IsNullOrEmpty(eventCode))
        {
            strWhere.Append("AND eventCode = '");
            strWhere.Append(eventCode);
            strWhere.Append("' ");
        }

        // Start date
        if (!string.IsNullOrEmpty(startTime))
        {
            strWhere.Append("AND TimeWritten >= '");
            strWhere.Append(getDmtfFromDateTime(startTime));
            strWhere.Append("' ");
        }

        // End Date
        if (!string.IsNullOrEmpty(endTime))
        {
            strWhere.Append("AND TimeWritten <= '");
            strWhere.Append(getDmtfFromDateTime(endTime));
            strWhere.Append("' ");
        }

        String laststrWhere = strWhere.ToString();

        // If search condition
        if (!string.IsNullOrEmpty(laststrWhere))
        {
            laststrWhere = "where" + laststrWhere.Substring(4);
        }

        // Combination condition
        query.Append(laststrWhere);

        // Value
        ManagementObjectCollection moCollection = null;

        // If local
        if (isLocal)
        {
            ManagementScope scope = new ManagementScope(scopePath);
            scope.Connect();
            ObjectQuery objectQuery = new ObjectQuery(query.ToString());
            // WQL statement, the operating range of the set of WMI WMI queries and retrieve WMI object set
            ManagementObjectSearcher Searcher = new ManagementObjectSearcher(scope, objectQuery);
            // Asynchronous calls WMI Query
            moCollection = Searcher.Get();
        }
        // Represents the remote
        else
        {
            // Set the content to query WMI
            ObjectQuery Query = new ObjectQuery(query.ToString());
            // WQL statement, the operating range of the set of WMI WMI queries and retrieve WMI object set
            ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Ms, Query);
            // Asynchronous calls WMI Query
            moCollection = Searcher.Get();
        }

        // Loop
        if (moCollection != null)
        {
            int i = 0;
            foreach (ManagementObject mObject in moCollection)
            {
                if (i == topNumber)
                {
                    break;
                }

                EventLogEntity eventLog = new EventLogEntity();
                // Log types
                eventLog.EventType = mObject["EventType"] == null ? string.Empty : GetEventTypeString((NTLogEvent.EventTypeValues)(System.Convert.ToInt32(mObject["EventType"])));

                // Log species
                eventLog.Category = mObject["Category"] == null ? string.Empty : mObject["Category"].ToString();

                // Log types
                eventLog.CategoryString = mObject["CategoryString"] == null ? string.Empty : mObject["CategoryString"].ToString();

                // Log encoding
                eventLog.EventCode = mObject["EventCode"] == null ? string.Empty : mObject["EventCode"].ToString();

                // Log ID
                eventLog.EventIdentifier = mObject["EventIdentifier"] == null ? string.Empty : mObject["EventIdentifier"].ToString();

                // Line number
                eventLog.RecordNumber = mObject["RecordNumber"] == null ? string.Empty : mObject["RecordNumber"].ToString();

                // Date
                eventLog.TimeWritten = mObject["TimeWritten"] == null ? string.Empty : getDateTimeFromDmtfDate(mObject["TimeWritten"].ToString());

                // Log source
                eventLog.SourceName = mObject["SourceName"] == null ? string.Empty : mObject["SourceName"].ToString();

                // Detailed error
                eventLog.Message = mObject["Message"] == null ? string.Empty : mObject["Message"].ToString();

                // Add
                logList.Add(eventLog);
                i++;
            }
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }

    // Return
    return logList;
}
#endregion

Retrieving Error Messages

To retrieve error messages, we need to provide the record number. This can be achieved by implementing the following feature using the wind32 API function of the WMI system.

#region // Error Message According to the Row Number Search
/// <summary>
/// The line number to retrieve the error message
/// </summary>
/// <param name="recordNumber">Row number</param>
/// <returns>Returns an error message</returns>
public string GetErrMsg(uint recordNumber)
{
    String Msg = string.Empty;

    try
    {
        // Conditional statements
        StringBuilder query = new StringBuilder();
        query.Append("select Message, InsertionStrings from Win32_NTLogEvent where");
        query.Append("RecordNumber = '");
        query.Append(recordNumber);
        query.Append("' ");

        // Value
        ManagementObjectCollection moCollection = null;

        // If local
        if (isLocal)
        {
            ManagementScope scope = new ManagementScope(scopePath);
            scope.Connect();
            ObjectQuery objectQuery = new ObjectQuery(query.ToString());
            // WQL statement, the operating range of the set of WMI WMI queries and retrieve WMI object set
            ManagementObjectSearcher Searcher = new ManagementObjectSearcher(scope, objectQuery);
            // Asynchronous calls WMI Query
            moCollection = Searcher.Get();
        }
        // Represents the remote
        else
        {
            // Set the content to query WMI
            ObjectQuery Query = new ObjectQuery(query.ToString());
            // WQL statement, the operating range of the set of WMI WMI queries and retrieve WMI object set
            ManagementObjectSearcher Searcher = new ManagementObjectSearcher(Ms, Query);
            // Asynchronous calls WMI Query
            moCollection = Searcher.Get();
        }

        // Retrieve the error message
        foreach (ManagementObject mObject in moCollection)
        {
            // Error message
            string message = mObject["Message"] == null ? string.Empty : mObject["Message"].ToString();

            // Error message
            string[] insertionStrings = mObject["InsertionStrings"] == null ? null : (String[])mObject["InsertionStrings"];

            // If an error message
            if (string.IsNullOrEmpty(message))
            {
                if (insertionStrings.Length > 0)
                {
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < insertionStrings.Length; i++)
                    {
                        sb.Append(insertionStrings[i]);
                        sb.Append(" ");
                    }
                    Msg = sb.ToString();
                }
                else
                {
                    Msg = message;
                }
            }
            else
            {
                Msg = message;
            }
        }
    }
    catch { }

    // Return
    return Msg.IsNullOrEmpty() ? "Error message, please contact your administrator to check!" : Msg;
}
#endregion

In conclusion, viewing system logs with C# and WMI is a powerful tool for system administrators to troubleshoot and debug issues. By implementing the features outlined in this article, you can easily view system logs on both local and remote computers.