说明
对于像windows服务运行中出现的一些异常信息,如何捕捉?做好的方法是写入日志,可以帮我们有效快速的进行修改。
调用
try
{
bool a = client.PlayTTSVhcNum(door2, VhcNum, "请车辆进厂去" + kuDes, 8000, 1);
if (a)
{
LogRecTxt.LogFileWrite("库房:" + kuDes + " 请车:" + VhcNum + " 进厂");
}
else
{
LogRecTxt.LogFileWrite("喇叭调用失败");
}
}
catch (Exception ex)
{
LogRecTxt.LogFileWrite(ex.Message);
}
工具类
在app.config配置:
<add key="FilePath" value="D:\Err.Log"/>
<add key="WSLogFilePath" value="D:\Err.Log\LBSql"/>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Configuration;
namespace MeasurementService.Comm
{
public class LogRecTxt
{
//日志txt文件路径及名称
private static string WSLogFilePath = ConfigurationManager.AppSettings["WSLogFilePath"];
private static string FilePath = ConfigurationManager.AppSettings["FilePath"];
private static string LogFilePath = "";
/// <summary>
/// 文件是否存在,如果不存在则创建
/// </summary>
public static void ExistsFile()
{
LogFilePath = WSLogFilePath + DateTime.Now.ToString("yyyyMM") + ".txt";
if (!Directory.Exists(FilePath))
{
Directory.CreateDirectory(FilePath);
}
if (!File.Exists(LogFilePath))
{
FileStream fs = File.Create(LogFilePath);
fs.Close();
}
}
/// <summary>
/// 读取文件内容并返回
/// </summary>
/// <returns>日志内容</returns>
public static string LogFileContent()
{
string str = "";
try
{
ExistsFile();
using (StreamReader sr = new StreamReader(LogFilePath, System.Text.Encoding.Default))
{
str = sr.ReadToEnd();
sr.Close();
}
}
catch { }
return str;
}
/// <summary>
/// 写日志
/// </summary>
/// <param name="log">要写的内容</param>
public static void LogFileWrite(string log)
{
try
{
ExistsFile();
using (StreamWriter sw = new StreamWriter(LogFilePath, true, System.Text.Encoding.Default))
{
sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") +": "+log);
sw.Close();
}
}
catch { }
}
}
}
结果
<add key="FilePath" value="D:\Err.Log"/>
<add key="WSLogFilePath" value="D:\Err.Log\LBSql"/>
每次填入异常信息时,会判断是否有此文件名,因为是加入了月份,所以每月的异常信息都会区分开,如下图所示,一个月一个异常txt文件,命名的规则就是(自定义+月份) .txt
|