How do I do logging in C# without using 3rd party libraries? [closed]
public void Logger(string lines)
{
//Write the string to a file.append mode is enabled so that the log
//lines get appended to test.txt than wiping content and writing the log
using(System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test.txt", true))
{
file.WriteLine(lines);
}
}
For more information MSDN
I would rather not use any outside frameworks like log4j.net.
Why? Log4net would probably address most of your requirements. For example check this class: RollingFileAppender.
Log4net is well documented and there are thousand of resources and use cases on the web.
You can write directly to an event log. Check the following links:
http://support.microsoft.com/kb/307024
http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.aspx
And here's the sample from MSDN:
using System;
using System.Diagnostics;
using System.Threading;
class MySample{
public static void Main(){
// Create the source, if it does not already exist.
if(!EventLog.SourceExists("MySource"))
{
//An event log source should not be created and immediately used.
//There is a latency time to enable the source, it should be created
//prior to executing the application that uses the source.
//Execute this sample a second time to use the new source.
EventLog.CreateEventSource("MySource", "MyNewLog");
Console.WriteLine("CreatedEventSource");
Console.WriteLine("Exiting, execute the application a second time to use the source.");
// The source is created. Exit the application to allow it to be registered.
return;
}
// Create an EventLog instance and assign its source.
EventLog myLog = new EventLog();
myLog.Source = "MySource";
// Write an informational entry to the event log.
myLog.WriteEntry("Writing to event log.");
}
}
If you are looking for a real simple way to log, you can use this one liner. If the file doesn't exist, it's created.
System.IO.File.AppendAllText(@"c:\log.txt", "mymsg\n");
I used to write my own error logging until I discovered ELMAH. I've never been able to get the emailing part down quite as perfectly as ELMAH does.