2014-04-04 44 views
0

我已經創建了一個簡單的應用程序將文件從我的電腦複製到閃存驅動器,我想要記錄用戶活動。 like: 啓動和關閉應用程序的時間。 複製的文件夾或文件的路徑和目標的路徑。 新建文件夾的時間和名稱...等。c#如何創建用戶活動的日誌?

我沒有嘗試任何東西,因爲我不知道如何去做。

我需要但記錄的數據到一個文本文件。我正在使用Windows窗體

謝謝您提前。

+0

爲什麼不直接寫入文本文件? – paqogomez

+0

然後使用@safeOtter的答案。簡單的文本文件作家。儘管他的解決方案中存在併發問題。你可能想看看[Log4Net](http://www.nuget.org/packages/log4net/2.0.3)。設置起來不復雜,但處理你想要的任何東西。 – paqogomez

+0

我做了一個基本的'用戶活動記錄器掛鉤各種事件'的實現,你可以在這裏看到:** http://stackoverflow.com/questions/30326673/user-activity-logging-see-variables-in -a全局異常處理程序** –

回答

2

我用這樣的事情時,我希望有一個簡單的文本文件日誌:

static void LogThis(string logMessage) 
    { 
     Console.WriteLine(logMessage); 
     using (StreamWriter writer = new StreamWriter(FileDate() + ".txt", true)) 
     { 
      writer.WriteLine(logMessage); 
      writer.WriteLine(); 
     } 
    } 

    static string FileDate() 
    { 
     return DateTime.Now.ToString("yyyy") + "-" + DateTime.Now.ToString("MM") + "-" + DateTime.Now.ToString("dd"); 
    } 

用法:

LogThis("I'm logging this!"); 
+0

如何處理併發性? – paqogomez

+0

@paqogomez我想通過刪除字符串並將函數留空。只是一個猜測。 –

+0

@ Zaid_Code36,我問otter如果多線程應用程序使用這一點代碼會發生什麼。有文件被鎖定和錯誤被拋出的可能性。 – paqogomez

1

使用System.Diagnostics命名空間中,使用事件日誌:

來源:http://msdn.microsoft.com/en-us/library/xzwc042w(v=vs.110).aspx

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; 
    } 

EventLog myLog = new EventLog(); 
    myLog.Source = "MySource"; 

    // Write an informational entry to the event log.  
    myLog.WriteEntry("Writing to event log.");