using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Text;
namespace SnapshotWinFormsApp.Tools
{
///
/// 最基本的日志记录
///
public static class Logs
{
///
/// 获取记录文件路径
///
/// 日志文件路径
public static string Path()
{
var logPath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "logs");
if (!Directory.Exists(logPath))
{
Directory.CreateDirectory(logPath);
}
return logPath;
}
///
/// 错误信息记录
/// 请在所有的日志记录都无法使用的情况下使用下, 再使用本方法
///
/// 记录的内容
public static void Err(string msg)
{
string logPath = System.IO.Path.Combine(Path(), "err.log");
StackTrace trace = new StackTrace();
MethodBase methodBase = trace.GetFrame(1).GetMethod();
msg = $"方法 {methodBase.Name} 异常: {msg}";
Note(logPath, msg, true);
}
///
/// 错误信息记录
///
///
public static void Err(Exception e)
{
var msg = string.Empty;
try
{
msg = "Form: " + e?.InnerException?.Source + "\r\nMsg: " + e;
}
catch
{
msg = e.ToString();
}
Err(msg);
}
///
/// 记录警告信息
///
/// 内容
public static void Warning(string msg)
{
Note(System.IO.Path.Combine(Path() , "Warning.log"),msg,true);
}
///
/// 错误信息记录
///
/// 记录的内容
/// 文件名字
public static void Err(string msg, string name)
{
string path = System.IO.Path.Combine(Path(), DateTime.Now.ToString("yyyyMMdd") + "[" + name + "][err].log");
Note(path, msg, true);
}
///
/// 错误信息记录
///
/// 方法
/// 参数
/// 描述
public static void Err(string method, string param ,string discription)
{
string message = "方法: " + method + "\r\n参数:" + param + "\r\n描述:" + discription;
Err(message);
}
///
/// 日志记录
///
/// 记录的内容
public static void Note(string msg)
{
var logPath = System.IO.Path.Combine(Path(), "note.log");
Note(logPath, msg, true);
}
///
/// 日志记录
/// 日志自动记录调用者的名字
///
/// 记录的信息
public static void MethodNote(string msg)
{
StackTrace trace = new StackTrace();
MethodBase metbodBase = trace.GetFrame(1).GetMethod();
Note(System.IO.Path.Combine(Path(), "note.log"), metbodBase.Name + ":" + msg);
}
///
/// 日志记录
///
/// 日志文件路径
/// 内容
public static void Note(string path, string msg)
{
Note(path, msg, false);
}
///
/// 日志记录
///
/// 记录的内容
/// 日志文件路径
/// 是否格式化信息
public static void Note(string path, string msg, bool format)
{
try
{
if (!File.Exists(path))
{
FileStream fs = File.Create(path);
fs.Dispose();
fs.Close();
}
using (FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.Write))
{
StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
if (format) sw.WriteLine(DateTime.Now + " " + msg);
else sw.WriteLine(msg);
sw.Dispose();
sw.Close();
}
}
catch
{
}
}
}
}