I'm trying to read event logs for my application EventLoggingApp. The problem is reading logs for my single source (EventLoggingApp).
This code read logs for every source. What is the problem? Any advice?
static void ReadEvenLog()
{
string eventLogName = "Application";
string sourceName = "EventLoggingApp";
string machineName = "Tom";
EventLog eventLog = new EventLog();
eventLog.Log = eventLogName;
eventLog.Source = sourceName;
eventLog.MachineName = machineName;
foreach (EventLogEntry log in eventLog.Entries)
{
Console.WriteLine("{0}\n",log.Source);
}
}
Try this:
EventLog log = new EventLog("Security");
var entries = log.Entries.Cast<EventLogEntry>()
.Where(x => x.InstanceId == 4624)
.Select(x => new
{
x.MachineName,
x.Site,
x.Source,
x.Message
}).ToList();
Check out this article on MSDN. You can't read event log entries by source. Only log name matters. Instead you can create separate event log for you application or filter entries by verifying Source property of each entry in foreach loop.
MSDN (1)(2) says that Source is for writing event logs only.
It is not necessary to specify a Source when only reading from a log. You can specify only the Log name and MachineName (server computer name) properties for the EventLog instance. In either case, the Entries member is automatically populated with the event log's list of entries. You can select the appropriate index for an item in this list to read individual entries. (1)
I am not really sure what you were trying to print on the console. If it is the message in each event log entry that you are trying to print, inside the foreach loop you should have this instead:
Console.WriteLine(log.Message + "\n");
If you connect to localhost set MachineName to "."
Check if user has right to read from eventlog
Related
i am getting all information from windows security log and event viewer related to logon and logg off but i want only latest loggon event info from all information can you please apply some linq on that to get the top most Startup Login event info
here is my code what i am trying
EventLog log = new EventLog()
{
Source = "Microsoft Windows security auditing.",
Log = "Security"
};
foreach (EventLogEntry entry in log.Entries)
{
Console.WriteLine(entry.Message);
}
can you make any foreach in lambda base to get only logon event that is the latest one
Here is a sample to get the latest "Logon (4624)" and "Special Logon (4672)"
var log = new EventLog
{
Source = "Microsoft Windows security auditing.",
Log = "Security"
};
var latestLogon =
log.Entries.Cast<EventLogEntry>()
.Where(entry => entry.InstanceId == 4624 || entry.InstanceId == 4672)
.OrderByDescending(i => i.TimeWritten)
.FirstOrDefault();
I know that I can read the Security logs of a Windows PC using:
var securityLog = new EventLog("security");
foreach (EventLogEntry entry in securityLog.Entries) {
...
}
The entry item contains all the interesting log fields I expect to see like: InstanceId, Message and others. What I want to do now is read the same things from an event log that was saved to disk as an .evtx file.
I have seen suggestions for using
string xpathQuery = "*";
var eventsQuery = args.Length == 0
? new EventLogQuery("Security", PathType.LogName, xpathQuery)
: new EventLogQuery(args[0], PathType.FilePath, xpathQuery);
using (var eventLogReader = new EventLogReader(eventsQuery)) {
EventLogRecord entry;
while ((entry = (EventLogRecord) eventLogReader.ReadEvent()) != null) {
...
}
}
but the entry in the second version doesn't contain the same members/values as the first example. I totally dig that I am confused and am looking at the problem the wrong way.
How should one go about reading the actual per record content from either an active or saved system log?
Or, can I go from an EventLogRecord to an EventLogEntry? I have not seen that conversion method yet.
Here i am trying to read the local system event log using c# using this code-
string eventLogText = "";
try
{
var eventLog = new EventLog("logname", "machinename");
foreach (var entry in eventLog.Entries)
{
eventLogText += entry;
}
}
catch (Exception eg)
{
MessageBox.Show(eg.Message);
}
It is working well, but the problem is, in the variable eventLogText i get only System.Diagnostics.EventLogEntry repeatedly, may be this is very common mistake but i don't know what to do as i am very new to the c# as well as programming too.
Secondly i want to know that if a system is not logged in using Administrator account, in that case reading event log will cause any exception or error and if it will what will be the solution for it ?
Need help.Thanks in advance.
Regarding your first question, you are just adding the variable entry to the string, which is calling the ToString method on that variable. The default implementation of ToString is to return the name of the class. (Hence the repeated System.Diagnostics.EventLogEntryoutput)
You will need to use the members in the EventLogEntry class to retrieve the data you are interested in. For example, this console application will print the source and message of the first 10 entries in the Application event log:
static void Main(string[] args)
{
StringBuilder eventLogText = new StringBuilder();
try
{
var eventLog = new EventLog("Application");
var tenMostRecentEvents = eventLog.Entries
.Cast<EventLogEntry>()
.Reverse()
.Take(10);
foreach (EventLogEntry entry in tenMostRecentEvents)
{
eventLogText.AppendLine(String.Format("{0} - {1}: {2}",
entry.Source,
entry.TimeWritten,
entry.Message));
}
Console.WriteLine(eventLogText.ToString());
}
catch (System.Security.SecurityException ex)
{
Console.WriteLine(ex);
}
Console.ReadLine();
}
Regarding your second question, your code will need the appropriate permissions to read that event log. For example, if I change the code read the Security event log using this line var eventLog = new EventLog("Security"); I will receive a security exception. You can check this answer for more information
Hope it helps!
In the Windows 7 and Server 2008 Event Viewer there is a folder for...
Applications and Services Logs
I want to create a place where all events from my application are logged. How do you create a log under this area? From the event viewer, all I see is "Create View" which appears to simply be a way to create a filtered view of events in a particular log.
Once this is created, how do you write events to it?
For example if my log is named 'StackApp', would you just use...
EventLog.WriteEntry('StackApp', message);
Thanks!
if your EventLog was created then you can do EventLog.WriteEntry("StackApp", message);
//create a log
string source;
string logName;
string machineName;//use "." for this machine
if (!EventLog.Exists(logName, machineName))
{
EventSourceCreationData creationData = new EventSourceCreationData(source, name);
EventLog.CreateEventSource(creationData);
}
More operation on log:
//find your log in the windows EventLog by name
EventLog log = null;
foreach (EventLog eventLog in EventLog.GetEventLogs())
{
if (string.Compare(eventLog.Log, logName, true) == 0)
{
log = eventLog;
break;
}
}
//modify log settings
log.ModifyOverflowPolicy(OverflowAction.OverwriteAsNeeded, 7);
log.MaximumKilobytes = MaxLogSize;
//write to event to log
EventLog.WriteEntry(source, message);
//more advance writing to log instance
long instanceId;
int categoryId;;
EventLogEntryType entryType;
byte[] binaryData;
object[] values;
EventInstance eventInstance = new EventInstance(instanceId, categoryId, entryType);
log.WriteEvent(eventInstance, binaryData, values);
i am sending email from windows service. It threw an error of "event log file is full" sometimes when i am writing the event entry into event viewer.
How to check whether it is full or not?
thanks
You use OverflowAction property of EventLog class
More information : http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.overflowaction.aspx
Event Log size is based on storage size and not by number of entries so it would be little bit difficult to figure out if event log is full or not. For example,
bool logFull = false;
EventLog e = ... // get the needed event log
var sizeKB = e.MaximumKilobytes; // event log size
// Check current event log size
var regEntry = Rgistry.LocalMachine.OpenSubKey("System\\CurrentControlSet\\Services\\EventLog\\" + e.Log);
if (regEntry != null)
{
var filePath = regEntry.GetValue("File");
if (filePath != null)
{
var file = new FileInfo(filePath.ToString());
if (file.Exists)
{
var fileSize = (file.Length + 1023) / 1024;
logFull = (fileSize >= sizeKB); // a 1K margin
}
}
}
So above code is using 1KB margin to decide if log file is full or not. As such, I would suggest that you always wrap your event entry writing code inside exception block to avoid rare scenario where current log may take you beyond event log size.