The C# team posts answers to common questions and describes new language features
Often, you need a way to monitor your applications once they are running on the server or even at the customer site -- away from your Visual Studio debugger. In those situations, it is often helpful to have a simple routine that you can use to log messages to a text file for later analysis.
Here’s a simple routine that has helped me a lot for example when writing server applications without an user interface:
using System.IO; public string GetTempPath() { string path = System.Environment.GetEnvironmentVariable("TEMP"); if (!path.EndsWith("\\")) path += "\\"; return path; } public void LogMessageToFile(string msg) { System.IO.StreamWriter sw = System.IO.File.AppendText( GetTempPath() + "My Log File.txt"); try { string logLine = System.String.Format( "{0:G}: {1}.", System.DateTime.Now, msg); sw.WriteLine(logLine); } finally { sw.Close(); } }
With this simple method, all you need to do is to pass in a string like this:
LogMessageToFile("Hello, World");
The current date and time are automatically inserted to the log file along with your message.
[author: Jani Järvinen, C# MVP]
Der einfachste Weg, meiner Meinung nach, um ein LogFile für ein Applikation in C# zu erstellen: public static void Log(String logMessage) { using (StreamWriter w = File.AppendText("log.txt")) { w.Write("\r\n{0} {1}&qu
PingBack from http://blog.gotchi.at/2007/05/08/logfiles-in-c-erstellen/
Today, either Bloglines.com or blogs.MSDN.com blinked, and suddenly I'm seeing old entries on the 'C#
private static readonly string LOG_FILENAME = Path.GetTempPath() + "My Log File.txt";
public static void LogMessageToFile(string msg)
{
msg = string.Format("{0:G}: {1}\r\n", DateTime.Now, msg);
File.AppendAllText(LOG_FILENAME, msg);
}
Thanks for this, it is very helpful.
Simple, elegant just what I wanted.
I will keep this as the basis for my future loggers.
Even better...
msg = string.Format("{0:G}: {1}{2}", DateTime.Now, msg, Environment.NewLine);
Sometimes..okay most of the time....simple is better. Thanks Jani!
thank you, really useful stuff. I'll change the log path with my app path though, it makes more sense to me.