C# File Logging for Debugging
In almost any project that requires debugging you need to have a logger that properly writes all your commands and suspicious variables into a file. Logging can save you a lot of effort because sometimes you think you understand how a built-in function works but you can be wrong. The following code can be used simply by typing Log.Logger.log("First log");. That's simple logging for debugging.
Contents [hide]
Logger Class
Just write the following code into a log.cs file in any project and you can use it.
using System.Collections.Generic;
using System.Text;
using System.IO;
// Code developed by InfernoDevelopment.com
namespace Log {
public class Logger {
public static void log(String message) {
DateTime datet = DateTime.Now;
String filePath = "Log" + datet.ToString("MM_dd") + ".log";
if (!File.Exists(filePath)) {
FileStream files = File.Create(filePath);
files.Close();
}
try {
StreamWriter sw = File.AppendText(filePath);
sw.WriteLine(datet.ToString("MM/dd hh:mm") + "> " + message);
sw.Flush();
sw.Close();
} catch (Exception e) {
Console.WriteLine(e.Message.ToString());
}
}
}
}
// Code by InfernoDevelopment.com
DateTime class provides the date and time which can be formatted using ToString. FileStream can be called to create the file if it doesn't exist yet.
StreamWriter class is useful for writing lines of text which will be written to the file using AppendText function.
The log file will be saved in the bin/debug folder or where ever your exe file is located.
Optionally you can Console.Writeline everything.
Testing of Log Class
Here's an example of it's usage:

Post new comment