예제 #1
0
        public static List <EventLogConfiguration> GetEventLogs(string computerName, bool filterForTasks = true)
        {
            var ret = new List <EventLogConfiguration>();

            try
            {
                using (EventLogSession session = GetEventLogSession(computerName))
                {
                    foreach (var s in session.GetLogNames())
                    {
                        try
                        {
                            var cfg = new EventLogConfiguration(s, session);
                            if (!filterForTasks || IsValidTaskLog(cfg))
                            {
                                ret.Add(cfg);
                            }
                        }
                        catch (Exception e) { System.Diagnostics.Debug.WriteLine($"Couldn't get config for event log '{s}': {e.Message}"); }
                    }
                }
            }
            catch { }
            return(ret);
        }
예제 #2
0
        static void Main(string[] args)
        {
            {
                Console.Out.WriteLine("Available Logs:");
                var session = new EventLogSession();
                foreach (var log in session.GetLogNames())
                {
                    Console.Out.WriteLine("    " + log);
                }
                Console.Out.WriteLine();
            }

            if (!EventLog.SourceExists("TestEventLog"))
            {
                EventSourceCreationData eventSourceData = new EventSourceCreationData("TestEventLog", "TestEventLog");
                EventLog.CreateEventSource(eventSourceData);
            }

            using (var testEventLogListener = new Listener("TestEventLog", "*"))
                using (var applicationListener = new Listener("Application", "*"))
                    using (var testEventLogger = new EventLog("TestEventLog", ".", "TestEventLog"))
                        using (var timer = new System.Threading.Timer(
                                   _ => testEventLogger.WriteEntry("Test message", EventLogEntryType.Information),
                                   null,
                                   TimeSpan.FromSeconds(1),
                                   TimeSpan.FromSeconds(1)
                                   ))
                        {
                            while (Console.ReadLine().Trim().ToLower() != "exit")
                            {
                                Console.WriteLine("  exit↵ to Exit");
                            }
                        }
        }
예제 #3
0
        public static object[] GetEventLogDisplayObjects(string computerName, bool filterForTasks = true)
        {
            var ret = new List <ELObj>();

            try
            {
                using (EventLogSession session = GetEventLogSession(computerName))
                {
                    foreach (var s in session.GetLogNames())
                    {
                        try
                        {
                            var cfg = new EventLogConfiguration(s, session);
                            if (!filterForTasks || IsValidTaskLog(cfg))
                            {
                                ret.Add(new ELObj(session.GetLogDisplayName(s), s));
                            }
                        }
                        catch (Exception e) { System.Diagnostics.Debug.WriteLine($"Couldn't get display name for event log '{s}': {e.Message}"); }
                    }
                    ret.Sort();
                }
            }
            catch { }
            return(ret.ToArray());
        }
        /// <summary>
        /// Retrieves event log data from the system based on event log metadata.
        /// </summary>
        /// <returns>A list of event log data.</returns>
        public static IList <EventLogData> GetEventLogs()
        {
            IList <EventLogData> logs = new List <EventLogData>();

            using (EventLogSession session = new EventLogSession())
            {
                foreach (EventLogData logData in session.GetLogNames().Select(logName => new EventLogData(logName)).Where(logData => !logs.Contains(logData)))
                {
                    logs.Add(logData);
                }
            }

            return(logs);
        }
        public static string[] GetEventLogs(string computerName)
        {
            bool isLocal = (string.IsNullOrEmpty(computerName) || computerName == "." || computerName.Equals(Environment.MachineName, StringComparison.CurrentCultureIgnoreCase));

            try
            {
                using (EventLogSession session = isLocal ? new EventLogSession() : new EventLogSession(computerName))
                {
                    var l = new List <string>(session.GetLogNames());
                    l.Sort();
                    return(l.ToArray());
                }
            }
            catch {}
            return(new string[0]);
        }
예제 #6
0
        public string[] GetAllLogNames()
        {
            System.Collections.Generic.IList <string> allLogs = new System.Collections.Generic.List <string>();
            using (EventLogSession logSession = new EventLogSession())
            {
                IEnumerable <string> logNames = logSession.GetLogNames();
                foreach (string logName in logNames)
                {
                    using (EventLogConfiguration logConfig = new EventLogConfiguration(logName))
                    {
                        if (logConfig.IsEnabled)
                        {
                            allLogs.Add(logName);
                        }
                    }
                }
            }

            return(allLogs.Cast <string>().ToArray());
        }
예제 #7
0
        // Our Find Events button, this is where the magic happens
        private void FindEventsButton_Click(object sender, EventArgs e)
        {
            FindEventsButton.Enabled = false;

            if (StartInput.Text == "" || EndInput.Text == "")                   // Check to make sure times are populated
            {
                StatusOutput.Text      = "Missing Start or End Time!";
                StatusOutput.ForeColor = System.Drawing.Color.Red;
            }
            else if (!DateTime.TryParse(StartInput.Text, out DateTime temp))  // And that the start time is valid
            {
                StatusOutput.Text      = "Invalid Start Time";
                StatusOutput.ForeColor = System.Drawing.Color.Red;
            }
            else if (!DateTime.TryParse(EndInput.Text, out DateTime temp2))   // And that the end time is valid
            {
                StatusOutput.Text      = "Invalid End Time";
                StatusOutput.ForeColor = System.Drawing.Color.Red;
            }
            else                                                              // If everything is valid, run!
            {
                // Variables we will need
                DateTime        StartTime   = DateTime.ParseExact(StartInput.Text, "MM/dd/yyyy HH:mm:ss", null); // Needed for filter query
                DateTime        EndTime     = DateTime.ParseExact(EndInput.Text, "MM/dd/yyyy HH:mm:ss", null);   // Needed for filter query
                string          DesktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);      // Needed for file name
                string          RunTime     = DateTime.Now.ToString("yyyyMMdd_HHmmss");                          // Needed for file name
                EventLogSession Session     = new EventLogSession();
                var             Logs        = Session.GetLogNames().ToList();
                var             pathType    = PathType.LogName;
                if (currentSystem.Checked == true)
                {
                    Logs     = Session.GetLogNames().ToList();
                    pathType = PathType.LogName;
                }
                else if (System.IO.Directory.Exists(currentPath.Text))
                {
                    Logs     = System.IO.Directory.GetFiles(currentPath.Text, "*.evtx").ToList();
                    pathType = PathType.FilePath;
                }
                else
                {
                    MessageBox.Show("Something Wrong:\nYou likely selected an invalid path");
                    FindEventsButton.Enabled = true;
                    return;
                }

                var           query   = string.Format(@"*[System[TimeCreated[@SystemTime >= '{0}']]] and *[System[TimeCreated[@SystemTime <= '{1}']]]", StartTime.ToUniversalTime().ToString("o"), EndTime.ToUniversalTime().ToString("o"));
                List <Record> records = new List <Record> {
                };                                                                                      // Start a list for all those sweet sweet logs we're going to get

                foreach (var Log in Logs)
                {
                    try
                    {
                        EventLogQuery  eventlogQuery  = new EventLogQuery(Log, pathType, query);
                        EventLogReader eventlogReader = new EventLogReader(eventlogQuery);
                        for (EventRecord eventRecord = eventlogReader.ReadEvent(); null != eventRecord; eventRecord = eventlogReader.ReadEvent())
                        {
                            // Get the SystemTime from the event record XML
                            var        xml = XDocument.Parse(eventRecord.ToXml());
                            XNamespace ns  = xml.Root.GetDefaultNamespace();

                            string Message           = "";
                            string SystemTime        = "";
                            string Id                = "";
                            string Version           = "";
                            string Qualifiers        = "";
                            string Level             = "";
                            string Task              = "";
                            string Opcode            = "";
                            string Keywords          = "";
                            string RecordId          = "";
                            string ProviderName      = "";
                            string ProviderID        = "";
                            string LogName           = "";
                            string ProcessId         = "";
                            string ThreadId          = "";
                            string MachineName       = "";
                            string UserID            = "";
                            string TimeCreated       = "";
                            string ActivityId        = "";
                            string RelatedActivityId = "";
                            string Hashcode          = "";
                            string LevelDisplayName  = "";
                            string OpcodeDisplayName = "";
                            string TaskDisplayName   = "";

                            // Debugging Stuff
                            //Console.WriteLine("-- STARTING --");
                            // Try to collect all the things. Catch them if we can't.
                            // Sometimes fields are null or cannot be converted to string (why?).
                            // If they are, catch and do nothing, so they will stay empty ("").
                            // This has primarily been LevelDisplayName, OpcodeDisplayName, and TaskDisplayName
                            // but we'll catch it all anyway
                            // https://github.com/BeanBagKing/EventFinder2/issues/1
                            try
                            {
                                Message = eventRecord.FormatDescription();
                                if (Message == null)
                                {
                                    Message += "EventRecord.FormatDescription() returned a null value. This is usually because:\n";
                                    Message += "    \"Either the component that raises this event is not installed on your local computer\n" +
                                               "    or the installation is corrupted. You can install or repair the component on the local computer.\"\n";
                                    Message += "The event likely originated on another system, below is the XML data associated with this event\n";
                                    Message += "\n";
                                    Message += XDocument.Parse(eventRecord.ToXml()).ToString();
                                    // If the message body is null, it's because the DLL that created it is on another system and it can't be parsed in real time
                                    // The below works, but we can do better!
                                    // foreach (var node in xml.Descendants(ns + "Event"))
                                    //  {
                                    //      Message += node.Value;
                                    //      Message += "\n";
                                    //  }
                                }
                            }
                            catch
                            {
                                //Console.WriteLine("Error on FormatDescription");
                            }
                            try
                            {
                                SystemTime = xml.Root.Element(ns + "System").Element(ns + "TimeCreated").Attribute("SystemTime").Value;
                            }
                            catch
                            {
                                //Console.WriteLine("Error on SystemTime");
                            }
                            try
                            {
                                Id = eventRecord.Id.ToString();
                            }
                            catch
                            {
                                //Console.WriteLine("Error on Id");
                            }
                            try
                            {
                                Version = eventRecord.Version.ToString();
                            }
                            catch
                            {
                                //Console.WriteLine("Error on Version");
                            }
                            try
                            {
                                Qualifiers = eventRecord.Qualifiers.ToString();
                            }
                            catch
                            {
                                //Console.WriteLine("Error on Qualifiers");
                            }
                            try
                            {
                                Level = eventRecord.Level.ToString();
                            }
                            catch
                            {
                                //Console.WriteLine("Error on Level");
                            }
                            try
                            {
                                Task = eventRecord.Task.ToString();
                            }
                            catch
                            {
                                //Console.WriteLine("Error on Task");
                            }
                            try
                            {
                                Opcode = eventRecord.Opcode.ToString();
                            }
                            catch
                            {
                                //Console.WriteLine("Error on Opcode");
                            }
                            try
                            {
                                Keywords = eventRecord.Keywords.ToString();
                            }
                            catch
                            {
                                //Console.WriteLine("Error on Keywords");
                            }
                            try
                            {
                                RecordId = eventRecord.RecordId.ToString();
                            }
                            catch
                            {
                                //Console.WriteLine("Error on RecordId");
                            }
                            try
                            {
                                ProviderName = eventRecord.ProviderName;
                            }
                            catch
                            {
                                //Console.WriteLine("Error on ProviderName");
                            }
                            try
                            {
                                ProviderID = eventRecord.ProviderId.ToString();
                            }
                            catch
                            {
                                //Console.WriteLine("Error on ProviderId");
                            }
                            try
                            {
                                LogName = eventRecord.LogName;
                            }
                            catch
                            {
                                //Console.WriteLine("Error on LogName");
                            }
                            try
                            {
                                ProcessId = eventRecord.ProcessId.ToString();
                            }
                            catch
                            {
                                //Console.WriteLine("Error on ProcessId");
                            }
                            try
                            {
                                ThreadId = eventRecord.ThreadId.ToString();
                            }
                            catch
                            {
                                //Console.WriteLine("Error on ThreadId");
                            }
                            try
                            {
                                MachineName = eventRecord.MachineName;
                            }
                            catch
                            {
                                //Console.WriteLine("Error on eventRecord");
                            }
                            try
                            {
                                UserID = eventRecord.UserId?.ToString();
                            }
                            catch
                            {
                                //Console.WriteLine("Error on UserId");
                            }
                            try
                            {
                                TimeCreated = eventRecord.TimeCreated.ToString();
                            }
                            catch
                            {
                                //Console.WriteLine("Error on TimeCreated");
                            }
                            try
                            {
                                ActivityId = eventRecord.ActivityId.ToString();
                            }
                            catch
                            {
                                //Console.WriteLine("Error on ActivityId");
                            }
                            try
                            {
                                RelatedActivityId = eventRecord.RelatedActivityId.ToString();
                            }
                            catch
                            {
                                //Console.WriteLine("Error on RelatedActivityId");
                            }
                            try
                            {
                                Hashcode = eventRecord.GetHashCode().ToString();
                            }
                            catch
                            {
                                //Console.WriteLine("Error on GetHashCode");
                            }
                            try
                            {
                                LevelDisplayName = eventRecord.LevelDisplayName;
                            }
                            catch
                            {
                                //Console.WriteLine("Error on LevelDisplayName");
                            }
                            try
                            {
                                OpcodeDisplayName = eventRecord.OpcodeDisplayName;
                            }
                            catch
                            {
                                //Console.WriteLine("Error on OpcodeDisplayName");
                            }
                            try
                            {
                                TaskDisplayName = eventRecord.TaskDisplayName;
                            }
                            catch
                            {
                                //Console.WriteLine("Error on TaskDisplayName");
                            }
                            //Console.WriteLine("-- ENDING --");

                            // Add them to the record. The things equal the things.
                            records.Add(new Record()
                            {
                                Message = Message, SystemTime = SystemTime, Id = Id, Version = Version, Qualifiers = Qualifiers, Level = Level, Task = Task, Opcode = Opcode, Keywords = Keywords, RecordId = RecordId, ProviderName = ProviderName, ProviderID = ProviderID, LogName = LogName, ProcessId = ProcessId, ThreadId = ThreadId, MachineName = MachineName, UserID = UserID, TimeCreated = TimeCreated, ActivityId = ActivityId, RelatedActivityId = RelatedActivityId, Hashcode = Hashcode, LevelDisplayName = LevelDisplayName, OpcodeDisplayName = OpcodeDisplayName, TaskDisplayName = TaskDisplayName
                            });
                        }
                    }
                    catch (UnauthorizedAccessException)
                    {
                        // If you are running as admin, you will get unauthorized for some logs. Hey, I warned you! Nothing to do here.
                        // Catching this seperately since we know what happened.
                    }
                    catch (Exception ex)
                    {
                        if (Log.ToString().Equals("Microsoft-RMS-MSIPC/Debug"))
                        {
                            // Known issue, do nothing
                            // https://github.com/BeanBagKing/EventFinder2/issues/3
                        }
                        else if (Log.ToString().Equals("Microsoft-Windows-USBVideo/Analytic"))
                        {
                            // Known issue, do nothing
                            // https://github.com/BeanBagKing/EventFinder2/issues/2
                        }
                        else
                        {
                            // Unknown issue! Write us a bug report
                            bool isElevated;
                            using (WindowsIdentity identity = WindowsIdentity.GetCurrent())
                            {
                                WindowsPrincipal principal = new WindowsPrincipal(identity);
                                isElevated = principal.IsInRole(WindowsBuiltInRole.Administrator);
                            }
                            using (StreamWriter writer = new StreamWriter(DesktopPath + "\\ERROR_EventFinder_" + RunTime + ".txt", append: true))
                            {
                                writer.WriteLine("-----------------------------------------------------------------------------");
                                writer.WriteLine("Issue Submission: https://github.com/BeanBagKing/EventFinder2/issues");
                                writer.WriteLine("Date : " + DateTime.Now.ToString());
                                writer.WriteLine("Log : " + Log);
                                writer.WriteLine("Admin Status: " + isElevated);
                                writer.WriteLine();

                                while (ex != null)
                                {
                                    writer.WriteLine(ex.GetType().FullName);
                                    writer.WriteLine("Message : " + ex.Message);
                                    writer.WriteLine("StackTrace : " + ex.StackTrace);
                                    writer.WriteLine("Data : " + ex.Data);
                                    writer.WriteLine("HelpLink : " + ex.HelpLink);
                                    writer.WriteLine("HResult : " + ex.HResult);
                                    writer.WriteLine("InnerException : " + ex.InnerException);
                                    writer.WriteLine("Source : " + ex.Source);
                                    writer.WriteLine("TargetSite : " + ex.TargetSite);

                                    ex = ex.InnerException;
                                }
                            }
                        }
                    }
                }
                records = records.OrderBy(x => x.SystemTime).ToList(); // Sort our records in chronological order
                // and write them to a CSV
                using (var writer = new StreamWriter(DesktopPath + "\\Logs_Runtime_" + RunTime + ".csv", append: true))
                    using (var csv = new CsvWriter(writer))
                    {
                        csv.Configuration.ShouldQuote = (field, context) => true;
                        csv.WriteRecords(records);
                    }
                StatusOutput.Text      = "Run Complete";
                StatusOutput.ForeColor = System.Drawing.Color.Blue;
                records.Clear();
            }
            FindEventsButton.Enabled = true;
        }
예제 #8
0
    public static int Main(string[] arguments)
    {
        // initiate parameter parsing
        ParseParameters parameter = new ParseParameters();

        // default parameter is allowed
        parameter.EnableDefaultParameter();

        // parse command line
        if (parameter.Scan(arguments))
        {         // error reading command line
            Console.Error.WriteLine(parameter.errorText);
            return(-1);
        }

        // check if there is an unknown parameter
        if (!parameter.CheckForUnknown(new string[] { "?", "h", "help", "l", "log", "logname", "c", "computer", "computername", "s", "start", "starttime", "e", "end", "endtime", "level", "csv", "f", "file", "filename", "q", "quiet" }))
        {         // error reading command line
            Console.Error.WriteLine("Unknown parameter error.");
            return(-1);
        }

        if (parameter.Exist("?") || parameter.Exist("h") || parameter.Exist("help"))
        {         // help wanted
            Console.WriteLine("{0}\t\t\t\t\tMarkus Scholtes, 2019\n", System.AppDomain.CurrentDomain.FriendlyName);
            Console.WriteLine("Console program to determine the events of all event logs ordered by time.\n");
            Console.WriteLine("{0} [[-logname:]<LOGNAMES>] [-level:<LEVEL>]", System.AppDomain.CurrentDomain.FriendlyName);
            Console.WriteLine("    [-starttime:<STARTTIME>] [-endtime:<ENDTIME>] [-computername:<COMPUTER>]");
            Console.WriteLine("    [-filename:<FILENAME>] [-csv] [-quiet] [-?|-help]");
            Console.WriteLine("\nParameters:");
            Console.WriteLine("-logname:<LOGNAMES> comma separated list of event log names. Queries all event");
            Console.WriteLine("    logs if omitted (can be abbreviated as -log or -l or can be omitted).");
            Console.WriteLine("-level:<LEVEL> queries up to level <LEVEL>. Queries all events if omitted.");
            Console.WriteLine("    Level: Critical - 1, Error - 2, Warning - 3, Informational - 4, Verbose - 5");
            Console.WriteLine("-starttime:<STARTTIME> start time of events to query (can be abbreviated as");
            Console.WriteLine("    -start or -s). Default is end time minus one hour.");
            Console.WriteLine("-endtime:<ENDTIME> end time of events to query (can be abbreviated as -end or");
            Console.WriteLine("    -e). Default is now.");
            Console.WriteLine("-computername:<COMPUTER> name of computer to query (can be abbreviated as");
            Console.WriteLine("    -computer or -c). Default is the local system.");
            Console.WriteLine("-filename:<FILENAME> name of the file in which the results are output (can be");
            Console.WriteLine("    abbreviated as -file or -f). Default is output to the console.");
            Console.WriteLine("-csv output format \"comma separated\" instead of output format text.");
            Console.WriteLine("-quiet shows only error messages and results (can be abbreviated as -q).");
            Console.WriteLine("-? or -help shows this help (can be abbreviated as -h).");
            Console.WriteLine("\nExamples:");
            Console.WriteLine("{0} -start:10:00 -end:11:00", System.AppDomain.CurrentDomain.FriendlyName);
            Console.WriteLine("{0} System,Setup,Application -Computer=REMOTESYSTEM", System.AppDomain.CurrentDomain.FriendlyName);
            Console.WriteLine("{0} /logname=Application /level:2 /q /CSV /file:OnlyErrors.csv", System.AppDomain.CurrentDomain.FriendlyName);
            Console.WriteLine("{0} \"/starttime:2019/11/29 10:00\" \"/endtime:2019/11/29 11:00\"", System.AppDomain.CurrentDomain.FriendlyName);
            Console.WriteLine("{0} \"/s=2019/12/08 10:09:49.450\" \"/e=2019/12/08 10:09:49.850\"", System.AppDomain.CurrentDomain.FriendlyName);
            return(0);
        }

        bool bQuiet = false;         // no status messages?

        if (parameter.Exist("q") || parameter.Exist("quiet"))
        {
            bQuiet = true;
        }

        // read end time for log query
        DateTime endTime;
        // read parameter /e, /end or /endtime
        string endString = parameter.ValueOrDefault("e", parameter.ValueOrDefault("end", parameter.Value("endtime")));

        if (endString != "")
        {         // parameter set, convert to timestamp
            try {
                endTime = DateTime.Parse(endString);
            }
            catch
            {             // cannot convert string to timestamp
                Console.Error.WriteLine("Error: unknown time format");
                return(-1);
            }
        }
        else
        {
            // parameter not specified, use default (now)
            endTime = DateTime.Now;
        }

        // read start time for log query
        DateTime startTime;
        // read parameter /s, /start or /starttime
        string startString = parameter.ValueOrDefault("s", parameter.ValueOrDefault("start", parameter.Value("starttime")));

        if (startString != "")
        {         // parameter set, convert to timestamp
            try {
                startTime = DateTime.Parse(startString);
            }
            catch
            {             // cannot convert string to timestamp
                Console.Error.WriteLine("Error: unknown time format");
                return(-1);
            }
        }
        else
        {
            // parameter not specified, use default (end time minus one hour)
            startTime = endTime.AddHours(-1.0);
        }

        if (endTime <= startTime)
        {         // end time has to be later than start time
            Console.Error.WriteLine("Error: end time has to be later than start time");
            return(-1);
        }

        // get information level, 0 = default = return all events
        // Level: LogAlways - 0, Critical - 1, Error - 2, Warning - 3, Informational - 4, Verbose - 5
        // there are different levels for auditing logs!
        string informationLevel = parameter.Value("level");
        int    maxLevel         = 0;

        if (informationLevel != "")
        {         // parameter level was given
            if (Int32.TryParse(informationLevel, out maxLevel))
            {     // filter for information level
                if ((maxLevel < 0) || (maxLevel > 5))
                {
                    // mark as wrong information level
                    maxLevel = -1;
                }
            }
            else
            {
                // mark as wrong information level
                maxLevel = -1;
            }
            if (maxLevel < 0)
            {             // wrong information level -> error
                Console.Error.WriteLine("Error: unknown information level");
                Console.Error.WriteLine("The following values are allowed: up to Critical - 1, up to Error - 2, up to Warning - 3, up to Informational - 4, up to Verbose - 5");
                return(-1);
            }
        }

        // connect to remote computer in parameter /c, /computer or /computername or to "localhost"
        EventLogSession session = new EventLogSession(parameter.ValueOrDefault("c", parameter.ValueOrDefault("computer", parameter.ValueOrDefault("computername", "localhost"))));

        int outputMode = 1;         // 1 - Text, 2 - CSV

        if (parameter.Exist("csv"))
        {
            outputMode = 2;
        }

        // get filename. If no filename is given output is written to console
        string fileName = parameter.ValueOrDefault("f", parameter.ValueOrDefault("file", parameter.Value("filename")));

        List <string> logNames;

        // read parameter /l or /log or default parameter for log name (or comma separated list of names given)
        if (parameter.ValueOrDefault("l", parameter.ValueOrDefault("log", parameter.ValueOrDefault("logname", parameter.DefaultParameter()))) != "")
        {         // yes, only read those logs
            logNames = new List <string>(parameter.ValueOrDefault("l", parameter.ValueOrDefault("log", parameter.DefaultParameter())).Split(new char[] { ',', ';' }).Where(val => val.Trim() != "").Select(val => val.Trim()).ToArray());
        }
        else
        {         // no parameter for log, read all logs
            try { // retrieve all log names
                logNames = new List <string>(session.GetLogNames());
            }
            catch (Exception e)
            {             // cannot retrieve log names
                Console.Error.WriteLine("Error connecting to event log: " + e.Message);
                return(-2);
            }
        }

        // sort log names now to save work later
        logNames.Sort();

        int logCount = 0;
        List <EventEntry> eventList = new List <EventEntry>();

        foreach (string name in logNames)
        {         // query entries for all logs
            if (GetEntries(ref eventList, name, session, startTime, endTime, maxLevel, outputMode, bQuiet))
            {
                logCount++;
            }
        }

        if (eventList.Count > 0)
        {         // only write events if there are any
            if (fileName == "")
            {     // output to console
                if (outputMode == 1)
                {
                    Console.WriteLine("time created\tlog\tid\tsource\tlevel\tdescription");
                }
                else
                {
                    Console.WriteLine("\"time created\";\"log\";\"id\";\"source\";\"level\";\"description\"");
                }

                foreach (EventEntry entry in eventList.OrderBy(a => a.timeCreated))
                {                 // output events sorted by time
                    Console.WriteLine(entry.message);
                }
            }
            else
            {                   // output to file
                try {
                    // write header line only to new files
                    bool typeHeader = true;
                    if (File.Exists(fileName))
                    {
                        typeHeader = false;
                    }

                    FileStream fs = new FileStream(fileName, FileMode.Append);
                    using (StreamWriter sw = new StreamWriter(fs, Encoding.Default))
                    {
                        if (typeHeader)
                        {                         // output the header line
                            if (outputMode == 1)
                            {
                                sw.WriteLine("time created\tlog\tid\tsource\tlevel\tdescription");
                            }
                            else
                            {
                                sw.WriteLine("\"time created\";\"log\";\"id\";\"source\";\"level\";\"description\"");
                            }
                        }

                        foreach (EventEntry entry in eventList.OrderBy(a => a.timeCreated))
                        {                         // output events sorted by time
                            sw.WriteLine(entry.message);
                        }
                    }
                    if (fs != null)
                    {
                        fs.Dispose();
                    }
                }
                catch (Exception e)
                {
                    Console.Error.WriteLine("Error writing to file \"" + fileName + "\": " + e.Message);
                    return(1);
                }
            }
        }

        if (!bQuiet)
        {
            Console.WriteLine("Successfully processed " + eventList.Count + " events from " + logCount + " logs, access errors with " + (int)(logNames.Count - logCount) + " logs.");
        }
        return(0);
    }
예제 #9
0
        static bool CollectEVT2(string Book)
        {
            try
            {
                EventLogSession session = new EventLogSession();

                bool Found = false;
                foreach (string logName in session.GetLogNames())
                {
                    if (Book == logName)
                    {
                        Found = true;
                        break;
                    }
                }

                if (Found == false)
                {
                    return(true);
                }

                EventLogReader evt = new EventLogReader(Book);

                EventRecord log;
                while ((log = evt.ReadEvent()) != null)
                {
                    EventLogReport ev = new EventLogReport();

                    ev.Category       = "(" + log.Id + ")";
                    ev.CategoryNumber = log.Id;
                    ev.Data           = new byte[0];
                    ev.EventLog       = Book;
                    switch (log.LevelDisplayName.ToLower())
                    {
                    case "information":
                        ev.EventLogType = (int)EventLogEntryType.Information; break;

                    case "warning":
                        ev.EventLogType = (int)EventLogEntryType.Warning; break;

                    case "error":
                        ev.EventLogType = (int)EventLogEntryType.Error; break;

                    default:
                        ev.EventLogType = (int)EventLogEntryType.Information; break;
                    }
                    ev.InstanceID             = log.Id;
                    ev.LogID                  = "";
                    ev.MachineID              = SystemInfos.SysInfo.MachineID;
                    ev.Message                = MakeNiceXML(log.ToXml());
                    ev.Source                 = log.ProviderName;
                    ev.TimeGenerated          = log.TimeCreated == null?DateTime.Now: log.TimeCreated.Value;
                    ev.TimeWritten            = log.TimeCreated == null ? DateTime.Now : log.TimeCreated.Value;
                    ev.JSONReplacementStrings = "[]";
                    CommonUtilities.CalcEventLogID(ev);
                    HasEVTLogs.Add(ev.LogID);
                    lst.Add(ev);
                }
            }
            catch
            {
                FoxEventLog.WriteEventLog("Cannot collect EventLog " + Book, EventLogEntryType.Error);
            }
            return(true);
        }