How to create log files for your application?

Hi! Friends, today I am explaining you with example how to create your own log files for the application. Suppose, you u want to track all the users who are logging into the application then you can write a log entry for each individual user login. And you can also use to write Error log files.

Let’s take an example:

Using System;
Using System.IO;

Namespace SimpleEvent

{
/* ——————————— Publisher of the Event ————————–*/
Public class MyClass
{
// First define a delegate named LogHandler, that will encapsulate. Any method that
takes a string as the parameter and returns no value

Public delegate void LogHandler(string message);

// Define an Event based on the above Delegate
Public event LogHandler Log;

// Instead of having the Process() function take a delegate
// as a parameter, we’ve declared a Log event. Call the Event,
// using the OnABCMethod, where ABCis the name of the Event.
Public void Process()
{
OnLog(“Process() begin”);
OnLog(“Process() end”);
}

// By Default, create an OnABCMethod, to call the Event
Protected void OnLog(string message)
{
if (Log != null)
{
Log(message);
}
}
}

// The FileLogger class merely encapsulates the file I/O
Public class FileLogger
{
FileStream fileStream;
StreamWriter streamWriter;

// Constructor
Public FileLogger(string filename)
{
fileStream = new FileStream(filename, FileMode.Create);
streamWriter = new StreamWriter(fileStream);
}

// Member Function which is used in the Delegate
Public void Logger(string s)
{
streamWriter.WriteLine(s);
}

Public void Close()
{
streamWriter.Close();
fileStream.Close();
}
}

/* ——————————— Subscriber of the Event ——————————— */
// It’s now easier and cleaner to merely add instances
// of the delegate to the event, instead of having to
// manage things ourselves
Public class TestApplication
{
Static void Logger(string s)
{
Console.WriteLine(s);
}

Static void Main(string[] args)
{
FileLogger fl = new FileLogger(“process.log”);
MyClass myClass = new MyClass();

// Subscribe the Functions Logger and fl.Logger
myClass.Log += new MyClass.LogHandler(Logger);
myClass.Log += new MyClass.LogHandler(fl.Logger);

// The Event will now be triggered in the Process() Method
myClass.Process();

fl.Close();
}
}
}

I hope you will like this method to create log files.

Please follow & like us 🙂