I Have this class want to practice how to write a factory method pattern
and I can change the logPlace
by set the app.config,
and I try to improve the performance so I use static List<string>
,I want to decrease IO loading
Here is my question
- This class can call factory method pattern or not?
- Is my code as clear as it could be?
- I think the
LogBoth
class can be much better, but I have no idea how to improve it.
public enum LogLevel
{
Error, Debug, Info, Fatal
}
static class Msg
{
public static List<string> msgList = new List<string>();
}
public class LogHelper
{
public static ILog Create()
{
string logPlace = System.Web.Configuration.WebConfigurationManager.AppSettings["LogPlace"];
switch (logPlace)
{
case "DB":
return new LogDB();
case "File":
return new LogFile();
case "Both":
return new LogBoth();
default:
return new LogFile();
}
throw new NullReferenceException();
}
}
public interface ILog
{
void WriteLog(string msg);
void ExecWrite(LogLevel logLevel);
}
public class LogDB : ILog
{
public LogDB()
{
Msg.msgList.Clear();
}
public void WriteLog(string msg)
{
Msg.msgList.Add(msg);
}
public void ExecWrite(LogLevel logLevel)
{
throw new NotImplementedException();
}
}
public class LogFile : ILog
{
private static object _lockObject = new object();
public LogFile()
{
Msg.msgList.Clear();
}
public void WriteLog(string msg)
{
Msg.msgList.Add(msg);
}
public void ExecWrite(LogLevel logLevel)
{
try
{
Policy.Handle<Exception>().Retry(1).Execute(()=>WriteToFile(logLevel));
}
catch (Exception ex)
{
LogDB logDB = new LogDB();
logDB.ExecWrite(logLevel);
}
}
private void WriteToFile(LogLevel logLevel)
{
lock (_lockObject)
{
using (FileStream fs = new FileStream(Path.Combine(path, fileName), FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
{
using (StreamWriter sw = new StreamWriter(fs))
{
foreach (string msg in Msg.msgList)
{
sw.WriteLine(string.Format("{0} [{1}] {2}", DateTime.UtcNow.AddHours(08).ToString("yyyy/MM/dd HH:mm:ss"), logLevel, msg));
}
}
}
}
}
}
public class LogBoth : ILog
{
public LogBoth()
{
Msg.msgList.Clear();
}
public void ExecWrite(LogLevel logLevel)
{
LogDB logDB = new LogDB();
LogFile logFile = new LogFile();
logDB.ExecWrite(logLevel);
logFile.ExecWrite(logLevel);
}
public void WriteLog(string msg)
{
Msg.msgList.Add(msg);
}
}