这是一个简单的日志记录功能,不需要插件。打开程序后可以直接使用。我这里使用的是WPF
public partial class MainWindow : Window
{
WriteLog log = new WriteLog();
public MainWindow()
{
InitializeComponent();
}
private void Setlog_Click(object sender, RoutedEventArgs e)
{
log.Logger("日志记录一下");
try
{
//这里我随便写了一个报错的程序
string filelog = AppDomain.CurrentDomain.BaseDirectory + "log11\\" + DateTime.Now.ToString("yyyy_MM_dd") + ".txt";
File.AppendAllText(filelog, "1111");//这句话因为异常是不会执行的
}
catch (Exception ex)
{
log.Logger(ex.ToString());
}
}
}
public class WriteLog
{
public void Logger( string msg)
{
string filePath = AppDomain.CurrentDomain.BaseDirectory + "log";
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
//这是一个日志的路径,日志名称是时间,这个时间格式可以自由搭配
string filelog = AppDomain.CurrentDomain.BaseDirectory + "log\\" + DateTime.Now.ToString("yyyy_MM_dd") + ".txt";
try
{
//加上锁,避免同时使用
lock (this)
{
string ss = msg + Environment.NewLine;//这句话是换行用的,不喜欢的可以删掉
using (StreamWriter write = File.AppendText(filelog))
{
write.WriteLine("时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss "));
write.WriteLine("信息:" + msg);
write.WriteLine("信息2:" + ss);
write.WriteLine();
write.Flush();
write.Close();
}
#region 另一种方式
//不过我这里的msg并没有处理,
//写到日志里的应该是没有任何格式的,
//日志与日志之间是不换行的,
//可以简单处理msg,像上面的方法在写入也可以
//File.AppendAllText(filelog, msg);
#endregion
}
}
catch (Exception ex)
{
}
}
}