I want to write a logger class which writes output to a log file based on user actions. I have written a logmessage class for this purpose. Following is what I have.
public class LogMessage
{
private static Object padlock = new Object();
private static string serviceDirectory ="C:\\MySite\\";
private static string filePath = "\\Logs\\Combined\\ActivityMonitorLog-" + DateTime.Now.ToString("dd'-'MM'-'yyyy") + ".log";
private static volatile LogMessage instance = new LogMessage();
public static LogMessage Instance
{
get
{
if (instance == null)
{
lock (padlock)
{
if (instance == null)
instance = new LogMessage();
}
}
return instance;
}
}
public void SaveLogMessage(string userName, string message, string stackTrace)
{
lock (padlock)
{
using (StreamWriter logWriter =
new StreamWriter(serviceDirectory + filePath, true))
{
string logMessage = "";
if (!string.IsNullOrEmpty(stackTrace))
logMessage = string.Format("{0} >> user : {1} ::: {2} ::: stack trace ::: {3}", DateTime.Now.ToString(), userName, message,stackTrace);
else
logMessage = string.Format("{0} >> user : {1} ::: {2}", DateTime.Now.ToString(), userName, message);
logWriter.WriteLine(logMessage);
}
}
}
}
And when i want do a log entry I am calling the about method like below
LogMessage.Instance.SaveLogMessage("My User", "Enter Logout PageLoad : Current Method :" + "Page_Load @ Logout.aspx.cs", "");
I believe I have got the singleton part and thread safety achieved. But I don't think this is non blocking as multiple users are logged in at the same time each one will have to wait until the file is available to be written. I am pondering about using a backgroundworker
to call this SaveLogMessage() from the LogMessage singleton object. Is that the correct way of doing it?
UPDATE
I have implemented this using backgroundworker and the complete class and how to call is mentioned in the answers. Thanks for inputs @bret and @huan