WPF开发随笔收录-本地日志LogUtil类
WPF开发随笔收录-本地日志LogUtil类
一、前言
生活中的日志是记录你生活的点点滴滴,让它把你内心的世界表露出来,更好的诠释自己的内心世界。而在开发者眼中的日志是我们排除问题的第一手资料,项目中的程序上线之后,一旦发生异常,第一件事就是先去查看日志是否有捕获到什么异常信息,然后再根据日志去排查问题。所以日志的重要性是非常高的,今天就分享一个简单的本地日记工具类。
二、正文
1、代码比较简单,这里直接贴出日志的代码,该类会在exe所在的目录下生成一个文件夹,然后每天生成一个文本来储存日志信息。这里我只添加了三个简单的方法,有需要的可以自己改造成更高级的用法。
public static class LogUtil
{
private const int LOG_CONTENT_MAX_LENGTH = 800;
static LogUtil()
{
string logDirPath = Path.Combine(Directory.GetCurrentDirectory(), "Log");
if (!Directory.Exists(logDirPath))
{
Directory.CreateDirectory(logDirPath);
}
}
private static string TestCurrentLogExists()
{
string logPath = Path.Combine(Directory.GetCurrentDirectory(), "Log", DateTime.Now.ToString("yyyy-MM-dd") + ".log");
if (!File.Exists(logPath))
{
File.Create(logPath).Close();
}
return logPath;
}
public static void Debug(string text)
{
WriteLog("Debug", text);
}
public static void Error(string text)
{
WriteLog("Error", text);
}
public static void Info(string text)
{
WriteLog("Info", text);
}
private static void WriteLog(string label, string log_content)
{
if (log_content.Length > LOG_CONTENT_MAX_LENGTH)
{
log_content = log_content.Substring(0, LOG_CONTENT_MAX_LENGTH);
}
var logPath = TestCurrentLogExists();
using (var fs = File.Open(logPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
{
fs.Position = fs.Length;
byte[] bytes = Encoding.UTF8.GetBytes($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")} {label} {log_content}{Environment.NewLine}");
fs.Write(bytes, 0, bytes.Length);
}
}
}
2、使用示例,这里去遍历一个空的List来触发一个异常,然后看看日志有没有帮我们记录下异常信息。
public partial class MainWindow : Window
{
private List<string> lists = null;
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
LogUtil.Info("这是一条普通的信息!!!");
LogUtil.Debug("这是一条普通的调试信息!!!");
try
{
foreach (var item in lists)
{
Console.WriteLine(item);
}
}
catch (Exception ex)
{
LogUtil.Error(ex.ToString());
throw;
}
}
}
3、运行结果,可以看到exe所在的目录下生成了一个Log文件夹,目录下也生成了一个以当日日期命名的.log文件


4、打开日志,我们可以看到异常的信息已经被记录到日志文件中,程序的哪个文件,哪个方法里的哪一行的什么异常导致的都已经清晰可见,这样就能方便定位的问题所在了

漫思

浙公网安备 33010602011771号