How to write Event viewer log using C#


Below Code will show how to Create/write into windows event viewer.

You can create your own Event viewer by specifying the name instead of "Application" in the program.

Only thing you have to remember is if you are writing into the server you should have admin rights to create event viewer in the systm.

using System;
using System.Collections.Generic;
using System.Text;
//Need to add Below namespace to use Event viewer
using System.Diagnostics;

namespace TestEventLog
class WriteEventLog
static void Main(string[] args)
//Call function to write into event log
WriteEventLog EvtLog = new WriteEventLog();
private void LogErrorToEventLog()
string sSource = "Test"; ;
//Event log name where we are going to write
string sLog = "Application";
//String to write into the event log
string strErrToWrite = "Error Occured";
//Create event viewer if it does not exists
if (!EventLog.SourceExists(sSource))
EventLog.CreateEventSource(sSource, sLog);
//Code to write Event into log
EventLog.WriteEntry(sSource, strErrToWrite, EventLogEntryType.Error, 234);
catch (Exception ex)
String strErr = "Error writing into event log:" + ex;


  • Sample code attached (34880-221020-TestEventLog.rar)
  • Comments

    Author: ABitSmart22 Nov 2009 Member Level: Gold   Points : 0

    Please use code block for code.

    Author: Asheej T K22 Nov 2009 Member Level: Gold   Points : 1

    I have formatted the code, but when i paste it here all formatting disappeard. I don't know is this the way you are expecting. Let me know if there is any other way to do it.

    Author: ABitSmart22 Nov 2009 Member Level: Gold   Points : 1

    You need to add the code blocks. I have added it for you. Take a look at your resource now. If you Edit it, you will see the CODE blocks added.

    Author: Asheej T K22 Nov 2009 Member Level: Gold   Points : 0

    Thank you i got it now..

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: