<appSettings>
<!-- 日志存放地址-->
<add key="LogPath" value="C:\Log\" />
<add key="windowName" value="LotInput"/>
<add key="windowMainName" value="IMS Ver.3.0.2.5"/>
</appSettings>
public class LogHelper
{
//日志文件目录路径 读取配置文件中的配置路径
public static string strDicPath = System.Configuration.ConfigurationManager.AppSettings["LogPath"];
static string strPath = string.Format("{0}", DateTime.Now.ToString("yyyyMMdd") + "log.txt");
//私有构造函数
static LogHelper()
{
//目录不存在自动创建
if (!Directory.Exists(strDicPath))
{
Directory.CreateDirectory(strDicPath);
}
}
/// <summary>
/// 写入日志信息
/// </summary>
/// <param name="strList"></param>
public static void WriteLog(params object[] strList)
{
if (strList.Length == 0)
{
return;
}
strPath = string.Format("{0}", DateTime.Now.ToString("yyyyMMdd") + "log.txt");
try
{
strPath = strDicPath + strPath;
}
#pragma warning disable CS0168 // 声明了变量“ex”,但从未使用过
catch (Exception ex)
#pragma warning restore CS0168 // 声明了变量“ex”,但从未使用过
{
strPath = "C:\\temp\\log\\";
strPath = strDicPath + strPath;
}
//自动创建文件 并追加信息
using (FileStream stream = new FileStream(strPath, FileMode.Append))
{
lock (stream)
{
StreamWriter writer = new StreamWriter(stream);
string content = "";
foreach (var str in strList)
{
content += DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":" + str;
}
//写入内容
writer.WriteLine(content);
//关闭并消费流写入文件
writer.Close();
writer.Dispose();
}
}
}
/// <summary>
/// 写入运行时错误
/// </summary>
/// <param name="strList"></param>
/// <param name="ex"></param>
public static void WriteErrLog(Exception ex, params object[] strList)
{
if (strList.Length == 0)
{
return;
}
strPath = string.Format("{0}", DateTime.Now.ToString("yyyyMMdd") + "log.txt");
try
{
strPath = strDicPath + strPath;
}
#pragma warning disable CS0168 // 声明了变量“ex1”,但从未使用过
catch (Exception ex1)
#pragma warning restore CS0168 // 声明了变量“ex1”,但从未使用过
{
strPath = "C:\\temp\\log\\";
strPath = strDicPath + strPath;
}
//自动创建文件 并追加信息
using (FileStream stream = new FileStream(strPath, FileMode.Append))
{
lock (stream)
{
StreamWriter writer = new StreamWriter(stream);
string content = "";
foreach (var str in strList)
{
content += DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ": 程序运行时错误" + str;
}
//写入内容
writer.WriteLine(content + ":" + ex.Source.ToString());
//关闭并消费流写入文件
writer.Close();
writer.Dispose();
}
}
}
}