我准备开始开发一个新应用程序,该应用程序必须连接到不同机器的不同API,这将使应用程序相当复杂。
有什么方法可以实现登录我的应用程序,它们各自的优缺点是什么?更准确地说,我正在研究将日志导出到外部日志文件的最佳方法。
详细说明:
目前我正在使用一个系统,我在这里添加了一个日志列表,然后我通过后台工作线逐行处理。
我的想法是,通过将日志处理放在不同的线程上,我不会打扰主UI线程或任何其他线程。
但是,我认为我仍然在我的UI线程中使用不必要的资源,因为我在UI线程上编译和添加我的logentry。我是否应该将实际条目放在另一个帖子上?
以下是我目前使用的代码:
List<LoggingClass> Logs;
BackgroundWorker bgLogs;
public void startLogging()
{
// INITIALIZE THE BACKGROUND WORKER
bgLogs = new BackgroundWorker();
// SET UP THE BACKGROUND WORKER
bgLogs.WorkerSupportsCancellation = true;
bgLogs.WorkerReportsProgress = false;
bgLogs.DoWork += bgLogs_DoWork;
// START THE BACKGROUND WORKER
bgLogs.RunWorkerAsync();
}
private void bgLogs_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
while (worker.IsBusy == true)
{
if (worker.CancellationPending == true)
{
e.Cancel = true;
break;
}
else
{
if (Logs != null && Logs.Count > 0)
{
processLogs();
}
Thread.Sleep(1000);
}
}
}
public void log(DateTime logTimeStamp, LogType logType, string logContent)
{
// CHECK IF THE LIST OF LOGS EXISTS
if (Logs == null)
{
Logs = new List<LoggingClass>();
}
// CREATE A TEMPORARY LOG ENTRY
LoggingClass tmpLog = new LoggingClass();
tmpLog.TimeStamp = logTimeStamp;
tmpLog.Type = logType;
tmpLog.Content = logContent;
// ADD THE LOG TO THE LIST OF LOGS
Logs.Add(tmpLog);
// CLEAR THE TEMPRARY LOG
tmpLog = null;
}
private void processLogs()
{
string logOutput = string.Empty;
do
{
// CREATE A TEMPORARY LOG ENTRY
LoggingClass tmpLog = Logs[0];
// APPEND THE LOG DATA INTO THE TEMPORARY STRING
logOutput += string.Format("[{0}]\t{1}\t{2}", tmpLog.TimeStamp.ToString("HH:mm:ss.fff"), tmpLog.Type.ToString(), tmpLog.Content) + Environment.NewLine;
// REMOVE THE FIRST LOG ENTRY
Logs.RemoveAt(0);
} while (Logs.Count > 0);
// GET THE FILENAME FOR THE LOGGING FILE
DateTime currentDate = DateTime.Now;
string logFile = Path.GetFullPath(Path.Combine(Application.ExecutablePath, @"..\LOGS\" + currentDate.ToString("yyyyMMdd") + "_log.log"));
// CHECK AND CREATE IF NEEDED THE LOGS DIRECTORY
Directory.CreateDirectory(Path.GetDirectoryName(logFile));
// ADD THE LOGGINGCONTENT TO THE LOG FILE
File.AppendAllText(logFile, logOutput, Encoding.UTF8);
}
class LoggingClass
{
public DateTime TimeStamp { get; set; }
public LogType Type { get; set; }
public string Content { get; set; }
}
使用此方法有任何问题吗?